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