hwmon: (acpi_power_meter) Fix acpi_bus_get_device() return value check
[linux-drm-fsl-dcu.git] / drivers / media / tuners / r820t.c
1 /*
2  * Rafael Micro R820T driver
3  *
4  * Copyright (C) 2013 Mauro Carvalho Chehab <mchehab@redhat.com>
5  *
6  * This driver was written from scratch, based on an existing driver
7  * that it is part of rtl-sdr git tree, released under GPLv2:
8  *      https://groups.google.com/forum/#!topic/ultra-cheap-sdr/Y3rBEOFtHug
9  *      https://github.com/n1gp/gr-baz
10  *
11  * From what I understood from the threads, the original driver was converted
12  * to userspace from a Realtek tree. I couldn't find the original tree.
13  * However, the original driver look awkward on my eyes. So, I decided to
14  * write a new version from it from the scratch, while trying to reproduce
15  * everything found there.
16  *
17  * TODO:
18  *      After locking, the original driver seems to have some routines to
19  *              improve reception. This was not implemented here yet.
20  *
21  *      RF Gain set/get is not implemented.
22  *
23  *    This program is free software; you can redistribute it and/or modify
24  *    it under the terms of the GNU General Public License as published by
25  *    the Free Software Foundation; either version 2 of the License, or
26  *    (at your option) any later version.
27  *
28  *    This program is distributed in the hope that it will be useful,
29  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
30  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31  *    GNU General Public License for more details.
32  *
33  */
34
35 #include <linux/videodev2.h>
36 #include <linux/mutex.h>
37 #include <linux/slab.h>
38 #include <linux/bitrev.h>
39
40 #include "tuner-i2c.h"
41 #include "r820t.h"
42
43 /*
44  * FIXME: I think that there are only 32 registers, but better safe than
45  *        sorry. After finishing the driver, we may review it.
46  */
47 #define REG_SHADOW_START        5
48 #define NUM_REGS                27
49 #define NUM_IMR                 5
50 #define IMR_TRIAL               9
51
52 #define VER_NUM  49
53
54 static int debug;
55 module_param(debug, int, 0644);
56 MODULE_PARM_DESC(debug, "enable verbose debug messages");
57
58 static int no_imr_cal;
59 module_param(no_imr_cal, int, 0444);
60 MODULE_PARM_DESC(no_imr_cal, "Disable IMR calibration at module init");
61
62
63 /*
64  * enums and structures
65  */
66
67 enum xtal_cap_value {
68         XTAL_LOW_CAP_30P = 0,
69         XTAL_LOW_CAP_20P,
70         XTAL_LOW_CAP_10P,
71         XTAL_LOW_CAP_0P,
72         XTAL_HIGH_CAP_0P
73 };
74
75 struct r820t_sect_type {
76         u8      phase_y;
77         u8      gain_x;
78         u16     value;
79 };
80
81 struct r820t_priv {
82         struct list_head                hybrid_tuner_instance_list;
83         const struct r820t_config       *cfg;
84         struct tuner_i2c_props          i2c_props;
85         struct mutex                    lock;
86
87         u8                              regs[NUM_REGS];
88         u8                              buf[NUM_REGS + 1];
89         enum xtal_cap_value             xtal_cap_sel;
90         u16                             pll;    /* kHz */
91         u32                             int_freq;
92         u8                              fil_cal_code;
93         bool                            imr_done;
94         bool                            has_lock;
95         bool                            init_done;
96         struct r820t_sect_type          imr_data[NUM_IMR];
97
98         /* Store current mode */
99         u32                             delsys;
100         enum v4l2_tuner_type            type;
101         v4l2_std_id                     std;
102         u32                             bw;     /* in MHz */
103 };
104
105 struct r820t_freq_range {
106         u32     freq;
107         u8      open_d;
108         u8      rf_mux_ploy;
109         u8      tf_c;
110         u8      xtal_cap20p;
111         u8      xtal_cap10p;
112         u8      xtal_cap0p;
113         u8      imr_mem;                /* Not used, currently */
114 };
115
116 #define VCO_POWER_REF   0x02
117 #define DIP_FREQ        32000000
118
119 /*
120  * Static constants
121  */
122
123 static LIST_HEAD(hybrid_tuner_instance_list);
124 static DEFINE_MUTEX(r820t_list_mutex);
125
126 /* Those initial values start from REG_SHADOW_START */
127 static const u8 r820t_init_array[NUM_REGS] = {
128         0x83, 0x32, 0x75,                       /* 05 to 07 */
129         0xc0, 0x40, 0xd6, 0x6c,                 /* 08 to 0b */
130         0xf5, 0x63, 0x75, 0x68,                 /* 0c to 0f */
131         0x6c, 0x83, 0x80, 0x00,                 /* 10 to 13 */
132         0x0f, 0x00, 0xc0, 0x30,                 /* 14 to 17 */
133         0x48, 0xcc, 0x60, 0x00,                 /* 18 to 1b */
134         0x54, 0xae, 0x4a, 0xc0                  /* 1c to 1f */
135 };
136
137 /* Tuner frequency ranges */
138 static const struct r820t_freq_range freq_ranges[] = {
139         {
140                 .freq = 0,
141                 .open_d = 0x08,         /* low */
142                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
143                 .tf_c = 0xdf,           /* R27[7:0]  band2,band0 */
144                 .xtal_cap20p = 0x02,    /* R16[1:0]  20pF (10)   */
145                 .xtal_cap10p = 0x01,
146                 .xtal_cap0p = 0x00,
147                 .imr_mem = 0,
148         }, {
149                 .freq = 50,             /* Start freq, in MHz */
150                 .open_d = 0x08,         /* low */
151                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
152                 .tf_c = 0xbe,           /* R27[7:0]  band4,band1  */
153                 .xtal_cap20p = 0x02,    /* R16[1:0]  20pF (10)   */
154                 .xtal_cap10p = 0x01,
155                 .xtal_cap0p = 0x00,
156                 .imr_mem = 0,
157         }, {
158                 .freq = 55,             /* Start freq, in MHz */
159                 .open_d = 0x08,         /* low */
160                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
161                 .tf_c = 0x8b,           /* R27[7:0]  band7,band4 */
162                 .xtal_cap20p = 0x02,    /* R16[1:0]  20pF (10)   */
163                 .xtal_cap10p = 0x01,
164                 .xtal_cap0p = 0x00,
165                 .imr_mem = 0,
166         }, {
167                 .freq = 60,             /* Start freq, in MHz */
168                 .open_d = 0x08,         /* low */
169                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
170                 .tf_c = 0x7b,           /* R27[7:0]  band8,band4 */
171                 .xtal_cap20p = 0x02,    /* R16[1:0]  20pF (10)   */
172                 .xtal_cap10p = 0x01,
173                 .xtal_cap0p = 0x00,
174                 .imr_mem = 0,
175         }, {
176                 .freq = 65,             /* Start freq, in MHz */
177                 .open_d = 0x08,         /* low */
178                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
179                 .tf_c = 0x69,           /* R27[7:0]  band9,band6 */
180                 .xtal_cap20p = 0x02,    /* R16[1:0]  20pF (10)   */
181                 .xtal_cap10p = 0x01,
182                 .xtal_cap0p = 0x00,
183                 .imr_mem = 0,
184         }, {
185                 .freq = 70,             /* Start freq, in MHz */
186                 .open_d = 0x08,         /* low */
187                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
188                 .tf_c = 0x58,           /* R27[7:0]  band10,band7 */
189                 .xtal_cap20p = 0x02,    /* R16[1:0]  20pF (10)   */
190                 .xtal_cap10p = 0x01,
191                 .xtal_cap0p = 0x00,
192                 .imr_mem = 0,
193         }, {
194                 .freq = 75,             /* Start freq, in MHz */
195                 .open_d = 0x00,         /* high */
196                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
197                 .tf_c = 0x44,           /* R27[7:0]  band11,band11 */
198                 .xtal_cap20p = 0x02,    /* R16[1:0]  20pF (10)   */
199                 .xtal_cap10p = 0x01,
200                 .xtal_cap0p = 0x00,
201                 .imr_mem = 0,
202         }, {
203                 .freq = 80,             /* Start freq, in MHz */
204                 .open_d = 0x00,         /* high */
205                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
206                 .tf_c = 0x44,           /* R27[7:0]  band11,band11 */
207                 .xtal_cap20p = 0x02,    /* R16[1:0]  20pF (10)   */
208                 .xtal_cap10p = 0x01,
209                 .xtal_cap0p = 0x00,
210                 .imr_mem = 0,
211         }, {
212                 .freq = 90,             /* Start freq, in MHz */
213                 .open_d = 0x00,         /* high */
214                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
215                 .tf_c = 0x34,           /* R27[7:0]  band12,band11 */
216                 .xtal_cap20p = 0x01,    /* R16[1:0]  10pF (01)   */
217                 .xtal_cap10p = 0x01,
218                 .xtal_cap0p = 0x00,
219                 .imr_mem = 0,
220         }, {
221                 .freq = 100,            /* Start freq, in MHz */
222                 .open_d = 0x00,         /* high */
223                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
224                 .tf_c = 0x34,           /* R27[7:0]  band12,band11 */
225                 .xtal_cap20p = 0x01,    /* R16[1:0]  10pF (01)    */
226                 .xtal_cap10p = 0x01,
227                 .xtal_cap0p = 0x00,
228                 .imr_mem = 0,
229         }, {
230                 .freq = 110,            /* Start freq, in MHz */
231                 .open_d = 0x00,         /* high */
232                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
233                 .tf_c = 0x24,           /* R27[7:0]  band13,band11 */
234                 .xtal_cap20p = 0x01,    /* R16[1:0]  10pF (01)   */
235                 .xtal_cap10p = 0x01,
236                 .xtal_cap0p = 0x00,
237                 .imr_mem = 1,
238         }, {
239                 .freq = 120,            /* Start freq, in MHz */
240                 .open_d = 0x00,         /* high */
241                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
242                 .tf_c = 0x24,           /* R27[7:0]  band13,band11 */
243                 .xtal_cap20p = 0x01,    /* R16[1:0]  10pF (01)   */
244                 .xtal_cap10p = 0x01,
245                 .xtal_cap0p = 0x00,
246                 .imr_mem = 1,
247         }, {
248                 .freq = 140,            /* Start freq, in MHz */
249                 .open_d = 0x00,         /* high */
250                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
251                 .tf_c = 0x14,           /* R27[7:0]  band14,band11 */
252                 .xtal_cap20p = 0x01,    /* R16[1:0]  10pF (01)   */
253                 .xtal_cap10p = 0x01,
254                 .xtal_cap0p = 0x00,
255                 .imr_mem = 1,
256         }, {
257                 .freq = 180,            /* Start freq, in MHz */
258                 .open_d = 0x00,         /* high */
259                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
260                 .tf_c = 0x13,           /* R27[7:0]  band14,band12 */
261                 .xtal_cap20p = 0x00,    /* R16[1:0]  0pF (00)   */
262                 .xtal_cap10p = 0x00,
263                 .xtal_cap0p = 0x00,
264                 .imr_mem = 1,
265         }, {
266                 .freq = 220,            /* Start freq, in MHz */
267                 .open_d = 0x00,         /* high */
268                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
269                 .tf_c = 0x13,           /* R27[7:0]  band14,band12 */
270                 .xtal_cap20p = 0x00,    /* R16[1:0]  0pF (00)   */
271                 .xtal_cap10p = 0x00,
272                 .xtal_cap0p = 0x00,
273                 .imr_mem = 2,
274         }, {
275                 .freq = 250,            /* Start freq, in MHz */
276                 .open_d = 0x00,         /* high */
277                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
278                 .tf_c = 0x11,           /* R27[7:0]  highest,highest */
279                 .xtal_cap20p = 0x00,    /* R16[1:0]  0pF (00)   */
280                 .xtal_cap10p = 0x00,
281                 .xtal_cap0p = 0x00,
282                 .imr_mem = 2,
283         }, {
284                 .freq = 280,            /* Start freq, in MHz */
285                 .open_d = 0x00,         /* high */
286                 .rf_mux_ploy = 0x02,    /* R26[7:6]=0 (LPF)  R26[1:0]=2 (low) */
287                 .tf_c = 0x00,           /* R27[7:0]  highest,highest */
288                 .xtal_cap20p = 0x00,    /* R16[1:0]  0pF (00)   */
289                 .xtal_cap10p = 0x00,
290                 .xtal_cap0p = 0x00,
291                 .imr_mem = 2,
292         }, {
293                 .freq = 310,            /* Start freq, in MHz */
294                 .open_d = 0x00,         /* high */
295                 .rf_mux_ploy = 0x41,    /* R26[7:6]=1 (bypass)  R26[1:0]=1 (middle) */
296                 .tf_c = 0x00,           /* R27[7:0]  highest,highest */
297                 .xtal_cap20p = 0x00,    /* R16[1:0]  0pF (00)   */
298                 .xtal_cap10p = 0x00,
299                 .xtal_cap0p = 0x00,
300                 .imr_mem = 2,
301         }, {
302                 .freq = 450,            /* Start freq, in MHz */
303                 .open_d = 0x00,         /* high */
304                 .rf_mux_ploy = 0x41,    /* R26[7:6]=1 (bypass)  R26[1:0]=1 (middle) */
305                 .tf_c = 0x00,           /* R27[7:0]  highest,highest */
306                 .xtal_cap20p = 0x00,    /* R16[1:0]  0pF (00)   */
307                 .xtal_cap10p = 0x00,
308                 .xtal_cap0p = 0x00,
309                 .imr_mem = 3,
310         }, {
311                 .freq = 588,            /* Start freq, in MHz */
312                 .open_d = 0x00,         /* high */
313                 .rf_mux_ploy = 0x40,    /* R26[7:6]=1 (bypass)  R26[1:0]=0 (highest) */
314                 .tf_c = 0x00,           /* R27[7:0]  highest,highest */
315                 .xtal_cap20p = 0x00,    /* R16[1:0]  0pF (00)   */
316                 .xtal_cap10p = 0x00,
317                 .xtal_cap0p = 0x00,
318                 .imr_mem = 3,
319         }, {
320                 .freq = 650,            /* Start freq, in MHz */
321                 .open_d = 0x00,         /* high */
322                 .rf_mux_ploy = 0x40,    /* R26[7:6]=1 (bypass)  R26[1:0]=0 (highest) */
323                 .tf_c = 0x00,           /* R27[7:0]  highest,highest */
324                 .xtal_cap20p = 0x00,    /* R16[1:0]  0pF (00)   */
325                 .xtal_cap10p = 0x00,
326                 .xtal_cap0p = 0x00,
327                 .imr_mem = 4,
328         }
329 };
330
331 static int r820t_xtal_capacitor[][2] = {
332         { 0x0b, XTAL_LOW_CAP_30P },
333         { 0x02, XTAL_LOW_CAP_20P },
334         { 0x01, XTAL_LOW_CAP_10P },
335         { 0x00, XTAL_LOW_CAP_0P  },
336         { 0x10, XTAL_HIGH_CAP_0P },
337 };
338
339 /*
340  * measured with a Racal 6103E GSM test set at 928 MHz with -60 dBm
341  * input power, for raw results see:
342  *      http://steve-m.de/projects/rtl-sdr/gain_measurement/r820t/
343  */
344
345 static const int r820t_lna_gain_steps[]  = {
346         0, 9, 13, 40, 38, 13, 31, 22, 26, 31, 26, 14, 19, 5, 35, 13
347 };
348
349 static const int r820t_mixer_gain_steps[]  = {
350         0, 5, 10, 10, 19, 9, 10, 25, 17, 10, 8, 16, 13, 6, 3, -8
351 };
352
353 /*
354  * I2C read/write code and shadow registers logic
355  */
356 static void shadow_store(struct r820t_priv *priv, u8 reg, const u8 *val,
357                          int len)
358 {
359         int r = reg - REG_SHADOW_START;
360
361         if (r < 0) {
362                 len += r;
363                 r = 0;
364         }
365         if (len <= 0)
366                 return;
367         if (len > NUM_REGS - r)
368                 len = NUM_REGS - r;
369
370         tuner_dbg("%s: prev  reg=%02x len=%d: %*ph\n",
371                   __func__, r + REG_SHADOW_START, len, len, val);
372
373         memcpy(&priv->regs[r], val, len);
374 }
375
376 static int r820t_write(struct r820t_priv *priv, u8 reg, const u8 *val,
377                        int len)
378 {
379         int rc, size, pos = 0;
380
381         /* Store the shadow registers */
382         shadow_store(priv, reg, val, len);
383
384         do {
385                 if (len > priv->cfg->max_i2c_msg_len - 1)
386                         size = priv->cfg->max_i2c_msg_len - 1;
387                 else
388                         size = len;
389
390                 /* Fill I2C buffer */
391                 priv->buf[0] = reg;
392                 memcpy(&priv->buf[1], &val[pos], size);
393
394                 rc = tuner_i2c_xfer_send(&priv->i2c_props, priv->buf, size + 1);
395                 if (rc != size + 1) {
396                         tuner_info("%s: i2c wr failed=%d reg=%02x len=%d: %*ph\n",
397                                    __func__, rc, reg, size, size, &priv->buf[1]);
398                         if (rc < 0)
399                                 return rc;
400                         return -EREMOTEIO;
401                 }
402                 tuner_dbg("%s: i2c wr reg=%02x len=%d: %*ph\n",
403                           __func__, reg, size, size, &priv->buf[1]);
404
405                 reg += size;
406                 len -= size;
407                 pos += size;
408         } while (len > 0);
409
410         return 0;
411 }
412
413 static int r820t_write_reg(struct r820t_priv *priv, u8 reg, u8 val)
414 {
415         return r820t_write(priv, reg, &val, 1);
416 }
417
418 static int r820t_read_cache_reg(struct r820t_priv *priv, int reg)
419 {
420         reg -= REG_SHADOW_START;
421
422         if (reg >= 0 && reg < NUM_REGS)
423                 return priv->regs[reg];
424         else
425                 return -EINVAL;
426 }
427
428 static int r820t_write_reg_mask(struct r820t_priv *priv, u8 reg, u8 val,
429                                 u8 bit_mask)
430 {
431         int rc = r820t_read_cache_reg(priv, reg);
432
433         if (rc < 0)
434                 return rc;
435
436         val = (rc & ~bit_mask) | (val & bit_mask);
437
438         return r820t_write(priv, reg, &val, 1);
439 }
440
441 static int r820t_read(struct r820t_priv *priv, u8 reg, u8 *val, int len)
442 {
443         int rc, i;
444         u8 *p = &priv->buf[1];
445
446         priv->buf[0] = reg;
447
448         rc = tuner_i2c_xfer_send_recv(&priv->i2c_props, priv->buf, 1, p, len);
449         if (rc != len) {
450                 tuner_info("%s: i2c rd failed=%d reg=%02x len=%d: %*ph\n",
451                            __func__, rc, reg, len, len, p);
452                 if (rc < 0)
453                         return rc;
454                 return -EREMOTEIO;
455         }
456
457         /* Copy data to the output buffer */
458         for (i = 0; i < len; i++)
459                 val[i] = bitrev8(p[i]);
460
461         tuner_dbg("%s: i2c rd reg=%02x len=%d: %*ph\n",
462                   __func__, reg, len, len, val);
463
464         return 0;
465 }
466
467 /*
468  * r820t tuning logic
469  */
470
471 static int r820t_set_mux(struct r820t_priv *priv, u32 freq)
472 {
473         const struct r820t_freq_range *range;
474         int i, rc;
475         u8 val, reg08, reg09;
476
477         /* Get the proper frequency range */
478         freq = freq / 1000000;
479         for (i = 0; i < ARRAY_SIZE(freq_ranges) - 1; i++) {
480                 if (freq < freq_ranges[i + 1].freq)
481                         break;
482         }
483         range = &freq_ranges[i];
484
485         tuner_dbg("set r820t range#%d for frequency %d MHz\n", i, freq);
486
487         /* Open Drain */
488         rc = r820t_write_reg_mask(priv, 0x17, range->open_d, 0x08);
489         if (rc < 0)
490                 return rc;
491
492         /* RF_MUX,Polymux */
493         rc = r820t_write_reg_mask(priv, 0x1a, range->rf_mux_ploy, 0xc3);
494         if (rc < 0)
495                 return rc;
496
497         /* TF BAND */
498         rc = r820t_write_reg(priv, 0x1b, range->tf_c);
499         if (rc < 0)
500                 return rc;
501
502         /* XTAL CAP & Drive */
503         switch (priv->xtal_cap_sel) {
504         case XTAL_LOW_CAP_30P:
505         case XTAL_LOW_CAP_20P:
506                 val = range->xtal_cap20p | 0x08;
507                 break;
508         case XTAL_LOW_CAP_10P:
509                 val = range->xtal_cap10p | 0x08;
510                 break;
511         case XTAL_HIGH_CAP_0P:
512                 val = range->xtal_cap0p | 0x00;
513                 break;
514         default:
515         case XTAL_LOW_CAP_0P:
516                 val = range->xtal_cap0p | 0x08;
517                 break;
518         }
519         rc = r820t_write_reg_mask(priv, 0x10, val, 0x0b);
520         if (rc < 0)
521                 return rc;
522
523         if (priv->imr_done) {
524                 reg08 = priv->imr_data[range->imr_mem].gain_x;
525                 reg09 = priv->imr_data[range->imr_mem].phase_y;
526         } else {
527                 reg08 = 0;
528                 reg09 = 0;
529         }
530         rc = r820t_write_reg_mask(priv, 0x08, reg08, 0x3f);
531         if (rc < 0)
532                 return rc;
533
534         rc = r820t_write_reg_mask(priv, 0x09, reg09, 0x3f);
535
536         return rc;
537 }
538
539 static int r820t_set_pll(struct r820t_priv *priv, enum v4l2_tuner_type type,
540                          u32 freq)
541 {
542         u32 vco_freq;
543         int rc, i;
544         unsigned sleep_time = 10000;
545         u32 vco_fra;            /* VCO contribution by SDM (kHz) */
546         u32 vco_min  = 1770000;
547         u32 vco_max  = vco_min * 2;
548         u32 pll_ref;
549         u16 n_sdm = 2;
550         u16 sdm = 0;
551         u8 mix_div = 2;
552         u8 div_buf = 0;
553         u8 div_num = 0;
554         u8 refdiv2 = 0;
555         u8 ni, si, nint, vco_fine_tune, val;
556         u8 data[5];
557
558         /* Frequency in kHz */
559         freq = freq / 1000;
560         pll_ref = priv->cfg->xtal / 1000;
561
562 #if 0
563         /* Doesn't exist on rtl-sdk, and on field tests, caused troubles */
564         if ((priv->cfg->rafael_chip == CHIP_R620D) ||
565            (priv->cfg->rafael_chip == CHIP_R828D) ||
566            (priv->cfg->rafael_chip == CHIP_R828)) {
567                 /* ref set refdiv2, reffreq = Xtal/2 on ATV application */
568                 if (type != V4L2_TUNER_DIGITAL_TV) {
569                         pll_ref /= 2;
570                         refdiv2 = 0x10;
571                         sleep_time = 20000;
572                 }
573         } else {
574                 if (priv->cfg->xtal > 24000000) {
575                         pll_ref /= 2;
576                         refdiv2 = 0x10;
577                 }
578         }
579 #endif
580
581         rc = r820t_write_reg_mask(priv, 0x10, refdiv2, 0x10);
582         if (rc < 0)
583                 return rc;
584
585         /* set pll autotune = 128kHz */
586         rc = r820t_write_reg_mask(priv, 0x1a, 0x00, 0x0c);
587         if (rc < 0)
588                 return rc;
589
590         /* set VCO current = 100 */
591         rc = r820t_write_reg_mask(priv, 0x12, 0x80, 0xe0);
592         if (rc < 0)
593                 return rc;
594
595         /* Calculate divider */
596         while (mix_div <= 64) {
597                 if (((freq * mix_div) >= vco_min) &&
598                    ((freq * mix_div) < vco_max)) {
599                         div_buf = mix_div;
600                         while (div_buf > 2) {
601                                 div_buf = div_buf >> 1;
602                                 div_num++;
603                         }
604                         break;
605                 }
606                 mix_div = mix_div << 1;
607         }
608
609         rc = r820t_read(priv, 0x00, data, sizeof(data));
610         if (rc < 0)
611                 return rc;
612
613         vco_fine_tune = (data[4] & 0x30) >> 4;
614
615         if (vco_fine_tune > VCO_POWER_REF)
616                 div_num = div_num - 1;
617         else if (vco_fine_tune < VCO_POWER_REF)
618                 div_num = div_num + 1;
619
620         rc = r820t_write_reg_mask(priv, 0x10, div_num << 5, 0xe0);
621         if (rc < 0)
622                 return rc;
623
624         vco_freq = freq * mix_div;
625         nint = vco_freq / (2 * pll_ref);
626         vco_fra = vco_freq - 2 * pll_ref * nint;
627
628         /* boundary spur prevention */
629         if (vco_fra < pll_ref / 64) {
630                 vco_fra = 0;
631         } else if (vco_fra > pll_ref * 127 / 64) {
632                 vco_fra = 0;
633                 nint++;
634         } else if ((vco_fra > pll_ref * 127 / 128) && (vco_fra < pll_ref)) {
635                 vco_fra = pll_ref * 127 / 128;
636         } else if ((vco_fra > pll_ref) && (vco_fra < pll_ref * 129 / 128)) {
637                 vco_fra = pll_ref * 129 / 128;
638         }
639
640         if (nint > 63) {
641                 tuner_info("No valid PLL values for %u kHz!\n", freq);
642                 return -EINVAL;
643         }
644
645         ni = (nint - 13) / 4;
646         si = nint - 4 * ni - 13;
647
648         rc = r820t_write_reg(priv, 0x14, ni + (si << 6));
649         if (rc < 0)
650                 return rc;
651
652         /* pw_sdm */
653         if (!vco_fra)
654                 val = 0x08;
655         else
656                 val = 0x00;
657
658         rc = r820t_write_reg_mask(priv, 0x12, val, 0x08);
659         if (rc < 0)
660                 return rc;
661
662         /* sdm calculator */
663         while (vco_fra > 1) {
664                 if (vco_fra > (2 * pll_ref / n_sdm)) {
665                         sdm = sdm + 32768 / (n_sdm / 2);
666                         vco_fra = vco_fra - 2 * pll_ref / n_sdm;
667                         if (n_sdm >= 0x8000)
668                                 break;
669                 }
670                 n_sdm = n_sdm << 1;
671         }
672
673         tuner_dbg("freq %d kHz, pll ref %d%s, sdm=0x%04x\n",
674                   freq, pll_ref, refdiv2 ? " / 2" : "", sdm);
675
676         rc = r820t_write_reg(priv, 0x16, sdm >> 8);
677         if (rc < 0)
678                 return rc;
679         rc = r820t_write_reg(priv, 0x15, sdm & 0xff);
680         if (rc < 0)
681                 return rc;
682
683         for (i = 0; i < 2; i++) {
684                 usleep_range(sleep_time, sleep_time + 1000);
685
686                 /* Check if PLL has locked */
687                 rc = r820t_read(priv, 0x00, data, 3);
688                 if (rc < 0)
689                         return rc;
690                 if (data[2] & 0x40)
691                         break;
692
693                 if (!i) {
694                         /* Didn't lock. Increase VCO current */
695                         rc = r820t_write_reg_mask(priv, 0x12, 0x60, 0xe0);
696                         if (rc < 0)
697                                 return rc;
698                 }
699         }
700
701         if (!(data[2] & 0x40)) {
702                 priv->has_lock = false;
703                 return 0;
704         }
705
706         priv->has_lock = true;
707         tuner_dbg("tuner has lock at frequency %d kHz\n", freq);
708
709         /* set pll autotune = 8kHz */
710         rc = r820t_write_reg_mask(priv, 0x1a, 0x08, 0x08);
711
712         return rc;
713 }
714
715 static int r820t_sysfreq_sel(struct r820t_priv *priv, u32 freq,
716                              enum v4l2_tuner_type type,
717                              v4l2_std_id std,
718                              u32 delsys)
719 {
720         int rc;
721         u8 mixer_top, lna_top, cp_cur, div_buf_cur, lna_vth_l, mixer_vth_l;
722         u8 air_cable1_in, cable2_in, pre_dect, lna_discharge, filter_cur;
723
724         tuner_dbg("adjusting tuner parameters for the standard\n");
725
726         switch (delsys) {
727         case SYS_DVBT:
728                 if ((freq == 506000000) || (freq == 666000000) ||
729                    (freq == 818000000)) {
730                         mixer_top = 0x14;       /* mixer top:14 , top-1, low-discharge */
731                         lna_top = 0xe5;         /* detect bw 3, lna top:4, predet top:2 */
732                         cp_cur = 0x28;          /* 101, 0.2 */
733                         div_buf_cur = 0x20;     /* 10, 200u */
734                 } else {
735                         mixer_top = 0x24;       /* mixer top:13 , top-1, low-discharge */
736                         lna_top = 0xe5;         /* detect bw 3, lna top:4, predet top:2 */
737                         cp_cur = 0x38;          /* 111, auto */
738                         div_buf_cur = 0x30;     /* 11, 150u */
739                 }
740                 lna_vth_l = 0x53;               /* lna vth 0.84 ,  vtl 0.64 */
741                 mixer_vth_l = 0x75;             /* mixer vth 1.04, vtl 0.84 */
742                 air_cable1_in = 0x00;
743                 cable2_in = 0x00;
744                 pre_dect = 0x40;
745                 lna_discharge = 14;
746                 filter_cur = 0x40;              /* 10, low */
747                 break;
748         case SYS_DVBT2:
749                 mixer_top = 0x24;       /* mixer top:13 , top-1, low-discharge */
750                 lna_top = 0xe5;         /* detect bw 3, lna top:4, predet top:2 */
751                 lna_vth_l = 0x53;       /* lna vth 0.84 ,  vtl 0.64 */
752                 mixer_vth_l = 0x75;     /* mixer vth 1.04, vtl 0.84 */
753                 air_cable1_in = 0x00;
754                 cable2_in = 0x00;
755                 pre_dect = 0x40;
756                 lna_discharge = 14;
757                 cp_cur = 0x38;          /* 111, auto */
758                 div_buf_cur = 0x30;     /* 11, 150u */
759                 filter_cur = 0x40;      /* 10, low */
760                 break;
761         case SYS_ISDBT:
762                 mixer_top = 0x24;       /* mixer top:13 , top-1, low-discharge */
763                 lna_top = 0xe5;         /* detect bw 3, lna top:4, predet top:2 */
764                 lna_vth_l = 0x75;       /* lna vth 1.04 ,  vtl 0.84 */
765                 mixer_vth_l = 0x75;     /* mixer vth 1.04, vtl 0.84 */
766                 air_cable1_in = 0x00;
767                 cable2_in = 0x00;
768                 pre_dect = 0x40;
769                 lna_discharge = 14;
770                 cp_cur = 0x38;          /* 111, auto */
771                 div_buf_cur = 0x30;     /* 11, 150u */
772                 filter_cur = 0x40;      /* 10, low */
773                 break;
774         default: /* DVB-T 8M */
775                 mixer_top = 0x24;       /* mixer top:13 , top-1, low-discharge */
776                 lna_top = 0xe5;         /* detect bw 3, lna top:4, predet top:2 */
777                 lna_vth_l = 0x53;       /* lna vth 0.84 ,  vtl 0.64 */
778                 mixer_vth_l = 0x75;     /* mixer vth 1.04, vtl 0.84 */
779                 air_cable1_in = 0x00;
780                 cable2_in = 0x00;
781                 pre_dect = 0x40;
782                 lna_discharge = 14;
783                 cp_cur = 0x38;          /* 111, auto */
784                 div_buf_cur = 0x30;     /* 11, 150u */
785                 filter_cur = 0x40;      /* 10, low */
786                 break;
787         }
788
789         if (priv->cfg->use_diplexer &&
790            ((priv->cfg->rafael_chip == CHIP_R820T) ||
791            (priv->cfg->rafael_chip == CHIP_R828S) ||
792            (priv->cfg->rafael_chip == CHIP_R820C))) {
793                 if (freq > DIP_FREQ)
794                         air_cable1_in = 0x00;
795                 else
796                         air_cable1_in = 0x60;
797                 cable2_in = 0x00;
798         }
799
800
801         if (priv->cfg->use_predetect) {
802                 rc = r820t_write_reg_mask(priv, 0x06, pre_dect, 0x40);
803                 if (rc < 0)
804                         return rc;
805         }
806
807         rc = r820t_write_reg_mask(priv, 0x1d, lna_top, 0xc7);
808         if (rc < 0)
809                 return rc;
810         rc = r820t_write_reg_mask(priv, 0x1c, mixer_top, 0xf8);
811         if (rc < 0)
812                 return rc;
813         rc = r820t_write_reg(priv, 0x0d, lna_vth_l);
814         if (rc < 0)
815                 return rc;
816         rc = r820t_write_reg(priv, 0x0e, mixer_vth_l);
817         if (rc < 0)
818                 return rc;
819
820         /* Air-IN only for Astrometa */
821         rc = r820t_write_reg_mask(priv, 0x05, air_cable1_in, 0x60);
822         if (rc < 0)
823                 return rc;
824         rc = r820t_write_reg_mask(priv, 0x06, cable2_in, 0x08);
825         if (rc < 0)
826                 return rc;
827
828         rc = r820t_write_reg_mask(priv, 0x11, cp_cur, 0x38);
829         if (rc < 0)
830                 return rc;
831         rc = r820t_write_reg_mask(priv, 0x17, div_buf_cur, 0x30);
832         if (rc < 0)
833                 return rc;
834         rc = r820t_write_reg_mask(priv, 0x0a, filter_cur, 0x60);
835         if (rc < 0)
836                 return rc;
837         /*
838          * Original driver initializes regs 0x05 and 0x06 with the
839          * same value again on this point. Probably, it is just an
840          * error there
841          */
842
843         /*
844          * Set LNA
845          */
846
847         tuner_dbg("adjusting LNA parameters\n");
848         if (type != V4L2_TUNER_ANALOG_TV) {
849                 /* LNA TOP: lowest */
850                 rc = r820t_write_reg_mask(priv, 0x1d, 0, 0x38);
851                 if (rc < 0)
852                         return rc;
853
854                 /* 0: normal mode */
855                 rc = r820t_write_reg_mask(priv, 0x1c, 0, 0x04);
856                 if (rc < 0)
857                         return rc;
858
859                 /* 0: PRE_DECT off */
860                 rc = r820t_write_reg_mask(priv, 0x06, 0, 0x40);
861                 if (rc < 0)
862                         return rc;
863
864                 /* agc clk 250hz */
865                 rc = r820t_write_reg_mask(priv, 0x1a, 0x30, 0x30);
866                 if (rc < 0)
867                         return rc;
868
869                 msleep(250);
870
871                 /* write LNA TOP = 3 */
872                 rc = r820t_write_reg_mask(priv, 0x1d, 0x18, 0x38);
873                 if (rc < 0)
874                         return rc;
875
876                 /*
877                  * write discharge mode
878                  * FIXME: IMHO, the mask here is wrong, but it matches
879                  * what's there at the original driver
880                  */
881                 rc = r820t_write_reg_mask(priv, 0x1c, mixer_top, 0x04);
882                 if (rc < 0)
883                         return rc;
884
885                 /* LNA discharge current */
886                 rc = r820t_write_reg_mask(priv, 0x1e, lna_discharge, 0x1f);
887                 if (rc < 0)
888                         return rc;
889
890                 /* agc clk 60hz */
891                 rc = r820t_write_reg_mask(priv, 0x1a, 0x20, 0x30);
892                 if (rc < 0)
893                         return rc;
894         } else {
895                 /* PRE_DECT off */
896                 rc = r820t_write_reg_mask(priv, 0x06, 0, 0x40);
897                 if (rc < 0)
898                         return rc;
899
900                 /* write LNA TOP */
901                 rc = r820t_write_reg_mask(priv, 0x1d, lna_top, 0x38);
902                 if (rc < 0)
903                         return rc;
904
905                 /*
906                  * write discharge mode
907                  * FIXME: IMHO, the mask here is wrong, but it matches
908                  * what's there at the original driver
909                  */
910                 rc = r820t_write_reg_mask(priv, 0x1c, mixer_top, 0x04);
911                 if (rc < 0)
912                         return rc;
913
914                 /* LNA discharge current */
915                 rc = r820t_write_reg_mask(priv, 0x1e, lna_discharge, 0x1f);
916                 if (rc < 0)
917                         return rc;
918
919                 /* agc clk 1Khz, external det1 cap 1u */
920                 rc = r820t_write_reg_mask(priv, 0x1a, 0x00, 0x30);
921                 if (rc < 0)
922                         return rc;
923
924                 rc = r820t_write_reg_mask(priv, 0x10, 0x00, 0x04);
925                 if (rc < 0)
926                         return rc;
927          }
928          return 0;
929 }
930
931 static int r820t_set_tv_standard(struct r820t_priv *priv,
932                                  unsigned bw,
933                                  enum v4l2_tuner_type type,
934                                  v4l2_std_id std, u32 delsys)
935
936 {
937         int rc, i;
938         u32 if_khz, filt_cal_lo;
939         u8 data[5], val;
940         u8 filt_gain, img_r, filt_q, hp_cor, ext_enable, loop_through;
941         u8 lt_att, flt_ext_widest, polyfil_cur;
942         bool need_calibration;
943
944         tuner_dbg("selecting the delivery system\n");
945
946         if (delsys == SYS_ISDBT) {
947                 if_khz = 4063;
948                 filt_cal_lo = 59000;
949                 filt_gain = 0x10;       /* +3db, 6mhz on */
950                 img_r = 0x00;           /* image negative */
951                 filt_q = 0x10;          /* r10[4]:low q(1'b1) */
952                 hp_cor = 0x6a;          /* 1.7m disable, +2cap, 1.25mhz */
953                 ext_enable = 0x40;      /* r30[6], ext enable; r30[5]:0 ext at lna max */
954                 loop_through = 0x00;    /* r5[7], lt on */
955                 lt_att = 0x00;          /* r31[7], lt att enable */
956                 flt_ext_widest = 0x00;  /* r15[7]: flt_ext_wide off */
957                 polyfil_cur = 0x60;     /* r25[6:5]:min */
958         } else {
959                 if (bw <= 6) {
960                         if_khz = 3570;
961                         filt_cal_lo = 56000;    /* 52000->56000 */
962                         filt_gain = 0x10;       /* +3db, 6mhz on */
963                         img_r = 0x00;           /* image negative */
964                         filt_q = 0x10;          /* r10[4]:low q(1'b1) */
965                         hp_cor = 0x6b;          /* 1.7m disable, +2cap, 1.0mhz */
966                         ext_enable = 0x60;      /* r30[6]=1 ext enable; r30[5]:1 ext at lna max-1 */
967                         loop_through = 0x00;    /* r5[7], lt on */
968                         lt_att = 0x00;          /* r31[7], lt att enable */
969                         flt_ext_widest = 0x00;  /* r15[7]: flt_ext_wide off */
970                         polyfil_cur = 0x60;     /* r25[6:5]:min */
971                 } else if (bw == 7) {
972 #if 0
973                         /*
974                          * There are two 7 MHz tables defined on the original
975                          * driver, but just the second one seems to be visible
976                          * by rtl2832. Keep this one here commented, as it
977                          * might be needed in the future
978                          */
979
980                         if_khz = 4070;
981                         filt_cal_lo = 60000;
982                         filt_gain = 0x10;       /* +3db, 6mhz on */
983                         img_r = 0x00;           /* image negative */
984                         filt_q = 0x10;          /* r10[4]:low q(1'b1) */
985                         hp_cor = 0x2b;          /* 1.7m disable, +1cap, 1.0mhz */
986                         ext_enable = 0x60;      /* r30[6]=1 ext enable; r30[5]:1 ext at lna max-1 */
987                         loop_through = 0x00;    /* r5[7], lt on */
988                         lt_att = 0x00;          /* r31[7], lt att enable */
989                         flt_ext_widest = 0x00;  /* r15[7]: flt_ext_wide off */
990                         polyfil_cur = 0x60;     /* r25[6:5]:min */
991 #endif
992                         /* 7 MHz, second table */
993                         if_khz = 4570;
994                         filt_cal_lo = 63000;
995                         filt_gain = 0x10;       /* +3db, 6mhz on */
996                         img_r = 0x00;           /* image negative */
997                         filt_q = 0x10;          /* r10[4]:low q(1'b1) */
998                         hp_cor = 0x2a;          /* 1.7m disable, +1cap, 1.25mhz */
999                         ext_enable = 0x60;      /* r30[6]=1 ext enable; r30[5]:1 ext at lna max-1 */
1000                         loop_through = 0x00;    /* r5[7], lt on */
1001                         lt_att = 0x00;          /* r31[7], lt att enable */
1002                         flt_ext_widest = 0x00;  /* r15[7]: flt_ext_wide off */
1003                         polyfil_cur = 0x60;     /* r25[6:5]:min */
1004                 } else {
1005                         if_khz = 4570;
1006                         filt_cal_lo = 68500;
1007                         filt_gain = 0x10;       /* +3db, 6mhz on */
1008                         img_r = 0x00;           /* image negative */
1009                         filt_q = 0x10;          /* r10[4]:low q(1'b1) */
1010                         hp_cor = 0x0b;          /* 1.7m disable, +0cap, 1.0mhz */
1011                         ext_enable = 0x60;      /* r30[6]=1 ext enable; r30[5]:1 ext at lna max-1 */
1012                         loop_through = 0x00;    /* r5[7], lt on */
1013                         lt_att = 0x00;          /* r31[7], lt att enable */
1014                         flt_ext_widest = 0x00;  /* r15[7]: flt_ext_wide off */
1015                         polyfil_cur = 0x60;     /* r25[6:5]:min */
1016                 }
1017         }
1018
1019         /* Initialize the shadow registers */
1020         memcpy(priv->regs, r820t_init_array, sizeof(r820t_init_array));
1021
1022         /* Init Flag & Xtal_check Result */
1023         if (priv->imr_done)
1024                 val = 1 | priv->xtal_cap_sel << 1;
1025         else
1026                 val = 0;
1027         rc = r820t_write_reg_mask(priv, 0x0c, val, 0x0f);
1028         if (rc < 0)
1029                 return rc;
1030
1031         /* version */
1032         rc = r820t_write_reg_mask(priv, 0x13, VER_NUM, 0x3f);
1033         if (rc < 0)
1034                 return rc;
1035
1036         /* for LT Gain test */
1037         if (type != V4L2_TUNER_ANALOG_TV) {
1038                 rc = r820t_write_reg_mask(priv, 0x1d, 0x00, 0x38);
1039                 if (rc < 0)
1040                         return rc;
1041                 usleep_range(1000, 2000);
1042         }
1043         priv->int_freq = if_khz * 1000;
1044
1045         /* Check if standard changed. If so, filter calibration is needed */
1046         if (type != priv->type)
1047                 need_calibration = true;
1048         else if ((type == V4L2_TUNER_ANALOG_TV) && (std != priv->std))
1049                 need_calibration = true;
1050         else if ((type == V4L2_TUNER_DIGITAL_TV) &&
1051                  ((delsys != priv->delsys) || bw != priv->bw))
1052                 need_calibration = true;
1053         else
1054                 need_calibration = false;
1055
1056         if (need_calibration) {
1057                 tuner_dbg("calibrating the tuner\n");
1058                 for (i = 0; i < 2; i++) {
1059                         /* Set filt_cap */
1060                         rc = r820t_write_reg_mask(priv, 0x0b, hp_cor, 0x60);
1061                         if (rc < 0)
1062                                 return rc;
1063
1064                         /* set cali clk =on */
1065                         rc = r820t_write_reg_mask(priv, 0x0f, 0x04, 0x04);
1066                         if (rc < 0)
1067                                 return rc;
1068
1069                         /* X'tal cap 0pF for PLL */
1070                         rc = r820t_write_reg_mask(priv, 0x10, 0x00, 0x03);
1071                         if (rc < 0)
1072                                 return rc;
1073
1074                         rc = r820t_set_pll(priv, type, filt_cal_lo * 1000);
1075                         if (rc < 0 || !priv->has_lock)
1076                                 return rc;
1077
1078                         /* Start Trigger */
1079                         rc = r820t_write_reg_mask(priv, 0x0b, 0x10, 0x10);
1080                         if (rc < 0)
1081                                 return rc;
1082
1083                         usleep_range(1000, 2000);
1084
1085                         /* Stop Trigger */
1086                         rc = r820t_write_reg_mask(priv, 0x0b, 0x00, 0x10);
1087                         if (rc < 0)
1088                                 return rc;
1089
1090                         /* set cali clk =off */
1091                         rc = r820t_write_reg_mask(priv, 0x0f, 0x00, 0x04);
1092                         if (rc < 0)
1093                                 return rc;
1094
1095                         /* Check if calibration worked */
1096                         rc = r820t_read(priv, 0x00, data, sizeof(data));
1097                         if (rc < 0)
1098                                 return rc;
1099
1100                         priv->fil_cal_code = data[4] & 0x0f;
1101                         if (priv->fil_cal_code && priv->fil_cal_code != 0x0f)
1102                                 break;
1103                 }
1104                 /* narrowest */
1105                 if (priv->fil_cal_code == 0x0f)
1106                         priv->fil_cal_code = 0;
1107         }
1108
1109         rc = r820t_write_reg_mask(priv, 0x0a,
1110                                   filt_q | priv->fil_cal_code, 0x1f);
1111         if (rc < 0)
1112                 return rc;
1113
1114         /* Set BW, Filter_gain, & HP corner */
1115         rc = r820t_write_reg_mask(priv, 0x0b, hp_cor, 0xef);
1116         if (rc < 0)
1117                 return rc;
1118
1119
1120         /* Set Img_R */
1121         rc = r820t_write_reg_mask(priv, 0x07, img_r, 0x80);
1122         if (rc < 0)
1123                 return rc;
1124
1125         /* Set filt_3dB, V6MHz */
1126         rc = r820t_write_reg_mask(priv, 0x06, filt_gain, 0x30);
1127         if (rc < 0)
1128                 return rc;
1129
1130         /* channel filter extension */
1131         rc = r820t_write_reg_mask(priv, 0x1e, ext_enable, 0x60);
1132         if (rc < 0)
1133                 return rc;
1134
1135         /* Loop through */
1136         rc = r820t_write_reg_mask(priv, 0x05, loop_through, 0x80);
1137         if (rc < 0)
1138                 return rc;
1139
1140         /* Loop through attenuation */
1141         rc = r820t_write_reg_mask(priv, 0x1f, lt_att, 0x80);
1142         if (rc < 0)
1143                 return rc;
1144
1145         /* filter extension widest */
1146         rc = r820t_write_reg_mask(priv, 0x0f, flt_ext_widest, 0x80);
1147         if (rc < 0)
1148                 return rc;
1149
1150         /* RF poly filter current */
1151         rc = r820t_write_reg_mask(priv, 0x19, polyfil_cur, 0x60);
1152         if (rc < 0)
1153                 return rc;
1154
1155         /* Store current standard. If it changes, re-calibrate the tuner */
1156         priv->delsys = delsys;
1157         priv->type = type;
1158         priv->std = std;
1159         priv->bw = bw;
1160
1161         return 0;
1162 }
1163
1164 static int r820t_read_gain(struct r820t_priv *priv)
1165 {
1166         u8 data[4];
1167         int rc;
1168
1169         rc = r820t_read(priv, 0x00, data, sizeof(data));
1170         if (rc < 0)
1171                 return rc;
1172
1173         return ((data[3] & 0x0f) << 1) + ((data[3] & 0xf0) >> 4);
1174 }
1175
1176 #if 0
1177 /* FIXME: This routine requires more testing */
1178 static int r820t_set_gain_mode(struct r820t_priv *priv,
1179                                bool set_manual_gain,
1180                                int gain)
1181 {
1182         int rc;
1183
1184         if (set_manual_gain) {
1185                 int i, total_gain = 0;
1186                 uint8_t mix_index = 0, lna_index = 0;
1187                 u8 data[4];
1188
1189                 /* LNA auto off */
1190                 rc = r820t_write_reg_mask(priv, 0x05, 0x10, 0x10);
1191                 if (rc < 0)
1192                         return rc;
1193
1194                  /* Mixer auto off */
1195                 rc = r820t_write_reg_mask(priv, 0x07, 0, 0x10);
1196                 if (rc < 0)
1197                         return rc;
1198
1199                 rc = r820t_read(priv, 0x00, data, sizeof(data));
1200                 if (rc < 0)
1201                         return rc;
1202
1203                 /* set fixed VGA gain for now (16.3 dB) */
1204                 rc = r820t_write_reg_mask(priv, 0x0c, 0x08, 0x9f);
1205                 if (rc < 0)
1206                         return rc;
1207
1208                 for (i = 0; i < 15; i++) {
1209                         if (total_gain >= gain)
1210                                 break;
1211
1212                         total_gain += r820t_lna_gain_steps[++lna_index];
1213
1214                         if (total_gain >= gain)
1215                                 break;
1216
1217                         total_gain += r820t_mixer_gain_steps[++mix_index];
1218                 }
1219
1220                 /* set LNA gain */
1221                 rc = r820t_write_reg_mask(priv, 0x05, lna_index, 0x0f);
1222                 if (rc < 0)
1223                         return rc;
1224
1225                 /* set Mixer gain */
1226                 rc = r820t_write_reg_mask(priv, 0x07, mix_index, 0x0f);
1227                 if (rc < 0)
1228                         return rc;
1229         } else {
1230                 /* LNA */
1231                 rc = r820t_write_reg_mask(priv, 0x05, 0, 0x10);
1232                 if (rc < 0)
1233                         return rc;
1234
1235                 /* Mixer */
1236                 rc = r820t_write_reg_mask(priv, 0x07, 0x10, 0x10);
1237                 if (rc < 0)
1238                         return rc;
1239
1240                 /* set fixed VGA gain for now (26.5 dB) */
1241                 rc = r820t_write_reg_mask(priv, 0x0c, 0x0b, 0x9f);
1242                 if (rc < 0)
1243                         return rc;
1244         }
1245
1246         return 0;
1247 }
1248 #endif
1249
1250 static int generic_set_freq(struct dvb_frontend *fe,
1251                             u32 freq /* in HZ */,
1252                             unsigned bw,
1253                             enum v4l2_tuner_type type,
1254                             v4l2_std_id std, u32 delsys)
1255 {
1256         struct r820t_priv               *priv = fe->tuner_priv;
1257         int                             rc = -EINVAL;
1258         u32                             lo_freq;
1259
1260         tuner_dbg("should set frequency to %d kHz, bw %d MHz\n",
1261                   freq / 1000, bw);
1262
1263         rc = r820t_set_tv_standard(priv, bw, type, std, delsys);
1264         if (rc < 0)
1265                 goto err;
1266
1267         if ((type == V4L2_TUNER_ANALOG_TV) && (std == V4L2_STD_SECAM_LC))
1268                 lo_freq = freq - priv->int_freq;
1269          else
1270                 lo_freq = freq + priv->int_freq;
1271
1272         rc = r820t_set_mux(priv, lo_freq);
1273         if (rc < 0)
1274                 goto err;
1275
1276         rc = r820t_set_pll(priv, type, lo_freq);
1277         if (rc < 0 || !priv->has_lock)
1278                 goto err;
1279
1280         rc = r820t_sysfreq_sel(priv, freq, type, std, delsys);
1281         if (rc < 0)
1282                 goto err;
1283
1284         tuner_dbg("%s: PLL locked on frequency %d Hz, gain=%d\n",
1285                   __func__, freq, r820t_read_gain(priv));
1286
1287 err:
1288
1289         if (rc < 0)
1290                 tuner_dbg("%s: failed=%d\n", __func__, rc);
1291         return rc;
1292 }
1293
1294 /*
1295  * r820t standby logic
1296  */
1297
1298 static int r820t_standby(struct r820t_priv *priv)
1299 {
1300         int rc;
1301
1302         /* If device was not initialized yet, don't need to standby */
1303         if (!priv->init_done)
1304                 return 0;
1305
1306         rc = r820t_write_reg(priv, 0x06, 0xb1);
1307         if (rc < 0)
1308                 return rc;
1309         rc = r820t_write_reg(priv, 0x05, 0x03);
1310         if (rc < 0)
1311                 return rc;
1312         rc = r820t_write_reg(priv, 0x07, 0x3a);
1313         if (rc < 0)
1314                 return rc;
1315         rc = r820t_write_reg(priv, 0x08, 0x40);
1316         if (rc < 0)
1317                 return rc;
1318         rc = r820t_write_reg(priv, 0x09, 0xc0);
1319         if (rc < 0)
1320                 return rc;
1321         rc = r820t_write_reg(priv, 0x0a, 0x36);
1322         if (rc < 0)
1323                 return rc;
1324         rc = r820t_write_reg(priv, 0x0c, 0x35);
1325         if (rc < 0)
1326                 return rc;
1327         rc = r820t_write_reg(priv, 0x0f, 0x68);
1328         if (rc < 0)
1329                 return rc;
1330         rc = r820t_write_reg(priv, 0x11, 0x03);
1331         if (rc < 0)
1332                 return rc;
1333         rc = r820t_write_reg(priv, 0x17, 0xf4);
1334         if (rc < 0)
1335                 return rc;
1336         rc = r820t_write_reg(priv, 0x19, 0x0c);
1337
1338         /* Force initial calibration */
1339         priv->type = -1;
1340
1341         return rc;
1342 }
1343
1344 /*
1345  * r820t device init logic
1346  */
1347
1348 static int r820t_xtal_check(struct r820t_priv *priv)
1349 {
1350         int rc, i;
1351         u8 data[3], val;
1352
1353         /* Initialize the shadow registers */
1354         memcpy(priv->regs, r820t_init_array, sizeof(r820t_init_array));
1355
1356         /* cap 30pF & Drive Low */
1357         rc = r820t_write_reg_mask(priv, 0x10, 0x0b, 0x0b);
1358         if (rc < 0)
1359                 return rc;
1360
1361         /* set pll autotune = 128kHz */
1362         rc = r820t_write_reg_mask(priv, 0x1a, 0x00, 0x0c);
1363         if (rc < 0)
1364                 return rc;
1365
1366         /* set manual initial reg = 111111;  */
1367         rc = r820t_write_reg_mask(priv, 0x13, 0x7f, 0x7f);
1368         if (rc < 0)
1369                 return rc;
1370
1371         /* set auto */
1372         rc = r820t_write_reg_mask(priv, 0x13, 0x00, 0x40);
1373         if (rc < 0)
1374                 return rc;
1375
1376         /* Try several xtal capacitor alternatives */
1377         for (i = 0; i < ARRAY_SIZE(r820t_xtal_capacitor); i++) {
1378                 rc = r820t_write_reg_mask(priv, 0x10,
1379                                           r820t_xtal_capacitor[i][0], 0x1b);
1380                 if (rc < 0)
1381                         return rc;
1382
1383                 usleep_range(5000, 6000);
1384
1385                 rc = r820t_read(priv, 0x00, data, sizeof(data));
1386                 if (rc < 0)
1387                         return rc;
1388                 if (!(data[2] & 0x40))
1389                         continue;
1390
1391                 val = data[2] & 0x3f;
1392
1393                 if (priv->cfg->xtal == 16000000 && (val > 29 || val < 23))
1394                         break;
1395
1396                 if (val != 0x3f)
1397                         break;
1398         }
1399
1400         if (i == ARRAY_SIZE(r820t_xtal_capacitor))
1401                 return -EINVAL;
1402
1403         return r820t_xtal_capacitor[i][1];
1404 }
1405
1406 static int r820t_imr_prepare(struct r820t_priv *priv)
1407 {
1408         int rc;
1409
1410         /* Initialize the shadow registers */
1411         memcpy(priv->regs, r820t_init_array, sizeof(r820t_init_array));
1412
1413         /* lna off (air-in off) */
1414         rc = r820t_write_reg_mask(priv, 0x05, 0x20, 0x20);
1415         if (rc < 0)
1416                 return rc;
1417
1418         /* mixer gain mode = manual */
1419         rc = r820t_write_reg_mask(priv, 0x07, 0, 0x10);
1420         if (rc < 0)
1421                 return rc;
1422
1423         /* filter corner = lowest */
1424         rc = r820t_write_reg_mask(priv, 0x0a, 0x0f, 0x0f);
1425         if (rc < 0)
1426                 return rc;
1427
1428         /* filter bw=+2cap, hp=5M */
1429         rc = r820t_write_reg_mask(priv, 0x0b, 0x60, 0x6f);
1430         if (rc < 0)
1431                 return rc;
1432
1433         /* adc=on, vga code mode, gain = 26.5dB   */
1434         rc = r820t_write_reg_mask(priv, 0x0c, 0x0b, 0x9f);
1435         if (rc < 0)
1436                 return rc;
1437
1438         /* ring clk = on */
1439         rc = r820t_write_reg_mask(priv, 0x0f, 0, 0x08);
1440         if (rc < 0)
1441                 return rc;
1442
1443         /* ring power = on */
1444         rc = r820t_write_reg_mask(priv, 0x18, 0x10, 0x10);
1445         if (rc < 0)
1446                 return rc;
1447
1448         /* from ring = ring pll in */
1449         rc = r820t_write_reg_mask(priv, 0x1c, 0x02, 0x02);
1450         if (rc < 0)
1451                 return rc;
1452
1453         /* sw_pdect = det3 */
1454         rc = r820t_write_reg_mask(priv, 0x1e, 0x80, 0x80);
1455         if (rc < 0)
1456                 return rc;
1457
1458         /* Set filt_3dB */
1459         rc = r820t_write_reg_mask(priv, 0x06, 0x20, 0x20);
1460
1461         return rc;
1462 }
1463
1464 static int r820t_multi_read(struct r820t_priv *priv)
1465 {
1466         int rc, i;
1467         u8 data[2], min = 0, max = 255, sum = 0;
1468
1469         usleep_range(5000, 6000);
1470
1471         for (i = 0; i < 6; i++) {
1472                 rc = r820t_read(priv, 0x00, data, sizeof(data));
1473                 if (rc < 0)
1474                         return rc;
1475
1476                 sum += data[1];
1477
1478                 if (data[1] < min)
1479                         min = data[1];
1480
1481                 if (data[1] > max)
1482                         max = data[1];
1483         }
1484         rc = sum - max - min;
1485
1486         return rc;
1487 }
1488
1489 static int r820t_imr_cross(struct r820t_priv *priv,
1490                            struct r820t_sect_type iq_point[3],
1491                            u8 *x_direct)
1492 {
1493         struct r820t_sect_type cross[5]; /* (0,0)(0,Q-1)(0,I-1)(Q-1,0)(I-1,0) */
1494         struct r820t_sect_type tmp;
1495         int i, rc;
1496         u8 reg08, reg09;
1497
1498         reg08 = r820t_read_cache_reg(priv, 8) & 0xc0;
1499         reg09 = r820t_read_cache_reg(priv, 9) & 0xc0;
1500
1501         tmp.gain_x = 0;
1502         tmp.phase_y = 0;
1503         tmp.value = 255;
1504
1505         for (i = 0; i < 5; i++) {
1506                 switch (i) {
1507                 case 0:
1508                         cross[i].gain_x  = reg08;
1509                         cross[i].phase_y = reg09;
1510                         break;
1511                 case 1:
1512                         cross[i].gain_x  = reg08;               /* 0 */
1513                         cross[i].phase_y = reg09 + 1;           /* Q-1 */
1514                         break;
1515                 case 2:
1516                         cross[i].gain_x  = reg08;               /* 0 */
1517                         cross[i].phase_y = (reg09 | 0x20) + 1;  /* I-1 */
1518                         break;
1519                 case 3:
1520                         cross[i].gain_x  = reg08 + 1;           /* Q-1 */
1521                         cross[i].phase_y = reg09;
1522                         break;
1523                 default:
1524                         cross[i].gain_x  = (reg08 | 0x20) + 1;  /* I-1 */
1525                         cross[i].phase_y = reg09;
1526                 }
1527
1528                 rc = r820t_write_reg(priv, 0x08, cross[i].gain_x);
1529                 if (rc < 0)
1530                         return rc;
1531
1532                 rc = r820t_write_reg(priv, 0x09, cross[i].phase_y);
1533                 if (rc < 0)
1534                         return rc;
1535
1536                 rc = r820t_multi_read(priv);
1537                 if (rc < 0)
1538                         return rc;
1539
1540                 cross[i].value = rc;
1541
1542                 if (cross[i].value < tmp.value)
1543                         memcpy(&tmp, &cross[i], sizeof(tmp));
1544         }
1545
1546         if ((tmp.phase_y & 0x1f) == 1) {        /* y-direction */
1547                 *x_direct = 0;
1548
1549                 iq_point[0] = cross[0];
1550                 iq_point[1] = cross[1];
1551                 iq_point[2] = cross[2];
1552         } else {                                /* (0,0) or x-direction */
1553                 *x_direct = 1;
1554
1555                 iq_point[0] = cross[0];
1556                 iq_point[1] = cross[3];
1557                 iq_point[2] = cross[4];
1558         }
1559         return 0;
1560 }
1561
1562 static void r820t_compre_cor(struct r820t_sect_type iq[3])
1563 {
1564         int i;
1565
1566         for (i = 3; i > 0; i--) {
1567                 if (iq[0].value > iq[i - 1].value)
1568                         swap(iq[0], iq[i - 1]);
1569         }
1570 }
1571
1572 static int r820t_compre_step(struct r820t_priv *priv,
1573                              struct r820t_sect_type iq[3], u8 reg)
1574 {
1575         int rc;
1576         struct r820t_sect_type tmp;
1577
1578         /*
1579          * Purpose: if (Gain<9 or Phase<9), Gain+1 or Phase+1 and compare
1580          * with min value:
1581          *  new < min => update to min and continue
1582          *  new > min => Exit
1583          */
1584
1585         /* min value already saved in iq[0] */
1586         tmp.phase_y = iq[0].phase_y;
1587         tmp.gain_x  = iq[0].gain_x;
1588
1589         while (((tmp.gain_x & 0x1f) < IMR_TRIAL) &&
1590               ((tmp.phase_y & 0x1f) < IMR_TRIAL)) {
1591                 if (reg == 0x08)
1592                         tmp.gain_x++;
1593                 else
1594                         tmp.phase_y++;
1595
1596                 rc = r820t_write_reg(priv, 0x08, tmp.gain_x);
1597                 if (rc < 0)
1598                         return rc;
1599
1600                 rc = r820t_write_reg(priv, 0x09, tmp.phase_y);
1601                 if (rc < 0)
1602                         return rc;
1603
1604                 rc = r820t_multi_read(priv);
1605                 if (rc < 0)
1606                         return rc;
1607                 tmp.value = rc;
1608
1609                 if (tmp.value <= iq[0].value) {
1610                         iq[0].gain_x  = tmp.gain_x;
1611                         iq[0].phase_y = tmp.phase_y;
1612                         iq[0].value   = tmp.value;
1613                 } else {
1614                         return 0;
1615                 }
1616
1617         }
1618
1619         return 0;
1620 }
1621
1622 static int r820t_iq_tree(struct r820t_priv *priv,
1623                          struct r820t_sect_type iq[3],
1624                          u8 fix_val, u8 var_val, u8 fix_reg)
1625 {
1626         int rc, i;
1627         u8 tmp, var_reg;
1628
1629         /*
1630          * record IMC results by input gain/phase location then adjust
1631          * gain or phase positive 1 step and negtive 1 step,
1632          * both record results
1633          */
1634
1635         if (fix_reg == 0x08)
1636                 var_reg = 0x09;
1637         else
1638                 var_reg = 0x08;
1639
1640         for (i = 0; i < 3; i++) {
1641                 rc = r820t_write_reg(priv, fix_reg, fix_val);
1642                 if (rc < 0)
1643                         return rc;
1644
1645                 rc = r820t_write_reg(priv, var_reg, var_val);
1646                 if (rc < 0)
1647                         return rc;
1648
1649                 rc = r820t_multi_read(priv);
1650                 if (rc < 0)
1651                         return rc;
1652                 iq[i].value = rc;
1653
1654                 if (fix_reg == 0x08) {
1655                         iq[i].gain_x  = fix_val;
1656                         iq[i].phase_y = var_val;
1657                 } else {
1658                         iq[i].phase_y = fix_val;
1659                         iq[i].gain_x  = var_val;
1660                 }
1661
1662                 if (i == 0) {  /* try right-side point */
1663                         var_val++;
1664                 } else if (i == 1) { /* try left-side point */
1665                          /* if absolute location is 1, change I/Q direction */
1666                         if ((var_val & 0x1f) < 0x02) {
1667                                 tmp = 2 - (var_val & 0x1f);
1668
1669                                 /* b[5]:I/Q selection. 0:Q-path, 1:I-path */
1670                                 if (var_val & 0x20) {
1671                                         var_val &= 0xc0;
1672                                         var_val |= tmp;
1673                                 } else {
1674                                         var_val |= 0x20 | tmp;
1675                                 }
1676                         } else {
1677                                 var_val -= 2;
1678                         }
1679                 }
1680         }
1681
1682         return 0;
1683 }
1684
1685 static int r820t_section(struct r820t_priv *priv,
1686                          struct r820t_sect_type *iq_point)
1687 {
1688         int rc;
1689         struct r820t_sect_type compare_iq[3], compare_bet[3];
1690
1691         /* Try X-1 column and save min result to compare_bet[0] */
1692         if (!(iq_point->gain_x & 0x1f))
1693                 compare_iq[0].gain_x = ((iq_point->gain_x) & 0xdf) + 1;  /* Q-path, Gain=1 */
1694         else
1695                 compare_iq[0].gain_x  = iq_point->gain_x - 1;  /* left point */
1696         compare_iq[0].phase_y = iq_point->phase_y;
1697
1698         /* y-direction */
1699         rc = r820t_iq_tree(priv, compare_iq,  compare_iq[0].gain_x,
1700                         compare_iq[0].phase_y, 0x08);
1701         if (rc < 0)
1702                 return rc;
1703
1704         r820t_compre_cor(compare_iq);
1705
1706         compare_bet[0] = compare_iq[0];
1707
1708         /* Try X column and save min result to compare_bet[1] */
1709         compare_iq[0].gain_x  = iq_point->gain_x;
1710         compare_iq[0].phase_y = iq_point->phase_y;
1711
1712         rc = r820t_iq_tree(priv, compare_iq,  compare_iq[0].gain_x,
1713                            compare_iq[0].phase_y, 0x08);
1714         if (rc < 0)
1715                 return rc;
1716
1717         r820t_compre_cor(compare_iq);
1718
1719         compare_bet[1] = compare_iq[0];
1720
1721         /* Try X+1 column and save min result to compare_bet[2] */
1722         if ((iq_point->gain_x & 0x1f) == 0x00)
1723                 compare_iq[0].gain_x = ((iq_point->gain_x) | 0x20) + 1;  /* I-path, Gain=1 */
1724         else
1725                 compare_iq[0].gain_x = iq_point->gain_x + 1;
1726         compare_iq[0].phase_y = iq_point->phase_y;
1727
1728         rc = r820t_iq_tree(priv, compare_iq,  compare_iq[0].gain_x,
1729                            compare_iq[0].phase_y, 0x08);
1730         if (rc < 0)
1731                 return rc;
1732
1733         r820t_compre_cor(compare_iq);
1734
1735         compare_bet[2] = compare_iq[0];
1736
1737         r820t_compre_cor(compare_bet);
1738
1739         *iq_point = compare_bet[0];
1740
1741         return 0;
1742 }
1743
1744 static int r820t_vga_adjust(struct r820t_priv *priv)
1745 {
1746         int rc;
1747         u8 vga_count;
1748
1749         /* increase vga power to let image significant */
1750         for (vga_count = 12; vga_count < 16; vga_count++) {
1751                 rc = r820t_write_reg_mask(priv, 0x0c, vga_count, 0x0f);
1752                 if (rc < 0)
1753                         return rc;
1754
1755                 usleep_range(10000, 11000);
1756
1757                 rc = r820t_multi_read(priv);
1758                 if (rc < 0)
1759                         return rc;
1760
1761                 if (rc > 40 * 4)
1762                         break;
1763         }
1764
1765         return 0;
1766 }
1767
1768 static int r820t_iq(struct r820t_priv *priv, struct r820t_sect_type *iq_pont)
1769 {
1770         struct r820t_sect_type compare_iq[3];
1771         int rc;
1772         u8 x_direction = 0;  /* 1:x, 0:y */
1773         u8 dir_reg, other_reg;
1774
1775         r820t_vga_adjust(priv);
1776
1777         rc = r820t_imr_cross(priv, compare_iq, &x_direction);
1778         if (rc < 0)
1779                 return rc;
1780
1781         if (x_direction == 1) {
1782                 dir_reg   = 0x08;
1783                 other_reg = 0x09;
1784         } else {
1785                 dir_reg   = 0x09;
1786                 other_reg = 0x08;
1787         }
1788
1789         /* compare and find min of 3 points. determine i/q direction */
1790         r820t_compre_cor(compare_iq);
1791
1792         /* increase step to find min value of this direction */
1793         rc = r820t_compre_step(priv, compare_iq, dir_reg);
1794         if (rc < 0)
1795                 return rc;
1796
1797         /* the other direction */
1798         rc = r820t_iq_tree(priv, compare_iq,  compare_iq[0].gain_x,
1799                                 compare_iq[0].phase_y, dir_reg);
1800         if (rc < 0)
1801                 return rc;
1802
1803         /* compare and find min of 3 points. determine i/q direction */
1804         r820t_compre_cor(compare_iq);
1805
1806         /* increase step to find min value on this direction */
1807         rc = r820t_compre_step(priv, compare_iq, other_reg);
1808         if (rc < 0)
1809                 return rc;
1810
1811         /* check 3 points again */
1812         rc = r820t_iq_tree(priv, compare_iq,  compare_iq[0].gain_x,
1813                                 compare_iq[0].phase_y, other_reg);
1814         if (rc < 0)
1815                 return rc;
1816
1817         r820t_compre_cor(compare_iq);
1818
1819         /* section-9 check */
1820         rc = r820t_section(priv, compare_iq);
1821
1822         *iq_pont = compare_iq[0];
1823
1824         /* reset gain/phase control setting */
1825         rc = r820t_write_reg_mask(priv, 0x08, 0, 0x3f);
1826         if (rc < 0)
1827                 return rc;
1828
1829         rc = r820t_write_reg_mask(priv, 0x09, 0, 0x3f);
1830
1831         return rc;
1832 }
1833
1834 static int r820t_f_imr(struct r820t_priv *priv, struct r820t_sect_type *iq_pont)
1835 {
1836         int rc;
1837
1838         r820t_vga_adjust(priv);
1839
1840         /*
1841          * search surrounding points from previous point
1842          * try (x-1), (x), (x+1) columns, and find min IMR result point
1843          */
1844         rc = r820t_section(priv, iq_pont);
1845         if (rc < 0)
1846                 return rc;
1847
1848         return 0;
1849 }
1850
1851 static int r820t_imr(struct r820t_priv *priv, unsigned imr_mem, bool im_flag)
1852 {
1853         struct r820t_sect_type imr_point;
1854         int rc;
1855         u32 ring_vco, ring_freq, ring_ref;
1856         u8 n_ring, n;
1857         int reg18, reg19, reg1f;
1858
1859         if (priv->cfg->xtal > 24000000)
1860                 ring_ref = priv->cfg->xtal / 2000;
1861         else
1862                 ring_ref = priv->cfg->xtal / 1000;
1863
1864         n_ring = 15;
1865         for (n = 0; n < 16; n++) {
1866                 if ((16 + n) * 8 * ring_ref >= 3100000) {
1867                         n_ring = n;
1868                         break;
1869                 }
1870         }
1871
1872         reg18 = r820t_read_cache_reg(priv, 0x18);
1873         reg19 = r820t_read_cache_reg(priv, 0x19);
1874         reg1f = r820t_read_cache_reg(priv, 0x1f);
1875
1876         reg18 &= 0xf0;      /* set ring[3:0] */
1877         reg18 |= n_ring;
1878
1879         ring_vco = (16 + n_ring) * 8 * ring_ref;
1880
1881         reg18 &= 0xdf;   /* clear ring_se23 */
1882         reg19 &= 0xfc;   /* clear ring_seldiv */
1883         reg1f &= 0xfc;   /* clear ring_att */
1884
1885         switch (imr_mem) {
1886         case 0:
1887                 ring_freq = ring_vco / 48;
1888                 reg18 |= 0x20;  /* ring_se23 = 1 */
1889                 reg19 |= 0x03;  /* ring_seldiv = 3 */
1890                 reg1f |= 0x02;  /* ring_att 10 */
1891                 break;
1892         case 1:
1893                 ring_freq = ring_vco / 16;
1894                 reg18 |= 0x00;  /* ring_se23 = 0 */
1895                 reg19 |= 0x02;  /* ring_seldiv = 2 */
1896                 reg1f |= 0x00;  /* pw_ring 00 */
1897                 break;
1898         case 2:
1899                 ring_freq = ring_vco / 8;
1900                 reg18 |= 0x00;  /* ring_se23 = 0 */
1901                 reg19 |= 0x01;  /* ring_seldiv = 1 */
1902                 reg1f |= 0x03;  /* pw_ring 11 */
1903                 break;
1904         case 3:
1905                 ring_freq = ring_vco / 6;
1906                 reg18 |= 0x20;  /* ring_se23 = 1 */
1907                 reg19 |= 0x00;  /* ring_seldiv = 0 */
1908                 reg1f |= 0x03;  /* pw_ring 11 */
1909                 break;
1910         case 4:
1911                 ring_freq = ring_vco / 4;
1912                 reg18 |= 0x00;  /* ring_se23 = 0 */
1913                 reg19 |= 0x00;  /* ring_seldiv = 0 */
1914                 reg1f |= 0x01;  /* pw_ring 01 */
1915                 break;
1916         default:
1917                 ring_freq = ring_vco / 4;
1918                 reg18 |= 0x00;  /* ring_se23 = 0 */
1919                 reg19 |= 0x00;  /* ring_seldiv = 0 */
1920                 reg1f |= 0x01;  /* pw_ring 01 */
1921                 break;
1922         }
1923
1924
1925         /* write pw_ring, n_ring, ringdiv2 registers */
1926
1927         /* n_ring, ring_se23 */
1928         rc = r820t_write_reg(priv, 0x18, reg18);
1929         if (rc < 0)
1930                 return rc;
1931
1932         /* ring_sediv */
1933         rc = r820t_write_reg(priv, 0x19, reg19);
1934         if (rc < 0)
1935                 return rc;
1936
1937         /* pw_ring */
1938         rc = r820t_write_reg(priv, 0x1f, reg1f);
1939         if (rc < 0)
1940                 return rc;
1941
1942         /* mux input freq ~ rf_in freq */
1943         rc = r820t_set_mux(priv, (ring_freq - 5300) * 1000);
1944         if (rc < 0)
1945                 return rc;
1946
1947         rc = r820t_set_pll(priv, V4L2_TUNER_DIGITAL_TV,
1948                            (ring_freq - 5300) * 1000);
1949         if (!priv->has_lock)
1950                 rc = -EINVAL;
1951         if (rc < 0)
1952                 return rc;
1953
1954         if (im_flag) {
1955                 rc = r820t_iq(priv, &imr_point);
1956         } else {
1957                 imr_point.gain_x  = priv->imr_data[3].gain_x;
1958                 imr_point.phase_y = priv->imr_data[3].phase_y;
1959                 imr_point.value   = priv->imr_data[3].value;
1960
1961                 rc = r820t_f_imr(priv, &imr_point);
1962         }
1963         if (rc < 0)
1964                 return rc;
1965
1966         /* save IMR value */
1967         switch (imr_mem) {
1968         case 0:
1969                 priv->imr_data[0].gain_x  = imr_point.gain_x;
1970                 priv->imr_data[0].phase_y = imr_point.phase_y;
1971                 priv->imr_data[0].value   = imr_point.value;
1972                 break;
1973         case 1:
1974                 priv->imr_data[1].gain_x  = imr_point.gain_x;
1975                 priv->imr_data[1].phase_y = imr_point.phase_y;
1976                 priv->imr_data[1].value   = imr_point.value;
1977                 break;
1978         case 2:
1979                 priv->imr_data[2].gain_x  = imr_point.gain_x;
1980                 priv->imr_data[2].phase_y = imr_point.phase_y;
1981                 priv->imr_data[2].value   = imr_point.value;
1982                 break;
1983         case 3:
1984                 priv->imr_data[3].gain_x  = imr_point.gain_x;
1985                 priv->imr_data[3].phase_y = imr_point.phase_y;
1986                 priv->imr_data[3].value   = imr_point.value;
1987                 break;
1988         case 4:
1989                 priv->imr_data[4].gain_x  = imr_point.gain_x;
1990                 priv->imr_data[4].phase_y = imr_point.phase_y;
1991                 priv->imr_data[4].value   = imr_point.value;
1992                 break;
1993         default:
1994                 priv->imr_data[4].gain_x  = imr_point.gain_x;
1995                 priv->imr_data[4].phase_y = imr_point.phase_y;
1996                 priv->imr_data[4].value   = imr_point.value;
1997                 break;
1998         }
1999
2000         return 0;
2001 }
2002
2003 static int r820t_imr_callibrate(struct r820t_priv *priv)
2004 {
2005         int rc, i;
2006         int xtal_cap = 0;
2007
2008         if (priv->init_done)
2009                 return 0;
2010
2011         /* Detect Xtal capacitance */
2012         if ((priv->cfg->rafael_chip == CHIP_R820T) ||
2013             (priv->cfg->rafael_chip == CHIP_R828S) ||
2014             (priv->cfg->rafael_chip == CHIP_R820C)) {
2015                 priv->xtal_cap_sel = XTAL_HIGH_CAP_0P;
2016         } else {
2017                 /* Initialize registers */
2018                 rc = r820t_write(priv, 0x05,
2019                                 r820t_init_array, sizeof(r820t_init_array));
2020                 if (rc < 0)
2021                         return rc;
2022                 for (i = 0; i < 3; i++) {
2023                         rc = r820t_xtal_check(priv);
2024                         if (rc < 0)
2025                                 return rc;
2026                         if (!i || rc > xtal_cap)
2027                                 xtal_cap = rc;
2028                 }
2029                 priv->xtal_cap_sel = xtal_cap;
2030         }
2031
2032         /*
2033          * Disables IMR callibration. That emulates the same behaviour
2034          * as what is done by rtl-sdr userspace library. Useful for testing
2035          */
2036         if (no_imr_cal) {
2037                 priv->init_done = true;
2038
2039                 return 0;
2040         }
2041
2042         /* Initialize registers */
2043         rc = r820t_write(priv, 0x05,
2044                          r820t_init_array, sizeof(r820t_init_array));
2045         if (rc < 0)
2046                 return rc;
2047
2048         rc = r820t_imr_prepare(priv);
2049         if (rc < 0)
2050                 return rc;
2051
2052         rc = r820t_imr(priv, 3, true);
2053         if (rc < 0)
2054                 return rc;
2055         rc = r820t_imr(priv, 1, false);
2056         if (rc < 0)
2057                 return rc;
2058         rc = r820t_imr(priv, 0, false);
2059         if (rc < 0)
2060                 return rc;
2061         rc = r820t_imr(priv, 2, false);
2062         if (rc < 0)
2063                 return rc;
2064         rc = r820t_imr(priv, 4, false);
2065         if (rc < 0)
2066                 return rc;
2067
2068         priv->init_done = true;
2069         priv->imr_done = true;
2070
2071         return 0;
2072 }
2073
2074 #if 0
2075 /* Not used, for now */
2076 static int r820t_gpio(struct r820t_priv *priv, bool enable)
2077 {
2078         return r820t_write_reg_mask(priv, 0x0f, enable ? 1 : 0, 0x01);
2079 }
2080 #endif
2081
2082 /*
2083  *  r820t frontend operations and tuner attach code
2084  *
2085  * All driver locks and i2c control are only in this part of the code
2086  */
2087
2088 static int r820t_init(struct dvb_frontend *fe)
2089 {
2090         struct r820t_priv *priv = fe->tuner_priv;
2091         int rc;
2092
2093         tuner_dbg("%s:\n", __func__);
2094
2095         mutex_lock(&priv->lock);
2096         if (fe->ops.i2c_gate_ctrl)
2097                 fe->ops.i2c_gate_ctrl(fe, 1);
2098
2099         rc = r820t_imr_callibrate(priv);
2100         if (rc < 0)
2101                 goto err;
2102
2103         /* Initialize registers */
2104         rc = r820t_write(priv, 0x05,
2105                          r820t_init_array, sizeof(r820t_init_array));
2106
2107 err:
2108         if (fe->ops.i2c_gate_ctrl)
2109                 fe->ops.i2c_gate_ctrl(fe, 0);
2110         mutex_unlock(&priv->lock);
2111
2112         if (rc < 0)
2113                 tuner_dbg("%s: failed=%d\n", __func__, rc);
2114         return rc;
2115 }
2116
2117 static int r820t_sleep(struct dvb_frontend *fe)
2118 {
2119         struct r820t_priv *priv = fe->tuner_priv;
2120         int rc;
2121
2122         tuner_dbg("%s:\n", __func__);
2123
2124         mutex_lock(&priv->lock);
2125         if (fe->ops.i2c_gate_ctrl)
2126                 fe->ops.i2c_gate_ctrl(fe, 1);
2127
2128         rc = r820t_standby(priv);
2129
2130         if (fe->ops.i2c_gate_ctrl)
2131                 fe->ops.i2c_gate_ctrl(fe, 0);
2132         mutex_unlock(&priv->lock);
2133
2134         tuner_dbg("%s: failed=%d\n", __func__, rc);
2135         return rc;
2136 }
2137
2138 static int r820t_set_analog_freq(struct dvb_frontend *fe,
2139                                  struct analog_parameters *p)
2140 {
2141         struct r820t_priv *priv = fe->tuner_priv;
2142         unsigned bw;
2143         int rc;
2144
2145         tuner_dbg("%s called\n", __func__);
2146
2147         /* if std is not defined, choose one */
2148         if (!p->std)
2149                 p->std = V4L2_STD_MN;
2150
2151         if ((p->std == V4L2_STD_PAL_M) || (p->std == V4L2_STD_NTSC))
2152                 bw = 6;
2153         else
2154                 bw = 8;
2155
2156         mutex_lock(&priv->lock);
2157         if (fe->ops.i2c_gate_ctrl)
2158                 fe->ops.i2c_gate_ctrl(fe, 1);
2159
2160         rc = generic_set_freq(fe, 62500l * p->frequency, bw,
2161                               V4L2_TUNER_ANALOG_TV, p->std, SYS_UNDEFINED);
2162
2163         if (fe->ops.i2c_gate_ctrl)
2164                 fe->ops.i2c_gate_ctrl(fe, 0);
2165         mutex_unlock(&priv->lock);
2166
2167         return rc;
2168 }
2169
2170 static int r820t_set_params(struct dvb_frontend *fe)
2171 {
2172         struct r820t_priv *priv = fe->tuner_priv;
2173         struct dtv_frontend_properties *c = &fe->dtv_property_cache;
2174         int rc;
2175         unsigned bw;
2176
2177         tuner_dbg("%s: delivery_system=%d frequency=%d bandwidth_hz=%d\n",
2178                 __func__, c->delivery_system, c->frequency, c->bandwidth_hz);
2179
2180         mutex_lock(&priv->lock);
2181         if (fe->ops.i2c_gate_ctrl)
2182                 fe->ops.i2c_gate_ctrl(fe, 1);
2183
2184         bw = (c->bandwidth_hz + 500000) / 1000000;
2185         if (!bw)
2186                 bw = 8;
2187
2188         rc = generic_set_freq(fe, c->frequency, bw,
2189                               V4L2_TUNER_DIGITAL_TV, 0, c->delivery_system);
2190
2191         if (fe->ops.i2c_gate_ctrl)
2192                 fe->ops.i2c_gate_ctrl(fe, 0);
2193         mutex_unlock(&priv->lock);
2194
2195         if (rc)
2196                 tuner_dbg("%s: failed=%d\n", __func__, rc);
2197         return rc;
2198 }
2199
2200 static int r820t_signal(struct dvb_frontend *fe, u16 *strength)
2201 {
2202         struct r820t_priv *priv = fe->tuner_priv;
2203         int rc = 0;
2204
2205         mutex_lock(&priv->lock);
2206         if (fe->ops.i2c_gate_ctrl)
2207                 fe->ops.i2c_gate_ctrl(fe, 1);
2208
2209         if (priv->has_lock) {
2210                 rc = r820t_read_gain(priv);
2211                 if (rc < 0)
2212                         goto err;
2213
2214                 /* A higher gain at LNA means a lower signal strength */
2215                 *strength = (45 - rc) << 4 | 0xff;
2216                 if (*strength == 0xff)
2217                         *strength = 0;
2218         } else {
2219                 *strength = 0;
2220         }
2221
2222 err:
2223         if (fe->ops.i2c_gate_ctrl)
2224                 fe->ops.i2c_gate_ctrl(fe, 0);
2225         mutex_unlock(&priv->lock);
2226
2227         tuner_dbg("%s: %s, gain=%d strength=%d\n",
2228                   __func__,
2229                   priv->has_lock ? "PLL locked" : "no signal",
2230                   rc, *strength);
2231
2232         return 0;
2233 }
2234
2235 static int r820t_get_if_frequency(struct dvb_frontend *fe, u32 *frequency)
2236 {
2237         struct r820t_priv *priv = fe->tuner_priv;
2238
2239         tuner_dbg("%s:\n", __func__);
2240
2241         *frequency = priv->int_freq;
2242
2243         return 0;
2244 }
2245
2246 static int r820t_release(struct dvb_frontend *fe)
2247 {
2248         struct r820t_priv *priv = fe->tuner_priv;
2249
2250         tuner_dbg("%s:\n", __func__);
2251
2252         mutex_lock(&r820t_list_mutex);
2253
2254         if (priv)
2255                 hybrid_tuner_release_state(priv);
2256
2257         mutex_unlock(&r820t_list_mutex);
2258
2259         fe->tuner_priv = NULL;
2260
2261         return 0;
2262 }
2263
2264 static const struct dvb_tuner_ops r820t_tuner_ops = {
2265         .info = {
2266                 .name           = "Rafael Micro R820T",
2267                 .frequency_min  =   42000000,
2268                 .frequency_max  = 1002000000,
2269         },
2270         .init = r820t_init,
2271         .release = r820t_release,
2272         .sleep = r820t_sleep,
2273         .set_params = r820t_set_params,
2274         .set_analog_params = r820t_set_analog_freq,
2275         .get_if_frequency = r820t_get_if_frequency,
2276         .get_rf_strength = r820t_signal,
2277 };
2278
2279 struct dvb_frontend *r820t_attach(struct dvb_frontend *fe,
2280                                   struct i2c_adapter *i2c,
2281                                   const struct r820t_config *cfg)
2282 {
2283         struct r820t_priv *priv;
2284         int rc = -ENODEV;
2285         u8 data[5];
2286         int instance;
2287
2288         mutex_lock(&r820t_list_mutex);
2289
2290         instance = hybrid_tuner_request_state(struct r820t_priv, priv,
2291                                               hybrid_tuner_instance_list,
2292                                               i2c, cfg->i2c_addr,
2293                                               "r820t");
2294         switch (instance) {
2295         case 0:
2296                 /* memory allocation failure */
2297                 goto err_no_gate;
2298                 break;
2299         case 1:
2300                 /* new tuner instance */
2301                 priv->cfg = cfg;
2302
2303                 mutex_init(&priv->lock);
2304
2305                 fe->tuner_priv = priv;
2306                 break;
2307         case 2:
2308                 /* existing tuner instance */
2309                 fe->tuner_priv = priv;
2310                 break;
2311         }
2312
2313         if (fe->ops.i2c_gate_ctrl)
2314                 fe->ops.i2c_gate_ctrl(fe, 1);
2315
2316         /* check if the tuner is there */
2317         rc = r820t_read(priv, 0x00, data, sizeof(data));
2318         if (rc < 0)
2319                 goto err;
2320
2321         rc = r820t_sleep(fe);
2322         if (rc < 0)
2323                 goto err;
2324
2325         tuner_info("Rafael Micro r820t successfully identified\n");
2326
2327         if (fe->ops.i2c_gate_ctrl)
2328                 fe->ops.i2c_gate_ctrl(fe, 0);
2329
2330         mutex_unlock(&r820t_list_mutex);
2331
2332         memcpy(&fe->ops.tuner_ops, &r820t_tuner_ops,
2333                         sizeof(struct dvb_tuner_ops));
2334
2335         return fe;
2336 err:
2337         if (fe->ops.i2c_gate_ctrl)
2338                 fe->ops.i2c_gate_ctrl(fe, 0);
2339
2340 err_no_gate:
2341         mutex_unlock(&r820t_list_mutex);
2342
2343         tuner_info("%s: failed=%d\n", __func__, rc);
2344         r820t_release(fe);
2345         return NULL;
2346 }
2347 EXPORT_SYMBOL_GPL(r820t_attach);
2348
2349 MODULE_DESCRIPTION("Rafael Micro r820t silicon tuner driver");
2350 MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
2351 MODULE_LICENSE("GPL");