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