xref: /openbmc/linux/drivers/media/tuners/xc4000.c (revision 11696c5e)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Driver for Xceive XC4000 "QAM/8VSB single chip tuner"
4  *
5  *  Copyright (c) 2007 Xceive Corporation
6  *  Copyright (c) 2007 Steven Toth <stoth@linuxtv.org>
7  *  Copyright (c) 2009 Devin Heitmueller <dheitmueller@kernellabs.com>
8  *  Copyright (c) 2009 Davide Ferri <d.ferri@zero11.it>
9  *  Copyright (c) 2010 Istvan Varga <istvan_v@mailbox.hu>
10  */
11 
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/videodev2.h>
15 #include <linux/delay.h>
16 #include <linux/dvb/frontend.h>
17 #include <linux/i2c.h>
18 #include <linux/mutex.h>
19 #include <asm/unaligned.h>
20 
21 #include <media/dvb_frontend.h>
22 
23 #include "xc4000.h"
24 #include "tuner-i2c.h"
25 #include "xc2028-types.h"
26 
27 static int debug;
28 module_param(debug, int, 0644);
29 MODULE_PARM_DESC(debug, "Debugging level (0 to 2, default: 0 (off)).");
30 
31 static int no_poweroff;
32 module_param(no_poweroff, int, 0644);
33 MODULE_PARM_DESC(no_poweroff, "Power management (1: disabled, 2: enabled, 0 (default): use device-specific default mode).");
34 
35 static int audio_std;
36 module_param(audio_std, int, 0644);
37 MODULE_PARM_DESC(audio_std, "Audio standard. XC4000 audio decoder explicitly needs to know what audio standard is needed for some video standards with audio A2 or NICAM. The valid settings are a sum of:\n"
38 	" 1: use NICAM/B or A2/B instead of NICAM/A or A2/A\n"
39 	" 2: use A2 instead of NICAM or BTSC\n"
40 	" 4: use SECAM/K3 instead of K1\n"
41 	" 8: use PAL-D/K audio for SECAM-D/K\n"
42 	"16: use FM radio input 1 instead of input 2\n"
43 	"32: use mono audio (the lower three bits are ignored)");
44 
45 static char firmware_name[30];
46 module_param_string(firmware_name, firmware_name, sizeof(firmware_name), 0);
47 MODULE_PARM_DESC(firmware_name, "Firmware file name. Allows overriding the default firmware name.");
48 
49 static DEFINE_MUTEX(xc4000_list_mutex);
50 static LIST_HEAD(hybrid_tuner_instance_list);
51 
52 #define dprintk(level, fmt, arg...) if (debug >= level) \
53 	printk(KERN_INFO "%s: " fmt, "xc4000", ## arg)
54 
55 /* struct for storing firmware table */
56 struct firmware_description {
57 	unsigned int  type;
58 	v4l2_std_id   id;
59 	__u16         int_freq;
60 	unsigned char *ptr;
61 	unsigned int  size;
62 };
63 
64 struct firmware_properties {
65 	unsigned int	type;
66 	v4l2_std_id	id;
67 	v4l2_std_id	std_req;
68 	__u16		int_freq;
69 	unsigned int	scode_table;
70 	int		scode_nr;
71 };
72 
73 struct xc4000_priv {
74 	struct tuner_i2c_props i2c_props;
75 	struct list_head hybrid_tuner_instance_list;
76 	struct firmware_description *firm;
77 	int	firm_size;
78 	u32	if_khz;
79 	u32	freq_hz, freq_offset;
80 	u32	bandwidth;
81 	u8	video_standard;
82 	u8	rf_mode;
83 	u8	default_pm;
84 	u8	dvb_amplitude;
85 	u8	set_smoothedcvbs;
86 	u8	ignore_i2c_write_errors;
87 	__u16	firm_version;
88 	struct firmware_properties cur_fw;
89 	__u16	hwmodel;
90 	__u16	hwvers;
91 	struct mutex	lock;
92 };
93 
94 #define XC4000_AUDIO_STD_B		 1
95 #define XC4000_AUDIO_STD_A2		 2
96 #define XC4000_AUDIO_STD_K3		 4
97 #define XC4000_AUDIO_STD_L		 8
98 #define XC4000_AUDIO_STD_INPUT1		16
99 #define XC4000_AUDIO_STD_MONO		32
100 
101 #define XC4000_DEFAULT_FIRMWARE "dvb-fe-xc4000-1.4.fw"
102 #define XC4000_DEFAULT_FIRMWARE_NEW "dvb-fe-xc4000-1.4.1.fw"
103 
104 /* Misc Defines */
105 #define MAX_TV_STANDARD			24
106 #define XC_MAX_I2C_WRITE_LENGTH		64
107 #define XC_POWERED_DOWN			0x80000000U
108 
109 /* Signal Types */
110 #define XC_RF_MODE_AIR			0
111 #define XC_RF_MODE_CABLE		1
112 
113 /* Product id */
114 #define XC_PRODUCT_ID_FW_NOT_LOADED	0x2000
115 #define XC_PRODUCT_ID_XC4000		0x0FA0
116 #define XC_PRODUCT_ID_XC4100		0x1004
117 
118 /* Registers (Write-only) */
119 #define XREG_INIT         0x00
120 #define XREG_VIDEO_MODE   0x01
121 #define XREG_AUDIO_MODE   0x02
122 #define XREG_RF_FREQ      0x03
123 #define XREG_D_CODE       0x04
124 #define XREG_DIRECTSITTING_MODE 0x05
125 #define XREG_SEEK_MODE    0x06
126 #define XREG_POWER_DOWN   0x08
127 #define XREG_SIGNALSOURCE 0x0A
128 #define XREG_SMOOTHEDCVBS 0x0E
129 #define XREG_AMPLITUDE    0x10
130 
131 /* Registers (Read-only) */
132 #define XREG_ADC_ENV      0x00
133 #define XREG_QUALITY      0x01
134 #define XREG_FRAME_LINES  0x02
135 #define XREG_HSYNC_FREQ   0x03
136 #define XREG_LOCK         0x04
137 #define XREG_FREQ_ERROR   0x05
138 #define XREG_SNR          0x06
139 #define XREG_VERSION      0x07
140 #define XREG_PRODUCT_ID   0x08
141 #define XREG_SIGNAL_LEVEL 0x0A
142 #define XREG_NOISE_LEVEL  0x0B
143 
144 /*
145    Basic firmware description. This will remain with
146    the driver for documentation purposes.
147 
148    This represents an I2C firmware file encoded as a
149    string of unsigned char. Format is as follows:
150 
151    char[0  ]=len0_MSB  -> len = len_MSB * 256 + len_LSB
152    char[1  ]=len0_LSB  -> length of first write transaction
153    char[2  ]=data0 -> first byte to be sent
154    char[3  ]=data1
155    char[4  ]=data2
156    char[   ]=...
157    char[M  ]=dataN  -> last byte to be sent
158    char[M+1]=len1_MSB  -> len = len_MSB * 256 + len_LSB
159    char[M+2]=len1_LSB  -> length of second write transaction
160    char[M+3]=data0
161    char[M+4]=data1
162    ...
163    etc.
164 
165    The [len] value should be interpreted as follows:
166 
167    len= len_MSB _ len_LSB
168    len=1111_1111_1111_1111   : End of I2C_SEQUENCE
169    len=0000_0000_0000_0000   : Reset command: Do hardware reset
170    len=0NNN_NNNN_NNNN_NNNN   : Normal transaction: number of bytes = {1:32767)
171    len=1WWW_WWWW_WWWW_WWWW   : Wait command: wait for {1:32767} ms
172 
173    For the RESET and WAIT commands, the two following bytes will contain
174    immediately the length of the following transaction.
175 */
176 
177 struct XC_TV_STANDARD {
178 	const char  *Name;
179 	u16	    audio_mode;
180 	u16	    video_mode;
181 	u16	    int_freq;
182 };
183 
184 /* Tuner standards */
185 #define XC4000_MN_NTSC_PAL_BTSC		0
186 #define XC4000_MN_NTSC_PAL_A2		1
187 #define XC4000_MN_NTSC_PAL_EIAJ		2
188 #define XC4000_MN_NTSC_PAL_Mono		3
189 #define XC4000_BG_PAL_A2		4
190 #define XC4000_BG_PAL_NICAM		5
191 #define XC4000_BG_PAL_MONO		6
192 #define XC4000_I_PAL_NICAM		7
193 #define XC4000_I_PAL_NICAM_MONO		8
194 #define XC4000_DK_PAL_A2		9
195 #define XC4000_DK_PAL_NICAM		10
196 #define XC4000_DK_PAL_MONO		11
197 #define XC4000_DK_SECAM_A2DK1		12
198 #define XC4000_DK_SECAM_A2LDK3		13
199 #define XC4000_DK_SECAM_A2MONO		14
200 #define XC4000_DK_SECAM_NICAM		15
201 #define XC4000_L_SECAM_NICAM		16
202 #define XC4000_LC_SECAM_NICAM		17
203 #define XC4000_DTV6			18
204 #define XC4000_DTV8			19
205 #define XC4000_DTV7_8			20
206 #define XC4000_DTV7			21
207 #define XC4000_FM_Radio_INPUT2		22
208 #define XC4000_FM_Radio_INPUT1		23
209 
210 static struct XC_TV_STANDARD xc4000_standard[MAX_TV_STANDARD] = {
211 	{"M/N-NTSC/PAL-BTSC",	0x0000, 0x80A0, 4500},
212 	{"M/N-NTSC/PAL-A2",	0x0000, 0x80A0, 4600},
213 	{"M/N-NTSC/PAL-EIAJ",	0x0040, 0x80A0, 4500},
214 	{"M/N-NTSC/PAL-Mono",	0x0078, 0x80A0, 4500},
215 	{"B/G-PAL-A2",		0x0000, 0x8159, 5640},
216 	{"B/G-PAL-NICAM",	0x0004, 0x8159, 5740},
217 	{"B/G-PAL-MONO",	0x0078, 0x8159, 5500},
218 	{"I-PAL-NICAM",		0x0080, 0x8049, 6240},
219 	{"I-PAL-NICAM-MONO",	0x0078, 0x8049, 6000},
220 	{"D/K-PAL-A2",		0x0000, 0x8049, 6380},
221 	{"D/K-PAL-NICAM",	0x0080, 0x8049, 6200},
222 	{"D/K-PAL-MONO",	0x0078, 0x8049, 6500},
223 	{"D/K-SECAM-A2 DK1",	0x0000, 0x8049, 6340},
224 	{"D/K-SECAM-A2 L/DK3",	0x0000, 0x8049, 6000},
225 	{"D/K-SECAM-A2 MONO",	0x0078, 0x8049, 6500},
226 	{"D/K-SECAM-NICAM",	0x0080, 0x8049, 6200},
227 	{"L-SECAM-NICAM",	0x8080, 0x0009, 6200},
228 	{"L'-SECAM-NICAM",	0x8080, 0x4009, 6200},
229 	{"DTV6",		0x00C0, 0x8002,    0},
230 	{"DTV8",		0x00C0, 0x800B,    0},
231 	{"DTV7/8",		0x00C0, 0x801B,    0},
232 	{"DTV7",		0x00C0, 0x8007,    0},
233 	{"FM Radio-INPUT2",	0x0008, 0x9800, 10700},
234 	{"FM Radio-INPUT1",	0x0008, 0x9000, 10700}
235 };
236 
237 static int xc4000_readreg(struct xc4000_priv *priv, u16 reg, u16 *val);
238 static int xc4000_tuner_reset(struct dvb_frontend *fe);
239 static void xc_debug_dump(struct xc4000_priv *priv);
240 
241 static int xc_send_i2c_data(struct xc4000_priv *priv, u8 *buf, int len)
242 {
243 	struct i2c_msg msg = { .addr = priv->i2c_props.addr,
244 			       .flags = 0, .buf = buf, .len = len };
245 	if (i2c_transfer(priv->i2c_props.adap, &msg, 1) != 1) {
246 		if (priv->ignore_i2c_write_errors == 0) {
247 			printk(KERN_ERR "xc4000: I2C write failed (len=%i)\n",
248 			       len);
249 			if (len == 4) {
250 				printk(KERN_ERR "bytes %*ph\n", 4, buf);
251 			}
252 			return -EREMOTEIO;
253 		}
254 	}
255 	return 0;
256 }
257 
258 static int xc4000_tuner_reset(struct dvb_frontend *fe)
259 {
260 	struct xc4000_priv *priv = fe->tuner_priv;
261 	int ret;
262 
263 	dprintk(1, "%s()\n", __func__);
264 
265 	if (fe->callback) {
266 		ret = fe->callback(((fe->dvb) && (fe->dvb->priv)) ?
267 					   fe->dvb->priv :
268 					   priv->i2c_props.adap->algo_data,
269 					   DVB_FRONTEND_COMPONENT_TUNER,
270 					   XC4000_TUNER_RESET, 0);
271 		if (ret) {
272 			printk(KERN_ERR "xc4000: reset failed\n");
273 			return -EREMOTEIO;
274 		}
275 	} else {
276 		printk(KERN_ERR "xc4000: no tuner reset callback function, fatal\n");
277 		return -EINVAL;
278 	}
279 	return 0;
280 }
281 
282 static int xc_write_reg(struct xc4000_priv *priv, u16 regAddr, u16 i2cData)
283 {
284 	u8 buf[4];
285 
286 	buf[0] = (regAddr >> 8) & 0xFF;
287 	buf[1] = regAddr & 0xFF;
288 	buf[2] = (i2cData >> 8) & 0xFF;
289 	buf[3] = i2cData & 0xFF;
290 
291 	return xc_send_i2c_data(priv, buf, 4);
292 }
293 
294 static int xc_load_i2c_sequence(struct dvb_frontend *fe, const u8 *i2c_sequence)
295 {
296 	struct xc4000_priv *priv = fe->tuner_priv;
297 
298 	int i, nbytes_to_send, result;
299 	unsigned int len, pos, index;
300 	u8 buf[XC_MAX_I2C_WRITE_LENGTH];
301 
302 	index = 0;
303 	while ((i2c_sequence[index] != 0xFF) ||
304 		(i2c_sequence[index + 1] != 0xFF)) {
305 		len = i2c_sequence[index] * 256 + i2c_sequence[index+1];
306 		if (len == 0x0000) {
307 			/* RESET command */
308 			/* NOTE: this is ignored, as the reset callback was */
309 			/* already called by check_firmware() */
310 			index += 2;
311 		} else if (len & 0x8000) {
312 			/* WAIT command */
313 			msleep(len & 0x7FFF);
314 			index += 2;
315 		} else {
316 			/* Send i2c data whilst ensuring individual transactions
317 			 * do not exceed XC_MAX_I2C_WRITE_LENGTH bytes.
318 			 */
319 			index += 2;
320 			buf[0] = i2c_sequence[index];
321 			buf[1] = i2c_sequence[index + 1];
322 			pos = 2;
323 			while (pos < len) {
324 				if ((len - pos) > XC_MAX_I2C_WRITE_LENGTH - 2)
325 					nbytes_to_send =
326 						XC_MAX_I2C_WRITE_LENGTH;
327 				else
328 					nbytes_to_send = (len - pos + 2);
329 				for (i = 2; i < nbytes_to_send; i++) {
330 					buf[i] = i2c_sequence[index + pos +
331 						i - 2];
332 				}
333 				result = xc_send_i2c_data(priv, buf,
334 					nbytes_to_send);
335 
336 				if (result != 0)
337 					return result;
338 
339 				pos += nbytes_to_send - 2;
340 			}
341 			index += len;
342 		}
343 	}
344 	return 0;
345 }
346 
347 static int xc_set_tv_standard(struct xc4000_priv *priv,
348 	u16 video_mode, u16 audio_mode)
349 {
350 	int ret;
351 	dprintk(1, "%s(0x%04x,0x%04x)\n", __func__, video_mode, audio_mode);
352 	dprintk(1, "%s() Standard = %s\n",
353 		__func__,
354 		xc4000_standard[priv->video_standard].Name);
355 
356 	/* Don't complain when the request fails because of i2c stretching */
357 	priv->ignore_i2c_write_errors = 1;
358 
359 	ret = xc_write_reg(priv, XREG_VIDEO_MODE, video_mode);
360 	if (ret == 0)
361 		ret = xc_write_reg(priv, XREG_AUDIO_MODE, audio_mode);
362 
363 	priv->ignore_i2c_write_errors = 0;
364 
365 	return ret;
366 }
367 
368 static int xc_set_signal_source(struct xc4000_priv *priv, u16 rf_mode)
369 {
370 	dprintk(1, "%s(%d) Source = %s\n", __func__, rf_mode,
371 		rf_mode == XC_RF_MODE_AIR ? "ANTENNA" : "CABLE");
372 
373 	if ((rf_mode != XC_RF_MODE_AIR) && (rf_mode != XC_RF_MODE_CABLE)) {
374 		rf_mode = XC_RF_MODE_CABLE;
375 		printk(KERN_ERR
376 			"%s(), Invalid mode, defaulting to CABLE",
377 			__func__);
378 	}
379 	return xc_write_reg(priv, XREG_SIGNALSOURCE, rf_mode);
380 }
381 
382 static const struct dvb_tuner_ops xc4000_tuner_ops;
383 
384 static int xc_set_rf_frequency(struct xc4000_priv *priv, u32 freq_hz)
385 {
386 	u16 freq_code;
387 
388 	dprintk(1, "%s(%u)\n", __func__, freq_hz);
389 
390 	if ((freq_hz > xc4000_tuner_ops.info.frequency_max_hz) ||
391 	    (freq_hz < xc4000_tuner_ops.info.frequency_min_hz))
392 		return -EINVAL;
393 
394 	freq_code = (u16)(freq_hz / 15625);
395 
396 	/* WAS: Starting in firmware version 1.1.44, Xceive recommends using the
397 	   FINERFREQ for all normal tuning (the doc indicates reg 0x03 should
398 	   only be used for fast scanning for channel lock) */
399 	/* WAS: XREG_FINERFREQ */
400 	return xc_write_reg(priv, XREG_RF_FREQ, freq_code);
401 }
402 
403 static int xc_get_adc_envelope(struct xc4000_priv *priv, u16 *adc_envelope)
404 {
405 	return xc4000_readreg(priv, XREG_ADC_ENV, adc_envelope);
406 }
407 
408 static int xc_get_frequency_error(struct xc4000_priv *priv, u32 *freq_error_hz)
409 {
410 	int result;
411 	u16 regData;
412 	u32 tmp;
413 
414 	result = xc4000_readreg(priv, XREG_FREQ_ERROR, &regData);
415 	if (result != 0)
416 		return result;
417 
418 	tmp = (u32)regData & 0xFFFFU;
419 	tmp = (tmp < 0x8000U ? tmp : 0x10000U - tmp);
420 	(*freq_error_hz) = tmp * 15625;
421 	return result;
422 }
423 
424 static int xc_get_lock_status(struct xc4000_priv *priv, u16 *lock_status)
425 {
426 	return xc4000_readreg(priv, XREG_LOCK, lock_status);
427 }
428 
429 static int xc_get_version(struct xc4000_priv *priv,
430 	u8 *hw_majorversion, u8 *hw_minorversion,
431 	u8 *fw_majorversion, u8 *fw_minorversion)
432 {
433 	u16 data;
434 	int result;
435 
436 	result = xc4000_readreg(priv, XREG_VERSION, &data);
437 	if (result != 0)
438 		return result;
439 
440 	(*hw_majorversion) = (data >> 12) & 0x0F;
441 	(*hw_minorversion) = (data >>  8) & 0x0F;
442 	(*fw_majorversion) = (data >>  4) & 0x0F;
443 	(*fw_minorversion) = data & 0x0F;
444 
445 	return 0;
446 }
447 
448 static int xc_get_hsync_freq(struct xc4000_priv *priv, u32 *hsync_freq_hz)
449 {
450 	u16 regData;
451 	int result;
452 
453 	result = xc4000_readreg(priv, XREG_HSYNC_FREQ, &regData);
454 	if (result != 0)
455 		return result;
456 
457 	(*hsync_freq_hz) = ((regData & 0x0fff) * 763)/100;
458 	return result;
459 }
460 
461 static int xc_get_frame_lines(struct xc4000_priv *priv, u16 *frame_lines)
462 {
463 	return xc4000_readreg(priv, XREG_FRAME_LINES, frame_lines);
464 }
465 
466 static int xc_get_quality(struct xc4000_priv *priv, u16 *quality)
467 {
468 	return xc4000_readreg(priv, XREG_QUALITY, quality);
469 }
470 
471 static int xc_get_signal_level(struct xc4000_priv *priv, u16 *signal)
472 {
473 	return xc4000_readreg(priv, XREG_SIGNAL_LEVEL, signal);
474 }
475 
476 static int xc_get_noise_level(struct xc4000_priv *priv, u16 *noise)
477 {
478 	return xc4000_readreg(priv, XREG_NOISE_LEVEL, noise);
479 }
480 
481 static u16 xc_wait_for_lock(struct xc4000_priv *priv)
482 {
483 	u16	lock_state = 0;
484 	int	watchdog_count = 40;
485 
486 	while ((lock_state == 0) && (watchdog_count > 0)) {
487 		xc_get_lock_status(priv, &lock_state);
488 		if (lock_state != 1) {
489 			msleep(5);
490 			watchdog_count--;
491 		}
492 	}
493 	return lock_state;
494 }
495 
496 static int xc_tune_channel(struct xc4000_priv *priv, u32 freq_hz)
497 {
498 	int	found = 1;
499 	int	result;
500 
501 	dprintk(1, "%s(%u)\n", __func__, freq_hz);
502 
503 	/* Don't complain when the request fails because of i2c stretching */
504 	priv->ignore_i2c_write_errors = 1;
505 	result = xc_set_rf_frequency(priv, freq_hz);
506 	priv->ignore_i2c_write_errors = 0;
507 
508 	if (result != 0)
509 		return 0;
510 
511 	/* wait for lock only in analog TV mode */
512 	if ((priv->cur_fw.type & (FM | DTV6 | DTV7 | DTV78 | DTV8)) == 0) {
513 		if (xc_wait_for_lock(priv) != 1)
514 			found = 0;
515 	}
516 
517 	/* Wait for stats to stabilize.
518 	 * Frame Lines needs two frame times after initial lock
519 	 * before it is valid.
520 	 */
521 	msleep(debug ? 100 : 10);
522 
523 	if (debug)
524 		xc_debug_dump(priv);
525 
526 	return found;
527 }
528 
529 static int xc4000_readreg(struct xc4000_priv *priv, u16 reg, u16 *val)
530 {
531 	u8 buf[2] = { reg >> 8, reg & 0xff };
532 	u8 bval[2] = { 0, 0 };
533 	struct i2c_msg msg[2] = {
534 		{ .addr = priv->i2c_props.addr,
535 			.flags = 0, .buf = &buf[0], .len = 2 },
536 		{ .addr = priv->i2c_props.addr,
537 			.flags = I2C_M_RD, .buf = &bval[0], .len = 2 },
538 	};
539 
540 	if (i2c_transfer(priv->i2c_props.adap, msg, 2) != 2) {
541 		printk(KERN_ERR "xc4000: I2C read failed\n");
542 		return -EREMOTEIO;
543 	}
544 
545 	*val = (bval[0] << 8) | bval[1];
546 	return 0;
547 }
548 
549 #define dump_firm_type(t)	dump_firm_type_and_int_freq(t, 0)
550 static void dump_firm_type_and_int_freq(unsigned int type, u16 int_freq)
551 {
552 	if (type & BASE)
553 		printk(KERN_CONT "BASE ");
554 	if (type & INIT1)
555 		printk(KERN_CONT "INIT1 ");
556 	if (type & F8MHZ)
557 		printk(KERN_CONT "F8MHZ ");
558 	if (type & MTS)
559 		printk(KERN_CONT "MTS ");
560 	if (type & D2620)
561 		printk(KERN_CONT "D2620 ");
562 	if (type & D2633)
563 		printk(KERN_CONT "D2633 ");
564 	if (type & DTV6)
565 		printk(KERN_CONT "DTV6 ");
566 	if (type & QAM)
567 		printk(KERN_CONT "QAM ");
568 	if (type & DTV7)
569 		printk(KERN_CONT "DTV7 ");
570 	if (type & DTV78)
571 		printk(KERN_CONT "DTV78 ");
572 	if (type & DTV8)
573 		printk(KERN_CONT "DTV8 ");
574 	if (type & FM)
575 		printk(KERN_CONT "FM ");
576 	if (type & INPUT1)
577 		printk(KERN_CONT "INPUT1 ");
578 	if (type & LCD)
579 		printk(KERN_CONT "LCD ");
580 	if (type & NOGD)
581 		printk(KERN_CONT "NOGD ");
582 	if (type & MONO)
583 		printk(KERN_CONT "MONO ");
584 	if (type & ATSC)
585 		printk(KERN_CONT "ATSC ");
586 	if (type & IF)
587 		printk(KERN_CONT "IF ");
588 	if (type & LG60)
589 		printk(KERN_CONT "LG60 ");
590 	if (type & ATI638)
591 		printk(KERN_CONT "ATI638 ");
592 	if (type & OREN538)
593 		printk(KERN_CONT "OREN538 ");
594 	if (type & OREN36)
595 		printk(KERN_CONT "OREN36 ");
596 	if (type & TOYOTA388)
597 		printk(KERN_CONT "TOYOTA388 ");
598 	if (type & TOYOTA794)
599 		printk(KERN_CONT "TOYOTA794 ");
600 	if (type & DIBCOM52)
601 		printk(KERN_CONT "DIBCOM52 ");
602 	if (type & ZARLINK456)
603 		printk(KERN_CONT "ZARLINK456 ");
604 	if (type & CHINA)
605 		printk(KERN_CONT "CHINA ");
606 	if (type & F6MHZ)
607 		printk(KERN_CONT "F6MHZ ");
608 	if (type & INPUT2)
609 		printk(KERN_CONT "INPUT2 ");
610 	if (type & SCODE)
611 		printk(KERN_CONT "SCODE ");
612 	if (type & HAS_IF)
613 		printk(KERN_CONT "HAS_IF_%d ", int_freq);
614 }
615 
616 static int seek_firmware(struct dvb_frontend *fe, unsigned int type,
617 			 v4l2_std_id *id)
618 {
619 	struct xc4000_priv *priv = fe->tuner_priv;
620 	int		i, best_i = -1;
621 	unsigned int	best_nr_diffs = 255U;
622 
623 	if (!priv->firm) {
624 		printk(KERN_ERR "Error! firmware not loaded\n");
625 		return -EINVAL;
626 	}
627 
628 	if (((type & ~SCODE) == 0) && (*id == 0))
629 		*id = V4L2_STD_PAL;
630 
631 	/* Seek for generic video standard match */
632 	for (i = 0; i < priv->firm_size; i++) {
633 		v4l2_std_id	id_diff_mask =
634 			(priv->firm[i].id ^ (*id)) & (*id);
635 		unsigned int	type_diff_mask =
636 			(priv->firm[i].type ^ type)
637 			& (BASE_TYPES | DTV_TYPES | LCD | NOGD | MONO | SCODE);
638 		unsigned int	nr_diffs;
639 
640 		if (type_diff_mask
641 		    & (BASE | INIT1 | FM | DTV6 | DTV7 | DTV78 | DTV8 | SCODE))
642 			continue;
643 
644 		nr_diffs = hweight64(id_diff_mask) + hweight32(type_diff_mask);
645 		if (!nr_diffs)	/* Supports all the requested standards */
646 			goto found;
647 
648 		if (nr_diffs < best_nr_diffs) {
649 			best_nr_diffs = nr_diffs;
650 			best_i = i;
651 		}
652 	}
653 
654 	/* FIXME: Would make sense to seek for type "hint" match ? */
655 	if (best_i < 0) {
656 		i = -ENOENT;
657 		goto ret;
658 	}
659 
660 	if (best_nr_diffs > 0U) {
661 		printk(KERN_WARNING
662 		       "Selecting best matching firmware (%u bits differ) for type=(%x), id %016llx:\n",
663 		       best_nr_diffs, type, (unsigned long long)*id);
664 		i = best_i;
665 	}
666 
667 found:
668 	*id = priv->firm[i].id;
669 
670 ret:
671 	if (debug) {
672 		printk(KERN_DEBUG "%s firmware for type=",
673 		       (i < 0) ? "Can't find" : "Found");
674 		dump_firm_type(type);
675 		printk(KERN_DEBUG "(%x), id %016llx.\n", type, (unsigned long long)*id);
676 	}
677 	return i;
678 }
679 
680 static int load_firmware(struct dvb_frontend *fe, unsigned int type,
681 			 v4l2_std_id *id)
682 {
683 	struct xc4000_priv *priv = fe->tuner_priv;
684 	int                pos, rc;
685 	unsigned char      *p;
686 
687 	pos = seek_firmware(fe, type, id);
688 	if (pos < 0)
689 		return pos;
690 
691 	p = priv->firm[pos].ptr;
692 
693 	/* Don't complain when the request fails because of i2c stretching */
694 	priv->ignore_i2c_write_errors = 1;
695 
696 	rc = xc_load_i2c_sequence(fe, p);
697 
698 	priv->ignore_i2c_write_errors = 0;
699 
700 	return rc;
701 }
702 
703 static int xc4000_fwupload(struct dvb_frontend *fe)
704 {
705 	struct xc4000_priv *priv = fe->tuner_priv;
706 	const struct firmware *fw   = NULL;
707 	const unsigned char   *p, *endp;
708 	int                   rc = 0;
709 	int		      n, n_array;
710 	char		      name[33];
711 	const char	      *fname;
712 
713 	if (firmware_name[0] != '\0') {
714 		fname = firmware_name;
715 
716 		dprintk(1, "Reading custom firmware %s\n", fname);
717 		rc = request_firmware(&fw, fname,
718 				      priv->i2c_props.adap->dev.parent);
719 	} else {
720 		fname = XC4000_DEFAULT_FIRMWARE_NEW;
721 		dprintk(1, "Trying to read firmware %s\n", fname);
722 		rc = request_firmware(&fw, fname,
723 				      priv->i2c_props.adap->dev.parent);
724 		if (rc == -ENOENT) {
725 			fname = XC4000_DEFAULT_FIRMWARE;
726 			dprintk(1, "Trying to read firmware %s\n", fname);
727 			rc = request_firmware(&fw, fname,
728 					      priv->i2c_props.adap->dev.parent);
729 		}
730 	}
731 
732 	if (rc < 0) {
733 		if (rc == -ENOENT)
734 			printk(KERN_ERR "Error: firmware %s not found.\n", fname);
735 		else
736 			printk(KERN_ERR "Error %d while requesting firmware %s\n",
737 			       rc, fname);
738 
739 		return rc;
740 	}
741 	dprintk(1, "Loading Firmware: %s\n", fname);
742 
743 	p = fw->data;
744 	endp = p + fw->size;
745 
746 	if (fw->size < sizeof(name) - 1 + 2 + 2) {
747 		printk(KERN_ERR "Error: firmware file %s has invalid size!\n",
748 		       fname);
749 		goto corrupt;
750 	}
751 
752 	memcpy(name, p, sizeof(name) - 1);
753 	name[sizeof(name) - 1] = '\0';
754 	p += sizeof(name) - 1;
755 
756 	priv->firm_version = get_unaligned_le16(p);
757 	p += 2;
758 
759 	n_array = get_unaligned_le16(p);
760 	p += 2;
761 
762 	dprintk(1, "Loading %d firmware images from %s, type: %s, ver %d.%d\n",
763 		n_array, fname, name,
764 		priv->firm_version >> 8, priv->firm_version & 0xff);
765 
766 	priv->firm = kcalloc(n_array, sizeof(*priv->firm), GFP_KERNEL);
767 	if (priv->firm == NULL) {
768 		printk(KERN_ERR "Not enough memory to load firmware file.\n");
769 		rc = -ENOMEM;
770 		goto done;
771 	}
772 	priv->firm_size = n_array;
773 
774 	n = -1;
775 	while (p < endp) {
776 		__u32 type, size;
777 		v4l2_std_id id;
778 		__u16 int_freq = 0;
779 
780 		n++;
781 		if (n >= n_array) {
782 			printk(KERN_ERR "More firmware images in file than were expected!\n");
783 			goto corrupt;
784 		}
785 
786 		/* Checks if there's enough bytes to read */
787 		if (endp - p < sizeof(type) + sizeof(id) + sizeof(size))
788 			goto header;
789 
790 		type = get_unaligned_le32(p);
791 		p += sizeof(type);
792 
793 		id = get_unaligned_le64(p);
794 		p += sizeof(id);
795 
796 		if (type & HAS_IF) {
797 			int_freq = get_unaligned_le16(p);
798 			p += sizeof(int_freq);
799 			if (endp - p < sizeof(size))
800 				goto header;
801 		}
802 
803 		size = get_unaligned_le32(p);
804 		p += sizeof(size);
805 
806 		if (!size || size > endp - p) {
807 			printk(KERN_ERR "Firmware type (%x), id %llx is corrupted (size=%zd, expected %d)\n",
808 			       type, (unsigned long long)id,
809 			       endp - p, size);
810 			goto corrupt;
811 		}
812 
813 		priv->firm[n].ptr = kmemdup(p, size, GFP_KERNEL);
814 		if (priv->firm[n].ptr == NULL) {
815 			printk(KERN_ERR "Not enough memory to load firmware file.\n");
816 			rc = -ENOMEM;
817 			goto done;
818 		}
819 
820 		if (debug) {
821 			printk(KERN_DEBUG "Reading firmware type ");
822 			dump_firm_type_and_int_freq(type, int_freq);
823 			printk(KERN_DEBUG "(%x), id %llx, size=%d.\n",
824 			       type, (unsigned long long)id, size);
825 		}
826 
827 		priv->firm[n].type = type;
828 		priv->firm[n].id   = id;
829 		priv->firm[n].size = size;
830 		priv->firm[n].int_freq = int_freq;
831 
832 		p += size;
833 	}
834 
835 	if (n + 1 != priv->firm_size) {
836 		printk(KERN_ERR "Firmware file is incomplete!\n");
837 		goto corrupt;
838 	}
839 
840 	goto done;
841 
842 header:
843 	printk(KERN_ERR "Firmware header is incomplete!\n");
844 corrupt:
845 	rc = -EINVAL;
846 	printk(KERN_ERR "Error: firmware file is corrupted!\n");
847 
848 done:
849 	release_firmware(fw);
850 	if (rc == 0)
851 		dprintk(1, "Firmware files loaded.\n");
852 
853 	return rc;
854 }
855 
856 static int load_scode(struct dvb_frontend *fe, unsigned int type,
857 			 v4l2_std_id *id, __u16 int_freq, int scode)
858 {
859 	struct xc4000_priv *priv = fe->tuner_priv;
860 	int		pos, rc;
861 	unsigned char	*p;
862 	u8		scode_buf[13];
863 	u8		indirect_mode[5];
864 
865 	dprintk(1, "%s called int_freq=%d\n", __func__, int_freq);
866 
867 	if (!int_freq) {
868 		pos = seek_firmware(fe, type, id);
869 		if (pos < 0)
870 			return pos;
871 	} else {
872 		for (pos = 0; pos < priv->firm_size; pos++) {
873 			if ((priv->firm[pos].int_freq == int_freq) &&
874 			    (priv->firm[pos].type & HAS_IF))
875 				break;
876 		}
877 		if (pos == priv->firm_size)
878 			return -ENOENT;
879 	}
880 
881 	p = priv->firm[pos].ptr;
882 
883 	if (priv->firm[pos].size != 12 * 16 || scode >= 16)
884 		return -EINVAL;
885 	p += 12 * scode;
886 
887 	if (debug) {
888 		tuner_info("Loading SCODE for type=");
889 		dump_firm_type_and_int_freq(priv->firm[pos].type,
890 					    priv->firm[pos].int_freq);
891 		printk(KERN_CONT "(%x), id %016llx.\n", priv->firm[pos].type,
892 		       (unsigned long long)*id);
893 	}
894 
895 	scode_buf[0] = 0x00;
896 	memcpy(&scode_buf[1], p, 12);
897 
898 	/* Enter direct-mode */
899 	rc = xc_write_reg(priv, XREG_DIRECTSITTING_MODE, 0);
900 	if (rc < 0) {
901 		printk(KERN_ERR "failed to put device into direct mode!\n");
902 		return -EIO;
903 	}
904 
905 	rc = xc_send_i2c_data(priv, scode_buf, 13);
906 	if (rc != 0) {
907 		/* Even if the send failed, make sure we set back to indirect
908 		   mode */
909 		printk(KERN_ERR "Failed to set scode %d\n", rc);
910 	}
911 
912 	/* Switch back to indirect-mode */
913 	memset(indirect_mode, 0, sizeof(indirect_mode));
914 	indirect_mode[4] = 0x88;
915 	xc_send_i2c_data(priv, indirect_mode, sizeof(indirect_mode));
916 	msleep(10);
917 
918 	return 0;
919 }
920 
921 static int check_firmware(struct dvb_frontend *fe, unsigned int type,
922 			  v4l2_std_id std, __u16 int_freq)
923 {
924 	struct xc4000_priv         *priv = fe->tuner_priv;
925 	struct firmware_properties new_fw;
926 	int			   rc = 0, is_retry = 0;
927 	u16			   hwmodel;
928 	v4l2_std_id		   std0;
929 	u8			   hw_major = 0, hw_minor = 0, fw_major = 0, fw_minor = 0;
930 
931 	dprintk(1, "%s called\n", __func__);
932 
933 	if (!priv->firm) {
934 		rc = xc4000_fwupload(fe);
935 		if (rc < 0)
936 			return rc;
937 	}
938 
939 retry:
940 	new_fw.type = type;
941 	new_fw.id = std;
942 	new_fw.std_req = std;
943 	new_fw.scode_table = SCODE;
944 	new_fw.scode_nr = 0;
945 	new_fw.int_freq = int_freq;
946 
947 	dprintk(1, "checking firmware, user requested type=");
948 	if (debug) {
949 		dump_firm_type(new_fw.type);
950 		printk(KERN_CONT "(%x), id %016llx, ", new_fw.type,
951 		       (unsigned long long)new_fw.std_req);
952 		if (!int_freq)
953 			printk(KERN_CONT "scode_tbl ");
954 		else
955 			printk(KERN_CONT "int_freq %d, ", new_fw.int_freq);
956 		printk(KERN_CONT "scode_nr %d\n", new_fw.scode_nr);
957 	}
958 
959 	/* No need to reload base firmware if it matches */
960 	if (priv->cur_fw.type & BASE) {
961 		dprintk(1, "BASE firmware not changed.\n");
962 		goto skip_base;
963 	}
964 
965 	/* Updating BASE - forget about all currently loaded firmware */
966 	memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
967 
968 	/* Reset is needed before loading firmware */
969 	rc = xc4000_tuner_reset(fe);
970 	if (rc < 0)
971 		goto fail;
972 
973 	/* BASE firmwares are all std0 */
974 	std0 = 0;
975 	rc = load_firmware(fe, BASE, &std0);
976 	if (rc < 0) {
977 		printk(KERN_ERR "Error %d while loading base firmware\n", rc);
978 		goto fail;
979 	}
980 
981 	/* Load INIT1, if needed */
982 	dprintk(1, "Load init1 firmware, if exists\n");
983 
984 	rc = load_firmware(fe, BASE | INIT1, &std0);
985 	if (rc == -ENOENT)
986 		rc = load_firmware(fe, BASE | INIT1, &std0);
987 	if (rc < 0 && rc != -ENOENT) {
988 		tuner_err("Error %d while loading init1 firmware\n",
989 			  rc);
990 		goto fail;
991 	}
992 
993 skip_base:
994 	/*
995 	 * No need to reload standard specific firmware if base firmware
996 	 * was not reloaded and requested video standards have not changed.
997 	 */
998 	if (priv->cur_fw.type == (BASE | new_fw.type) &&
999 	    priv->cur_fw.std_req == std) {
1000 		dprintk(1, "Std-specific firmware already loaded.\n");
1001 		goto skip_std_specific;
1002 	}
1003 
1004 	/* Reloading std-specific firmware forces a SCODE update */
1005 	priv->cur_fw.scode_table = 0;
1006 
1007 	/* Load the standard firmware */
1008 	rc = load_firmware(fe, new_fw.type, &new_fw.id);
1009 
1010 	if (rc < 0)
1011 		goto fail;
1012 
1013 skip_std_specific:
1014 	if (priv->cur_fw.scode_table == new_fw.scode_table &&
1015 	    priv->cur_fw.scode_nr == new_fw.scode_nr) {
1016 		dprintk(1, "SCODE firmware already loaded.\n");
1017 		goto check_device;
1018 	}
1019 
1020 	/* Load SCODE firmware, if exists */
1021 	rc = load_scode(fe, new_fw.type | new_fw.scode_table, &new_fw.id,
1022 			new_fw.int_freq, new_fw.scode_nr);
1023 	if (rc != 0)
1024 		dprintk(1, "load scode failed %d\n", rc);
1025 
1026 check_device:
1027 	if (xc4000_readreg(priv, XREG_PRODUCT_ID, &hwmodel) < 0) {
1028 		printk(KERN_ERR "Unable to read tuner registers.\n");
1029 		goto fail;
1030 	}
1031 
1032 	if (xc_get_version(priv, &hw_major, &hw_minor, &fw_major,
1033 			   &fw_minor) != 0) {
1034 		printk(KERN_ERR "Unable to read tuner registers.\n");
1035 		goto fail;
1036 	}
1037 
1038 	dprintk(1, "Device is Xceive %d version %d.%d, firmware version %d.%d\n",
1039 		hwmodel, hw_major, hw_minor, fw_major, fw_minor);
1040 
1041 	/* Check firmware version against what we downloaded. */
1042 	if (priv->firm_version != ((fw_major << 8) | fw_minor)) {
1043 		printk(KERN_WARNING
1044 		       "Incorrect readback of firmware version %d.%d.\n",
1045 		       fw_major, fw_minor);
1046 		goto fail;
1047 	}
1048 
1049 	/* Check that the tuner hardware model remains consistent over time. */
1050 	if (priv->hwmodel == 0 &&
1051 	    (hwmodel == XC_PRODUCT_ID_XC4000 ||
1052 	     hwmodel == XC_PRODUCT_ID_XC4100)) {
1053 		priv->hwmodel = hwmodel;
1054 		priv->hwvers = (hw_major << 8) | hw_minor;
1055 	} else if (priv->hwmodel == 0 || priv->hwmodel != hwmodel ||
1056 		   priv->hwvers != ((hw_major << 8) | hw_minor)) {
1057 		printk(KERN_WARNING
1058 		       "Read invalid device hardware information - tuner hung?\n");
1059 		goto fail;
1060 	}
1061 
1062 	priv->cur_fw = new_fw;
1063 
1064 	/*
1065 	 * By setting BASE in cur_fw.type only after successfully loading all
1066 	 * firmwares, we can:
1067 	 * 1. Identify that BASE firmware with type=0 has been loaded;
1068 	 * 2. Tell whether BASE firmware was just changed the next time through.
1069 	 */
1070 	priv->cur_fw.type |= BASE;
1071 
1072 	return 0;
1073 
1074 fail:
1075 	memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
1076 	if (!is_retry) {
1077 		msleep(50);
1078 		is_retry = 1;
1079 		dprintk(1, "Retrying firmware load\n");
1080 		goto retry;
1081 	}
1082 
1083 	if (rc == -ENOENT)
1084 		rc = -EINVAL;
1085 	return rc;
1086 }
1087 
1088 static void xc_debug_dump(struct xc4000_priv *priv)
1089 {
1090 	u16	adc_envelope;
1091 	u32	freq_error_hz = 0;
1092 	u16	lock_status;
1093 	u32	hsync_freq_hz = 0;
1094 	u16	frame_lines;
1095 	u16	quality;
1096 	u16	signal = 0;
1097 	u16	noise = 0;
1098 	u8	hw_majorversion = 0, hw_minorversion = 0;
1099 	u8	fw_majorversion = 0, fw_minorversion = 0;
1100 
1101 	xc_get_adc_envelope(priv, &adc_envelope);
1102 	dprintk(1, "*** ADC envelope (0-1023) = %d\n", adc_envelope);
1103 
1104 	xc_get_frequency_error(priv, &freq_error_hz);
1105 	dprintk(1, "*** Frequency error = %d Hz\n", freq_error_hz);
1106 
1107 	xc_get_lock_status(priv, &lock_status);
1108 	dprintk(1, "*** Lock status (0-Wait, 1-Locked, 2-No-signal) = %d\n",
1109 		lock_status);
1110 
1111 	xc_get_version(priv, &hw_majorversion, &hw_minorversion,
1112 		       &fw_majorversion, &fw_minorversion);
1113 	dprintk(1, "*** HW: V%02x.%02x, FW: V%02x.%02x\n",
1114 		hw_majorversion, hw_minorversion,
1115 		fw_majorversion, fw_minorversion);
1116 
1117 	if (priv->video_standard < XC4000_DTV6) {
1118 		xc_get_hsync_freq(priv, &hsync_freq_hz);
1119 		dprintk(1, "*** Horizontal sync frequency = %d Hz\n",
1120 			hsync_freq_hz);
1121 
1122 		xc_get_frame_lines(priv, &frame_lines);
1123 		dprintk(1, "*** Frame lines = %d\n", frame_lines);
1124 	}
1125 
1126 	xc_get_quality(priv, &quality);
1127 	dprintk(1, "*** Quality (0:<8dB, 7:>56dB) = %d\n", quality);
1128 
1129 	xc_get_signal_level(priv, &signal);
1130 	dprintk(1, "*** Signal level = -%ddB (%d)\n", signal >> 8, signal);
1131 
1132 	xc_get_noise_level(priv, &noise);
1133 	dprintk(1, "*** Noise level = %ddB (%d)\n", noise >> 8, noise);
1134 }
1135 
1136 static int xc4000_set_params(struct dvb_frontend *fe)
1137 {
1138 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1139 	u32 delsys = c->delivery_system;
1140 	u32 bw = c->bandwidth_hz;
1141 	struct xc4000_priv *priv = fe->tuner_priv;
1142 	unsigned int type;
1143 	int	ret = -EREMOTEIO;
1144 
1145 	dprintk(1, "%s() frequency=%d (Hz)\n", __func__, c->frequency);
1146 
1147 	mutex_lock(&priv->lock);
1148 
1149 	switch (delsys) {
1150 	case SYS_ATSC:
1151 		dprintk(1, "%s() VSB modulation\n", __func__);
1152 		priv->rf_mode = XC_RF_MODE_AIR;
1153 		priv->freq_offset = 1750000;
1154 		priv->video_standard = XC4000_DTV6;
1155 		type = DTV6;
1156 		break;
1157 	case SYS_DVBC_ANNEX_B:
1158 		dprintk(1, "%s() QAM modulation\n", __func__);
1159 		priv->rf_mode = XC_RF_MODE_CABLE;
1160 		priv->freq_offset = 1750000;
1161 		priv->video_standard = XC4000_DTV6;
1162 		type = DTV6;
1163 		break;
1164 	case SYS_DVBT:
1165 	case SYS_DVBT2:
1166 		dprintk(1, "%s() OFDM\n", __func__);
1167 		if (bw == 0) {
1168 			if (c->frequency < 400000000) {
1169 				priv->freq_offset = 2250000;
1170 			} else {
1171 				priv->freq_offset = 2750000;
1172 			}
1173 			priv->video_standard = XC4000_DTV7_8;
1174 			type = DTV78;
1175 		} else if (bw <= 6000000) {
1176 			priv->video_standard = XC4000_DTV6;
1177 			priv->freq_offset = 1750000;
1178 			type = DTV6;
1179 		} else if (bw <= 7000000) {
1180 			priv->video_standard = XC4000_DTV7;
1181 			priv->freq_offset = 2250000;
1182 			type = DTV7;
1183 		} else {
1184 			priv->video_standard = XC4000_DTV8;
1185 			priv->freq_offset = 2750000;
1186 			type = DTV8;
1187 		}
1188 		priv->rf_mode = XC_RF_MODE_AIR;
1189 		break;
1190 	default:
1191 		printk(KERN_ERR "xc4000 delivery system not supported!\n");
1192 		ret = -EINVAL;
1193 		goto fail;
1194 	}
1195 
1196 	priv->freq_hz = c->frequency - priv->freq_offset;
1197 
1198 	dprintk(1, "%s() frequency=%d (compensated)\n",
1199 		__func__, priv->freq_hz);
1200 
1201 	/* Make sure the correct firmware type is loaded */
1202 	if (check_firmware(fe, type, 0, priv->if_khz) != 0)
1203 		goto fail;
1204 
1205 	priv->bandwidth = c->bandwidth_hz;
1206 
1207 	ret = xc_set_signal_source(priv, priv->rf_mode);
1208 	if (ret != 0) {
1209 		printk(KERN_ERR "xc4000: xc_set_signal_source(%d) failed\n",
1210 		       priv->rf_mode);
1211 		goto fail;
1212 	} else {
1213 		u16	video_mode, audio_mode;
1214 		video_mode = xc4000_standard[priv->video_standard].video_mode;
1215 		audio_mode = xc4000_standard[priv->video_standard].audio_mode;
1216 		if (type == DTV6 && priv->firm_version != 0x0102)
1217 			video_mode |= 0x0001;
1218 		ret = xc_set_tv_standard(priv, video_mode, audio_mode);
1219 		if (ret != 0) {
1220 			printk(KERN_ERR "xc4000: xc_set_tv_standard failed\n");
1221 			/* DJH - do not return when it fails... */
1222 			/* goto fail; */
1223 		}
1224 	}
1225 
1226 	if (xc_write_reg(priv, XREG_D_CODE, 0) == 0)
1227 		ret = 0;
1228 	if (priv->dvb_amplitude != 0) {
1229 		if (xc_write_reg(priv, XREG_AMPLITUDE,
1230 				 (priv->firm_version != 0x0102 ||
1231 				  priv->dvb_amplitude != 134 ?
1232 				  priv->dvb_amplitude : 132)) != 0)
1233 			ret = -EREMOTEIO;
1234 	}
1235 	if (priv->set_smoothedcvbs != 0) {
1236 		if (xc_write_reg(priv, XREG_SMOOTHEDCVBS, 1) != 0)
1237 			ret = -EREMOTEIO;
1238 	}
1239 	if (ret != 0) {
1240 		printk(KERN_ERR "xc4000: setting registers failed\n");
1241 		/* goto fail; */
1242 	}
1243 
1244 	xc_tune_channel(priv, priv->freq_hz);
1245 
1246 	ret = 0;
1247 
1248 fail:
1249 	mutex_unlock(&priv->lock);
1250 
1251 	return ret;
1252 }
1253 
1254 static int xc4000_set_analog_params(struct dvb_frontend *fe,
1255 	struct analog_parameters *params)
1256 {
1257 	struct xc4000_priv *priv = fe->tuner_priv;
1258 	unsigned int type = 0;
1259 	int	ret = -EREMOTEIO;
1260 
1261 	if (params->mode == V4L2_TUNER_RADIO) {
1262 		dprintk(1, "%s() frequency=%d (in units of 62.5Hz)\n",
1263 			__func__, params->frequency);
1264 
1265 		mutex_lock(&priv->lock);
1266 
1267 		params->std = 0;
1268 		priv->freq_hz = params->frequency * 125L / 2;
1269 
1270 		if (audio_std & XC4000_AUDIO_STD_INPUT1) {
1271 			priv->video_standard = XC4000_FM_Radio_INPUT1;
1272 			type = FM | INPUT1;
1273 		} else {
1274 			priv->video_standard = XC4000_FM_Radio_INPUT2;
1275 			type = FM | INPUT2;
1276 		}
1277 
1278 		goto tune_channel;
1279 	}
1280 
1281 	dprintk(1, "%s() frequency=%d (in units of 62.5khz)\n",
1282 		__func__, params->frequency);
1283 
1284 	mutex_lock(&priv->lock);
1285 
1286 	/* params->frequency is in units of 62.5khz */
1287 	priv->freq_hz = params->frequency * 62500;
1288 
1289 	params->std &= V4L2_STD_ALL;
1290 	/* if std is not defined, choose one */
1291 	if (!params->std)
1292 		params->std = V4L2_STD_PAL_BG;
1293 
1294 	if (audio_std & XC4000_AUDIO_STD_MONO)
1295 		type = MONO;
1296 
1297 	if (params->std & V4L2_STD_MN) {
1298 		params->std = V4L2_STD_MN;
1299 		if (audio_std & XC4000_AUDIO_STD_MONO) {
1300 			priv->video_standard = XC4000_MN_NTSC_PAL_Mono;
1301 		} else if (audio_std & XC4000_AUDIO_STD_A2) {
1302 			params->std |= V4L2_STD_A2;
1303 			priv->video_standard = XC4000_MN_NTSC_PAL_A2;
1304 		} else {
1305 			params->std |= V4L2_STD_BTSC;
1306 			priv->video_standard = XC4000_MN_NTSC_PAL_BTSC;
1307 		}
1308 		goto tune_channel;
1309 	}
1310 
1311 	if (params->std & V4L2_STD_PAL_BG) {
1312 		params->std = V4L2_STD_PAL_BG;
1313 		if (audio_std & XC4000_AUDIO_STD_MONO) {
1314 			priv->video_standard = XC4000_BG_PAL_MONO;
1315 		} else if (!(audio_std & XC4000_AUDIO_STD_A2)) {
1316 			if (!(audio_std & XC4000_AUDIO_STD_B)) {
1317 				params->std |= V4L2_STD_NICAM_A;
1318 				priv->video_standard = XC4000_BG_PAL_NICAM;
1319 			} else {
1320 				params->std |= V4L2_STD_NICAM_B;
1321 				priv->video_standard = XC4000_BG_PAL_NICAM;
1322 			}
1323 		} else {
1324 			if (!(audio_std & XC4000_AUDIO_STD_B)) {
1325 				params->std |= V4L2_STD_A2_A;
1326 				priv->video_standard = XC4000_BG_PAL_A2;
1327 			} else {
1328 				params->std |= V4L2_STD_A2_B;
1329 				priv->video_standard = XC4000_BG_PAL_A2;
1330 			}
1331 		}
1332 		goto tune_channel;
1333 	}
1334 
1335 	if (params->std & V4L2_STD_PAL_I) {
1336 		/* default to NICAM audio standard */
1337 		params->std = V4L2_STD_PAL_I | V4L2_STD_NICAM;
1338 		if (audio_std & XC4000_AUDIO_STD_MONO)
1339 			priv->video_standard = XC4000_I_PAL_NICAM_MONO;
1340 		else
1341 			priv->video_standard = XC4000_I_PAL_NICAM;
1342 		goto tune_channel;
1343 	}
1344 
1345 	if (params->std & V4L2_STD_PAL_DK) {
1346 		params->std = V4L2_STD_PAL_DK;
1347 		if (audio_std & XC4000_AUDIO_STD_MONO) {
1348 			priv->video_standard = XC4000_DK_PAL_MONO;
1349 		} else if (audio_std & XC4000_AUDIO_STD_A2) {
1350 			params->std |= V4L2_STD_A2;
1351 			priv->video_standard = XC4000_DK_PAL_A2;
1352 		} else {
1353 			params->std |= V4L2_STD_NICAM;
1354 			priv->video_standard = XC4000_DK_PAL_NICAM;
1355 		}
1356 		goto tune_channel;
1357 	}
1358 
1359 	if (params->std & V4L2_STD_SECAM_DK) {
1360 		/* default to A2 audio standard */
1361 		params->std = V4L2_STD_SECAM_DK | V4L2_STD_A2;
1362 		if (audio_std & XC4000_AUDIO_STD_L) {
1363 			type = 0;
1364 			priv->video_standard = XC4000_DK_SECAM_NICAM;
1365 		} else if (audio_std & XC4000_AUDIO_STD_MONO) {
1366 			priv->video_standard = XC4000_DK_SECAM_A2MONO;
1367 		} else if (audio_std & XC4000_AUDIO_STD_K3) {
1368 			params->std |= V4L2_STD_SECAM_K3;
1369 			priv->video_standard = XC4000_DK_SECAM_A2LDK3;
1370 		} else {
1371 			priv->video_standard = XC4000_DK_SECAM_A2DK1;
1372 		}
1373 		goto tune_channel;
1374 	}
1375 
1376 	if (params->std & V4L2_STD_SECAM_L) {
1377 		/* default to NICAM audio standard */
1378 		type = 0;
1379 		params->std = V4L2_STD_SECAM_L | V4L2_STD_NICAM;
1380 		priv->video_standard = XC4000_L_SECAM_NICAM;
1381 		goto tune_channel;
1382 	}
1383 
1384 	if (params->std & V4L2_STD_SECAM_LC) {
1385 		/* default to NICAM audio standard */
1386 		type = 0;
1387 		params->std = V4L2_STD_SECAM_LC | V4L2_STD_NICAM;
1388 		priv->video_standard = XC4000_LC_SECAM_NICAM;
1389 		goto tune_channel;
1390 	}
1391 
1392 tune_channel:
1393 	/* FIXME: it could be air. */
1394 	priv->rf_mode = XC_RF_MODE_CABLE;
1395 
1396 	if (check_firmware(fe, type, params->std,
1397 			   xc4000_standard[priv->video_standard].int_freq) != 0)
1398 		goto fail;
1399 
1400 	ret = xc_set_signal_source(priv, priv->rf_mode);
1401 	if (ret != 0) {
1402 		printk(KERN_ERR
1403 		       "xc4000: xc_set_signal_source(%d) failed\n",
1404 		       priv->rf_mode);
1405 		goto fail;
1406 	} else {
1407 		u16	video_mode, audio_mode;
1408 		video_mode = xc4000_standard[priv->video_standard].video_mode;
1409 		audio_mode = xc4000_standard[priv->video_standard].audio_mode;
1410 		if (priv->video_standard < XC4000_BG_PAL_A2) {
1411 			if (type & NOGD)
1412 				video_mode &= 0xFF7F;
1413 		} else if (priv->video_standard < XC4000_I_PAL_NICAM) {
1414 			if (priv->firm_version == 0x0102)
1415 				video_mode &= 0xFEFF;
1416 			if (audio_std & XC4000_AUDIO_STD_B)
1417 				video_mode |= 0x0080;
1418 		}
1419 		ret = xc_set_tv_standard(priv, video_mode, audio_mode);
1420 		if (ret != 0) {
1421 			printk(KERN_ERR "xc4000: xc_set_tv_standard failed\n");
1422 			goto fail;
1423 		}
1424 	}
1425 
1426 	if (xc_write_reg(priv, XREG_D_CODE, 0) == 0)
1427 		ret = 0;
1428 	if (xc_write_reg(priv, XREG_AMPLITUDE, 1) != 0)
1429 		ret = -EREMOTEIO;
1430 	if (priv->set_smoothedcvbs != 0) {
1431 		if (xc_write_reg(priv, XREG_SMOOTHEDCVBS, 1) != 0)
1432 			ret = -EREMOTEIO;
1433 	}
1434 	if (ret != 0) {
1435 		printk(KERN_ERR "xc4000: setting registers failed\n");
1436 		goto fail;
1437 	}
1438 
1439 	xc_tune_channel(priv, priv->freq_hz);
1440 
1441 	ret = 0;
1442 
1443 fail:
1444 	mutex_unlock(&priv->lock);
1445 
1446 	return ret;
1447 }
1448 
1449 static int xc4000_get_signal(struct dvb_frontend *fe, u16 *strength)
1450 {
1451 	struct xc4000_priv *priv = fe->tuner_priv;
1452 	u16 value = 0;
1453 	int rc;
1454 
1455 	mutex_lock(&priv->lock);
1456 	rc = xc4000_readreg(priv, XREG_SIGNAL_LEVEL, &value);
1457 	mutex_unlock(&priv->lock);
1458 
1459 	if (rc < 0)
1460 		goto ret;
1461 
1462 	/* Information from real testing of DVB-T and radio part,
1463 	   coefficient for one dB is 0xff.
1464 	 */
1465 	tuner_dbg("Signal strength: -%ddB (%05d)\n", value >> 8, value);
1466 
1467 	/* all known digital modes */
1468 	if ((priv->video_standard == XC4000_DTV6) ||
1469 	    (priv->video_standard == XC4000_DTV7) ||
1470 	    (priv->video_standard == XC4000_DTV7_8) ||
1471 	    (priv->video_standard == XC4000_DTV8))
1472 		goto digital;
1473 
1474 	/* Analog mode has NOISE LEVEL important, signal
1475 	   depends only on gain of antenna and amplifiers,
1476 	   but it doesn't tell anything about real quality
1477 	   of reception.
1478 	 */
1479 	mutex_lock(&priv->lock);
1480 	rc = xc4000_readreg(priv, XREG_NOISE_LEVEL, &value);
1481 	mutex_unlock(&priv->lock);
1482 
1483 	tuner_dbg("Noise level: %ddB (%05d)\n", value >> 8, value);
1484 
1485 	/* highest noise level: 32dB */
1486 	if (value >= 0x2000) {
1487 		value = 0;
1488 	} else {
1489 		value = (~value << 3) & 0xffff;
1490 	}
1491 
1492 	goto ret;
1493 
1494 	/* Digital mode has SIGNAL LEVEL important and real
1495 	   noise level is stored in demodulator registers.
1496 	 */
1497 digital:
1498 	/* best signal: -50dB */
1499 	if (value <= 0x3200) {
1500 		value = 0xffff;
1501 	/* minimum: -114dB - should be 0x7200 but real zero is 0x713A */
1502 	} else if (value >= 0x713A) {
1503 		value = 0;
1504 	} else {
1505 		value = ~(value - 0x3200) << 2;
1506 	}
1507 
1508 ret:
1509 	*strength = value;
1510 
1511 	return rc;
1512 }
1513 
1514 static int xc4000_get_frequency(struct dvb_frontend *fe, u32 *freq)
1515 {
1516 	struct xc4000_priv *priv = fe->tuner_priv;
1517 
1518 	*freq = priv->freq_hz + priv->freq_offset;
1519 
1520 	if (debug) {
1521 		mutex_lock(&priv->lock);
1522 		if ((priv->cur_fw.type
1523 		     & (BASE | FM | DTV6 | DTV7 | DTV78 | DTV8)) == BASE) {
1524 			u16	snr = 0;
1525 			if (xc4000_readreg(priv, XREG_SNR, &snr) == 0) {
1526 				mutex_unlock(&priv->lock);
1527 				dprintk(1, "%s() freq = %u, SNR = %d\n",
1528 					__func__, *freq, snr);
1529 				return 0;
1530 			}
1531 		}
1532 		mutex_unlock(&priv->lock);
1533 	}
1534 
1535 	dprintk(1, "%s()\n", __func__);
1536 
1537 	return 0;
1538 }
1539 
1540 static int xc4000_get_bandwidth(struct dvb_frontend *fe, u32 *bw)
1541 {
1542 	struct xc4000_priv *priv = fe->tuner_priv;
1543 	dprintk(1, "%s()\n", __func__);
1544 
1545 	*bw = priv->bandwidth;
1546 	return 0;
1547 }
1548 
1549 static int xc4000_get_status(struct dvb_frontend *fe, u32 *status)
1550 {
1551 	struct xc4000_priv *priv = fe->tuner_priv;
1552 	u16	lock_status = 0;
1553 
1554 	mutex_lock(&priv->lock);
1555 
1556 	if (priv->cur_fw.type & BASE)
1557 		xc_get_lock_status(priv, &lock_status);
1558 
1559 	*status = (lock_status == 1 ?
1560 		   TUNER_STATUS_LOCKED | TUNER_STATUS_STEREO : 0);
1561 	if (priv->cur_fw.type & (DTV6 | DTV7 | DTV78 | DTV8))
1562 		*status &= (~TUNER_STATUS_STEREO);
1563 
1564 	mutex_unlock(&priv->lock);
1565 
1566 	dprintk(2, "%s() lock_status = %d\n", __func__, lock_status);
1567 
1568 	return 0;
1569 }
1570 
1571 static int xc4000_sleep(struct dvb_frontend *fe)
1572 {
1573 	struct xc4000_priv *priv = fe->tuner_priv;
1574 	int	ret = 0;
1575 
1576 	dprintk(1, "%s()\n", __func__);
1577 
1578 	mutex_lock(&priv->lock);
1579 
1580 	/* Avoid firmware reload on slow devices */
1581 	if ((no_poweroff == 2 ||
1582 	     (no_poweroff == 0 && priv->default_pm != 0)) &&
1583 	    (priv->cur_fw.type & BASE) != 0) {
1584 		/* force reset and firmware reload */
1585 		priv->cur_fw.type = XC_POWERED_DOWN;
1586 
1587 		if (xc_write_reg(priv, XREG_POWER_DOWN, 0) != 0) {
1588 			printk(KERN_ERR
1589 			       "xc4000: %s() unable to shutdown tuner\n",
1590 			       __func__);
1591 			ret = -EREMOTEIO;
1592 		}
1593 		msleep(20);
1594 	}
1595 
1596 	mutex_unlock(&priv->lock);
1597 
1598 	return ret;
1599 }
1600 
1601 static int xc4000_init(struct dvb_frontend *fe)
1602 {
1603 	dprintk(1, "%s()\n", __func__);
1604 
1605 	return 0;
1606 }
1607 
1608 static void xc4000_release(struct dvb_frontend *fe)
1609 {
1610 	struct xc4000_priv *priv = fe->tuner_priv;
1611 
1612 	dprintk(1, "%s()\n", __func__);
1613 
1614 	mutex_lock(&xc4000_list_mutex);
1615 
1616 	if (priv)
1617 		hybrid_tuner_release_state(priv);
1618 
1619 	mutex_unlock(&xc4000_list_mutex);
1620 
1621 	fe->tuner_priv = NULL;
1622 }
1623 
1624 static const struct dvb_tuner_ops xc4000_tuner_ops = {
1625 	.info = {
1626 		.name              = "Xceive XC4000",
1627 		.frequency_min_hz  =    1 * MHz,
1628 		.frequency_max_hz  = 1023 * MHz,
1629 		.frequency_step_hz =   50 * kHz,
1630 	},
1631 
1632 	.release	   = xc4000_release,
1633 	.init		   = xc4000_init,
1634 	.sleep		   = xc4000_sleep,
1635 
1636 	.set_params	   = xc4000_set_params,
1637 	.set_analog_params = xc4000_set_analog_params,
1638 	.get_frequency	   = xc4000_get_frequency,
1639 	.get_rf_strength   = xc4000_get_signal,
1640 	.get_bandwidth	   = xc4000_get_bandwidth,
1641 	.get_status	   = xc4000_get_status
1642 };
1643 
1644 struct dvb_frontend *xc4000_attach(struct dvb_frontend *fe,
1645 				   struct i2c_adapter *i2c,
1646 				   struct xc4000_config *cfg)
1647 {
1648 	struct xc4000_priv *priv = NULL;
1649 	int	instance;
1650 	u16	id = 0;
1651 
1652 	dprintk(1, "%s(%d-%04x)\n", __func__,
1653 		i2c ? i2c_adapter_id(i2c) : -1,
1654 		cfg ? cfg->i2c_address : -1);
1655 
1656 	mutex_lock(&xc4000_list_mutex);
1657 
1658 	instance = hybrid_tuner_request_state(struct xc4000_priv, priv,
1659 					      hybrid_tuner_instance_list,
1660 					      i2c, cfg->i2c_address, "xc4000");
1661 	switch (instance) {
1662 	case 0:
1663 		goto fail;
1664 	case 1:
1665 		/* new tuner instance */
1666 		priv->bandwidth = 6000000;
1667 		/* set default configuration */
1668 		priv->if_khz = 4560;
1669 		priv->default_pm = 0;
1670 		priv->dvb_amplitude = 134;
1671 		priv->set_smoothedcvbs = 1;
1672 		mutex_init(&priv->lock);
1673 		fe->tuner_priv = priv;
1674 		break;
1675 	default:
1676 		/* existing tuner instance */
1677 		fe->tuner_priv = priv;
1678 		break;
1679 	}
1680 
1681 	if (cfg->if_khz != 0) {
1682 		/* copy configuration if provided by the caller */
1683 		priv->if_khz = cfg->if_khz;
1684 		priv->default_pm = cfg->default_pm;
1685 		priv->dvb_amplitude = cfg->dvb_amplitude;
1686 		priv->set_smoothedcvbs = cfg->set_smoothedcvbs;
1687 	}
1688 
1689 	/* Check if firmware has been loaded. It is possible that another
1690 	   instance of the driver has loaded the firmware.
1691 	 */
1692 
1693 	if (instance == 1) {
1694 		if (xc4000_readreg(priv, XREG_PRODUCT_ID, &id) != 0)
1695 			goto fail;
1696 	} else {
1697 		id = ((priv->cur_fw.type & BASE) != 0 ?
1698 		      priv->hwmodel : XC_PRODUCT_ID_FW_NOT_LOADED);
1699 	}
1700 
1701 	switch (id) {
1702 	case XC_PRODUCT_ID_XC4000:
1703 	case XC_PRODUCT_ID_XC4100:
1704 		printk(KERN_INFO
1705 			"xc4000: Successfully identified at address 0x%02x\n",
1706 			cfg->i2c_address);
1707 		printk(KERN_INFO
1708 			"xc4000: Firmware has been loaded previously\n");
1709 		break;
1710 	case XC_PRODUCT_ID_FW_NOT_LOADED:
1711 		printk(KERN_INFO
1712 			"xc4000: Successfully identified at address 0x%02x\n",
1713 			cfg->i2c_address);
1714 		printk(KERN_INFO
1715 			"xc4000: Firmware has not been loaded previously\n");
1716 		break;
1717 	default:
1718 		printk(KERN_ERR
1719 			"xc4000: Device not found at addr 0x%02x (0x%x)\n",
1720 			cfg->i2c_address, id);
1721 		goto fail;
1722 	}
1723 
1724 	mutex_unlock(&xc4000_list_mutex);
1725 
1726 	memcpy(&fe->ops.tuner_ops, &xc4000_tuner_ops,
1727 		sizeof(struct dvb_tuner_ops));
1728 
1729 	if (instance == 1) {
1730 		int	ret;
1731 		mutex_lock(&priv->lock);
1732 		ret = xc4000_fwupload(fe);
1733 		mutex_unlock(&priv->lock);
1734 		if (ret != 0)
1735 			goto fail2;
1736 	}
1737 
1738 	return fe;
1739 fail:
1740 	mutex_unlock(&xc4000_list_mutex);
1741 fail2:
1742 	xc4000_release(fe);
1743 	return NULL;
1744 }
1745 EXPORT_SYMBOL(xc4000_attach);
1746 
1747 MODULE_AUTHOR("Steven Toth, Davide Ferri");
1748 MODULE_DESCRIPTION("Xceive xc4000 silicon tuner driver");
1749 MODULE_LICENSE("GPL");
1750 MODULE_FIRMWARE(XC4000_DEFAULT_FIRMWARE_NEW);
1751 MODULE_FIRMWARE(XC4000_DEFAULT_FIRMWARE);
1752