tuner-xc2028.c 27.9 KB
Newer Older
1 2
/* tuner-xc2028
 *
3
 * Copyright (c) 2007-2008 Mauro Carvalho Chehab (mchehab@infradead.org)
4
 *
5 6
 * Copyright (c) 2007 Michel Ludwig (michel.ludwig@gmail.com)
 *       - frontend interface
7
 *
8 9 10 11 12 13
 * This code is placed under the terms of the GNU General Public License v2
 */

#include <linux/i2c.h>
#include <asm/div64.h>
#include <linux/firmware.h>
14
#include <linux/videodev2.h>
15
#include <linux/delay.h>
16
#include <media/tuner.h>
17
#include <linux/mutex.h>
18
#include "tuner-i2c.h"
19
#include "tuner-xc2028.h"
20
#include "tuner-xc2028-types.h"
21

22 23 24
#include <linux/dvb/frontend.h>
#include "dvb_frontend.h"

25

26 27 28 29
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "enable verbose debug messages");

30 31 32 33 34 35 36 37 38 39 40 41 42 43
static char audio_std[8];
module_param_string(audio_std, audio_std, sizeof(audio_std), 0);
MODULE_PARM_DESC(audio_std,
	"Audio standard. XC3028 audio decoder explicitly "
	"needs to know what audio\n"
	"standard is needed for some video standards with audio A2 or NICAM.\n"
	"The valid values are:\n"
	"A2\n"
	"A2/A\n"
	"A2/B\n"
	"NICAM\n"
	"NICAM/A\n"
	"NICAM/B\n");

44 45 46 47 48
static char firmware_name[FIRMWARE_NAME_MAX];
module_param_string(firmware_name, firmware_name, sizeof(firmware_name), 0);
MODULE_PARM_DESC(firmware_name, "Firmware file name. Allows overriding the "
				"default firmware name\n");

49
static LIST_HEAD(hybrid_tuner_instance_list);
50 51
static DEFINE_MUTEX(xc2028_list_mutex);

52 53 54 55
/* struct for storing firmware table */
struct firmware_description {
	unsigned int  type;
	v4l2_std_id   id;
56
	__u16         int_freq;
57 58 59
	unsigned char *ptr;
	unsigned int  size;
};
60

61 62 63 64
struct firmware_properties {
	unsigned int	type;
	v4l2_std_id	id;
	v4l2_std_id	std_req;
65
	__u16		int_freq;
66 67 68 69
	unsigned int	scode_table;
	int 		scode_nr;
};

70
struct xc2028_data {
71
	struct list_head        hybrid_tuner_instance_list;
72 73 74 75
	struct tuner_i2c_props  i2c_props;
	int                     (*tuner_callback) (void *dev,
						   int command, int arg);
	void			*video_dev;
76 77 78 79
	__u32			frequency;

	struct firmware_description *firm;
	int			firm_size;
80
	__u16			firm_version;
81

82 83 84
	__u16			hwmodel;
	__u16			hwvers;

85
	struct xc2028_ctrl	ctrl;
86

87
	struct firmware_properties cur_fw;
88 89

	struct mutex lock;
90 91
};

92 93 94 95 96 97 98 99 100 101 102 103 104
#define i2c_send(priv, buf, size) ({					\
	int _rc;							\
	_rc = tuner_i2c_xfer_send(&priv->i2c_props, buf, size);		\
	if (size != _rc)						\
		tuner_info("i2c output error: rc = %d (should be %d)\n",\
			   _rc, (int)size);				\
	_rc;								\
})

#define i2c_rcv(priv, buf, size) ({					\
	int _rc;							\
	_rc = tuner_i2c_xfer_recv(&priv->i2c_props, buf, size);		\
	if (size != _rc)						\
105
		tuner_err("i2c input error: rc = %d (should be %d)\n",	\
106 107 108
			   _rc, (int)size); 				\
	_rc;								\
})
109

110 111 112 113 114 115 116 117 118 119
#define i2c_send_recv(priv, obuf, osize, ibuf, isize) ({		\
	int _rc;							\
	_rc = tuner_i2c_xfer_send_recv(&priv->i2c_props, obuf, osize,	\
				       ibuf, isize);			\
	if (isize != _rc)						\
		tuner_err("i2c input error: rc = %d (should be %d)\n",	\
			   _rc, (int)isize); 				\
	_rc;								\
})

120
#define send_seq(priv, data...)	({					\
121
	static u8 _val[] = data;					\
122
	int _rc;							\
123
	if (sizeof(_val) !=						\
124
			(_rc = tuner_i2c_xfer_send(&priv->i2c_props,	\
125
						_val, sizeof(_val)))) {	\
126 127 128 129 130
		tuner_err("Error on line %d: %d\n", __LINE__, _rc);	\
	} else 								\
		msleep(10);						\
	_rc;								\
})
131

132
static int xc2028_get_reg(struct xc2028_data *priv, u16 reg, u16 *val)
133
{
134
	unsigned char buf[2];
135
	unsigned char ibuf[2];
136

137
	tuner_dbg("%s %04x called\n", __func__, reg);
138

139
	buf[0] = reg >> 8;
140
	buf[1] = (unsigned char) reg;
141

142 143
	if (i2c_send_recv(priv, buf, 2, ibuf, 2) != 2)
		return -EIO;
144

145 146
	*val = (ibuf[1]) | (ibuf[0] << 8);
	return 0;
147 148
}

149
#define dump_firm_type(t) 	dump_firm_type_and_int_freq(t, 0)
150
static void dump_firm_type_and_int_freq(unsigned int type, u16 int_freq)
151 152 153
{
	 if (type & BASE)
		printk("BASE ");
154 155
	 if (type & INIT1)
		printk("INIT1 ");
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
	 if (type & F8MHZ)
		printk("F8MHZ ");
	 if (type & MTS)
		printk("MTS ");
	 if (type & D2620)
		printk("D2620 ");
	 if (type & D2633)
		printk("D2633 ");
	 if (type & DTV6)
		printk("DTV6 ");
	 if (type & QAM)
		printk("QAM ");
	 if (type & DTV7)
		printk("DTV7 ");
	 if (type & DTV78)
		printk("DTV78 ");
	 if (type & DTV8)
		printk("DTV8 ");
	 if (type & FM)
		printk("FM ");
	 if (type & INPUT1)
		printk("INPUT1 ");
	 if (type & LCD)
		printk("LCD ");
	 if (type & NOGD)
		printk("NOGD ");
	 if (type & MONO)
		printk("MONO ");
	 if (type & ATSC)
		printk("ATSC ");
	 if (type & IF)
		printk("IF ");
	 if (type & LG60)
		printk("LG60 ");
	 if (type & ATI638)
		printk("ATI638 ");
	 if (type & OREN538)
		printk("OREN538 ");
	 if (type & OREN36)
		printk("OREN36 ");
	 if (type & TOYOTA388)
		printk("TOYOTA388 ");
	 if (type & TOYOTA794)
		printk("TOYOTA794 ");
	 if (type & DIBCOM52)
		printk("DIBCOM52 ");
	 if (type & ZARLINK456)
		printk("ZARLINK456 ");
	 if (type & CHINA)
		printk("CHINA ");
	 if (type & F6MHZ)
		printk("F6MHZ ");
	 if (type & INPUT2)
		printk("INPUT2 ");
	 if (type & SCODE)
		printk("SCODE ");
212 213
	 if (type & HAS_IF)
		printk("HAS_IF_%d ", int_freq);
214 215
}

216
static  v4l2_std_id parse_audio_std_option(void)
217
{
218
	if (strcasecmp(audio_std, "A2") == 0)
219
		return V4L2_STD_A2;
220
	if (strcasecmp(audio_std, "A2/A") == 0)
221
		return V4L2_STD_A2_A;
222
	if (strcasecmp(audio_std, "A2/B") == 0)
223
		return V4L2_STD_A2_B;
224
	if (strcasecmp(audio_std, "NICAM") == 0)
225
		return V4L2_STD_NICAM;
226
	if (strcasecmp(audio_std, "NICAM/A") == 0)
227
		return V4L2_STD_NICAM_A;
228
	if (strcasecmp(audio_std, "NICAM/B") == 0)
229 230 231 232 233
		return V4L2_STD_NICAM_B;

	return 0;
}

234
static void free_firmware(struct xc2028_data *priv)
235
{
236
	int i;
237
	tuner_dbg("%s called\n", __func__);
238 239 240 241

	if (!priv->firm)
		return;

242 243 244
	for (i = 0; i < priv->firm_size; i++)
		kfree(priv->firm[i].ptr);

245 246
	kfree(priv->firm);

247
	priv->firm = NULL;
248
	priv->firm_size = 0;
249 250

	memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
251 252
}

253
static int load_all_firmwares(struct dvb_frontend *fe)
254 255
{
	struct xc2028_data    *priv = fe->tuner_priv;
256
	const struct firmware *fw   = NULL;
257
	unsigned char         *p, *endp;
258 259
	int                   rc = 0;
	int		      n, n_array;
260
	char		      name[33];
261
	char		      *fname;
262

263
	tuner_dbg("%s called\n", __func__);
264

265 266 267 268 269 270 271
	if (!firmware_name[0])
		fname = priv->ctrl.fname;
	else
		fname = firmware_name;

	tuner_dbg("Reading firmware %s\n", fname);
	rc = request_firmware(&fw, fname, &priv->i2c_props.adap->dev);
272
	if (rc < 0) {
273
		if (rc == -ENOENT)
274
			tuner_err("Error: firmware %s not found.\n",
275
				   fname);
276
		else
277
			tuner_err("Error %d while requesting firmware %s \n",
278
				   rc, fname);
279

280 281
		return rc;
	}
282 283
	p = fw->data;
	endp = p + fw->size;
284

285 286
	if (fw->size < sizeof(name) - 1 + 2 + 2) {
		tuner_err("Error: firmware file %s has invalid size!\n",
287
			  fname);
288
		goto corrupt;
289
	}
290

291 292 293
	memcpy(name, p, sizeof(name) - 1);
	name[sizeof(name) - 1] = 0;
	p += sizeof(name) - 1;
294

295
	priv->firm_version = le16_to_cpu(*(__u16 *) p);
296 297
	p += 2;

298
	n_array = le16_to_cpu(*(__u16 *) p);
299 300
	p += 2;

301
	tuner_info("Loading %d firmware images from %s, type: %s, ver %d.%d\n",
302
		   n_array, fname, name,
303
		   priv->firm_version >> 8, priv->firm_version & 0xff);
304

305
	priv->firm = kzalloc(sizeof(*priv->firm) * n_array, GFP_KERNEL);
306 307
	if (priv->firm == NULL) {
		tuner_err("Not enough memory to load firmware file.\n");
308
		rc = -ENOMEM;
309
		goto err;
310
	}
311
	priv->firm_size = n_array;
312

313 314
	n = -1;
	while (p < endp) {
315 316
		__u32 type, size;
		v4l2_std_id id;
317
		__u16 int_freq = 0;
318 319 320

		n++;
		if (n >= n_array) {
321 322
			tuner_err("More firmware images in file than "
				  "were expected!\n");
323 324 325 326
			goto corrupt;
		}

		/* Checks if there's enough bytes to read */
327
		if (p + sizeof(type) + sizeof(id) + sizeof(size) > endp) {
328
			tuner_err("Firmware header is incomplete!\n");
329 330 331
			goto corrupt;
		}

332
		type = le32_to_cpu(*(__u32 *) p);
333 334
		p += sizeof(type);

335
		id = le64_to_cpu(*(v4l2_std_id *) p);
336 337
		p += sizeof(id);

338 339 340 341 342
		if (type & HAS_IF) {
			int_freq = le16_to_cpu(*(__u16 *) p);
			p += sizeof(int_freq);
		}

343
		size = le32_to_cpu(*(__u32 *) p);
344 345
		p += sizeof(size);

346
		if ((!size) || (size + p > endp)) {
347
			tuner_err("Firmware type ");
348
			dump_firm_type(type);
349 350
			printk("(%x), id %llx is corrupted "
			       "(size=%d, expected %d)\n",
351
			       type, (unsigned long long)id,
352
			       (unsigned)(endp - p), size);
353 354 355
			goto corrupt;
		}

356
		priv->firm[n].ptr = kzalloc(size, GFP_KERNEL);
357 358
		if (priv->firm[n].ptr == NULL) {
			tuner_err("Not enough memory to load firmware file.\n");
359
			rc = -ENOMEM;
360 361
			goto err;
		}
362 363
		tuner_dbg("Reading firmware type ");
		if (debug) {
364
			dump_firm_type_and_int_freq(type, int_freq);
365
			printk("(%x), id %llx, size=%d.\n",
366
			       type, (unsigned long long)id, size);
367
		}
368 369 370 371 372

		memcpy(priv->firm[n].ptr, p, size);
		priv->firm[n].type = type;
		priv->firm[n].id   = id;
		priv->firm[n].size = size;
373
		priv->firm[n].int_freq = int_freq;
374 375 376 377

		p += size;
	}

378
	if (n + 1 != priv->firm_size) {
379
		tuner_err("Firmware file is incomplete!\n");
380 381 382 383 384 385
		goto corrupt;
	}

	goto done;

corrupt:
386
	rc = -EINVAL;
387
	tuner_err("Error: firmware file is corrupted!\n");
388 389

err:
390
	tuner_info("Releasing partially loaded firmware file.\n");
391 392 393 394
	free_firmware(priv);

done:
	release_firmware(fw);
395 396
	if (rc == 0)
		tuner_dbg("Firmware files loaded.\n");
397 398 399 400

	return rc;
}

401 402
static int seek_firmware(struct dvb_frontend *fe, unsigned int type,
			 v4l2_std_id *id)
403 404
{
	struct xc2028_data *priv = fe->tuner_priv;
405
	int                 i, best_i = -1, best_nr_matches = 0;
406
	unsigned int        type_mask = 0;
407

408
	tuner_dbg("%s called, want type=", __func__);
409 410 411 412
	if (debug) {
		dump_firm_type(type);
		printk("(%x), id %016llx.\n", type, (unsigned long long)*id);
	}
413 414

	if (!priv->firm) {
415
		tuner_err("Error! firmware not loaded\n");
416 417 418
		return -EINVAL;
	}

419
	if (((type & ~SCODE) == 0) && (*id == 0))
420
		*id = V4L2_STD_PAL;
421

422
	if (type & BASE)
423
		type_mask = BASE_TYPES;
424
	else if (type & SCODE) {
425
		type &= SCODE_TYPES;
426
		type_mask = SCODE_TYPES & ~HAS_IF;
427
	} else if (type & DTV_TYPES)
428
		type_mask = DTV_TYPES;
429
	else if (type & STD_SPECIFIC_TYPES)
430 431 432 433
		type_mask = STD_SPECIFIC_TYPES;

	type &= type_mask;

434
	if (!(type & SCODE))
435
		type_mask = ~0;
436

437
	/* Seek for exact match */
438
	for (i = 0; i < priv->firm_size; i++) {
439
		if ((type == (priv->firm[i].type & type_mask)) &&
440
		    (*id == priv->firm[i].id))
441 442 443 444
			goto found;
	}

	/* Seek for generic video standard match */
445
	for (i = 0; i < priv->firm_size; i++) {
446 447 448
		v4l2_std_id match_mask;
		int nr_matches;

449
		if (type != (priv->firm[i].type & type_mask))
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
			continue;

		match_mask = *id & priv->firm[i].id;
		if (!match_mask)
			continue;

		if ((*id & match_mask) == *id)
			goto found; /* Supports all the requested standards */

		nr_matches = hweight64(match_mask);
		if (nr_matches > best_nr_matches) {
			best_nr_matches = nr_matches;
			best_i = i;
		}
	}

	if (best_nr_matches > 0) {
		tuner_dbg("Selecting best matching firmware (%d bits) for "
			  "type=", best_nr_matches);
		dump_firm_type(type);
		printk("(%x), id %016llx:\n", type, (unsigned long long)*id);
		i = best_i;
		goto found;
473 474 475 476
	}

	/*FIXME: Would make sense to seek for type "hint" match ? */

477
	i = -ENOENT;
478
	goto ret;
479 480 481 482

found:
	*id = priv->firm[i].id;

483
ret:
484
	tuner_dbg("%s firmware for type=", (i < 0) ? "Can't find" : "Found");
485 486
	if (debug) {
		dump_firm_type(type);
487
		printk("(%x), id %016llx.\n", type, (unsigned long long)*id);
488
	}
489 490 491 492 493 494 495 496
	return i;
}

static int load_firmware(struct dvb_frontend *fe, unsigned int type,
			 v4l2_std_id *id)
{
	struct xc2028_data *priv = fe->tuner_priv;
	int                pos, rc;
497
	unsigned char      *p, *endp, buf[priv->ctrl.max_len];
498

499
	tuner_dbg("%s called\n", __func__);
500 501 502 503 504

	pos = seek_firmware(fe, type, id);
	if (pos < 0)
		return pos;

505
	tuner_info("Loading firmware for type=");
506 507 508
	dump_firm_type(priv->firm[pos].type);
	printk("(%x), id %016llx.\n", priv->firm[pos].type,
	       (unsigned long long)*id);
509

510 511
	p = priv->firm[pos].ptr;
	endp = p + priv->firm[pos].size;
512

513
	while (p < endp) {
514 515 516
		__u16 size;

		/* Checks if there's enough bytes to read */
517
		if (p + sizeof(size) > endp) {
518
			tuner_err("Firmware chunk size is wrong\n");
519 520 521
			return -EINVAL;
		}

522
		size = le16_to_cpu(*(__u16 *) p);
523 524 525 526 527 528
		p += sizeof(size);

		if (size == 0xffff)
			return 0;

		if (!size) {
529
			/* Special callback command received */
530
			rc = priv->tuner_callback(priv->video_dev,
531 532
						  XC2028_TUNER_RESET, 0);
			if (rc < 0) {
533
				tuner_err("Error at RESET code %d\n",
534
					   (*p) & 0x7f);
535
				return -EINVAL;
536 537 538
			}
			continue;
		}
539 540 541 542 543 544 545 546 547 548
		if (size >= 0xff00) {
			switch (size) {
			case 0xff00:
				rc = priv->tuner_callback(priv->video_dev,
							XC2028_RESET_CLK, 0);
				if (rc < 0) {
					tuner_err("Error at RESET code %d\n",
						  (*p) & 0x7f);
					return -EINVAL;
				}
549
				break;
550 551 552 553 554 555
			default:
				tuner_info("Invalid RESET code %d\n",
					   size & 0x7f);
				return -EINVAL;

			}
556
			continue;
557
		}
558 559 560

		/* Checks for a sleep command */
		if (size & 0x8000) {
561
			msleep(size & 0x7fff);
562
			continue;
563 564
		}

565
		if ((size + p > endp)) {
566
			tuner_err("missing bytes: need %d, have %d\n",
567
				   size, (int)(endp - p));
568 569
			return -EINVAL;
		}
570

571
		buf[0] = *p;
572
		p++;
573
		size--;
574

575
		/* Sends message chunks */
576
		while (size > 0) {
577 578
			int len = (size < priv->ctrl.max_len - 1) ?
				   size : priv->ctrl.max_len - 1;
579

580
			memcpy(buf + 1, p, len);
581

582
			rc = i2c_send(priv, buf, len + 1);
583
			if (rc < 0) {
584
				tuner_err("%d returned from send\n", rc);
585 586 587 588 589 590 591
				return -EINVAL;
			}

			p += len;
			size -= len;
		}
	}
592
	return 0;
593 594
}

595
static int load_scode(struct dvb_frontend *fe, unsigned int type,
596
			 v4l2_std_id *id, __u16 int_freq, int scode)
597 598 599 600 601
{
	struct xc2028_data *priv = fe->tuner_priv;
	int                pos, rc;
	unsigned char	   *p;

602
	tuner_dbg("%s called\n", __func__);
603

604 605 606 607 608 609 610
	if (!int_freq) {
		pos = seek_firmware(fe, type, id);
		if (pos < 0)
			return pos;
	} else {
		for (pos = 0; pos < priv->firm_size; pos++) {
			if ((priv->firm[pos].int_freq == int_freq) &&
611
			    (priv->firm[pos].type & HAS_IF))
612 613 614 615 616
				break;
		}
		if (pos == priv->firm_size)
			return -ENOENT;
	}
617 618 619

	p = priv->firm[pos].ptr;

620
	if (priv->firm[pos].type & HAS_IF) {
621 622 623 624 625 626 627 628 629 630 631
		if (priv->firm[pos].size != 12 * 16 || scode >= 16)
			return -EINVAL;
		p += 12 * scode;
	} else {
		/* 16 SCODE entries per file; each SCODE entry is 12 bytes and
		 * has a 2-byte size header in the firmware format. */
		if (priv->firm[pos].size != 14 * 16 || scode >= 16 ||
		    le16_to_cpu(*(__u16 *)(p + 14 * scode)) != 12)
			return -EINVAL;
		p += 14 * scode + 2;
	}
632

633
	tuner_info("Loading SCODE for type=");
634 635
	dump_firm_type_and_int_freq(priv->firm[pos].type,
				    priv->firm[pos].int_freq);
636 637 638
	printk("(%x), id %016llx.\n", priv->firm[pos].type,
	       (unsigned long long)*id);

639
	if (priv->firm_version < 0x0202)
640 641 642 643 644
		rc = send_seq(priv, {0x20, 0x00, 0x00, 0x00});
	else
		rc = send_seq(priv, {0xa0, 0x00, 0x00, 0x00});
	if (rc < 0)
		return -EIO;
645

646
	rc = i2c_send(priv, p, 12);
647 648
	if (rc < 0)
		return -EIO;
649

650 651 652
	rc = send_seq(priv, {0x00, 0x8c});
	if (rc < 0)
		return -EIO;
653 654 655 656

	return 0;
}

657
static int check_firmware(struct dvb_frontend *fe, unsigned int type,
658
			  v4l2_std_id std, __u16 int_freq)
659
{
660
	struct xc2028_data         *priv = fe->tuner_priv;
661
	struct firmware_properties new_fw;
662 663 664
	int			   rc = 0, is_retry = 0;
	u16			   version, hwmodel;
	v4l2_std_id		   std0;
665

666
	tuner_dbg("%s called\n", __func__);
667

668
	if (!priv->firm) {
669 670
		if (!priv->ctrl.fname) {
			tuner_info("xc2028/3028 firmware name not set!\n");
671
			return -EINVAL;
672
		}
673

674 675
		rc = load_all_firmwares(fe);
		if (rc < 0)
676 677 678
			return rc;
	}

679
	if (priv->ctrl.mts && !(type & FM))
680
		type |= MTS;
681

682
retry:
683 684 685 686 687
	new_fw.type = type;
	new_fw.id = std;
	new_fw.std_req = std;
	new_fw.scode_table = SCODE | priv->ctrl.scode_table;
	new_fw.scode_nr = 0;
688
	new_fw.int_freq = int_freq;
689 690 691 692

	tuner_dbg("checking firmware, user requested type=");
	if (debug) {
		dump_firm_type(new_fw.type);
693
		printk("(%x), id %016llx, ", new_fw.type,
694
		       (unsigned long long)new_fw.std_req);
695 696 697 698 699 700 701
		if (!int_freq) {
			printk("scode_tbl ");
			dump_firm_type(priv->ctrl.scode_table);
			printk("(%x), ", priv->ctrl.scode_table);
		} else
			printk("int_freq %d, ", new_fw.int_freq);
		printk("scode_nr %d\n", new_fw.scode_nr);
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
	}

	/* No need to reload base firmware if it matches */
	if (((BASE | new_fw.type) & BASE_TYPES) ==
	    (priv->cur_fw.type & BASE_TYPES)) {
		tuner_dbg("BASE firmware not changed.\n");
		goto skip_base;
	}

	/* Updating BASE - forget about all currently loaded firmware */
	memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));

	/* Reset is needed before loading firmware */
	rc = priv->tuner_callback(priv->video_dev,
				  XC2028_TUNER_RESET, 0);
	if (rc < 0)
		goto fail;

720 721 722
	/* BASE firmwares are all std0 */
	std0 = 0;
	rc = load_firmware(fe, BASE | new_fw.type, &std0);
723 724 725 726 727
	if (rc < 0) {
		tuner_err("Error %d while loading base firmware\n",
			  rc);
		goto fail;
	}
728

729
	/* Load INIT1, if needed */
730
	tuner_dbg("Load init1 firmware, if exists\n");
731

732
	rc = load_firmware(fe, BASE | INIT1 | new_fw.type, &std0);
733 734 735
	if (rc == -ENOENT)
		rc = load_firmware(fe, (BASE | INIT1 | new_fw.type) & ~F8MHZ,
				   &std0);
736 737 738 739 740
	if (rc < 0 && rc != -ENOENT) {
		tuner_err("Error %d while loading init1 firmware\n",
			  rc);
		goto fail;
	}
741

742 743 744 745
skip_base:
	/*
	 * No need to reload standard specific firmware if base firmware
	 * was not reloaded and requested video standards have not changed.
746
	 */
747 748
	if (priv->cur_fw.type == (BASE | new_fw.type) &&
	    priv->cur_fw.std_req == std) {
749
		tuner_dbg("Std-specific firmware already loaded.\n");
750
		goto skip_std_specific;
751
	}
752

753 754 755 756
	/* Reloading std-specific firmware forces a SCODE update */
	priv->cur_fw.scode_table = 0;

	rc = load_firmware(fe, new_fw.type, &new_fw.id);
757 758 759
	if (rc == -ENOENT)
		rc = load_firmware(fe, new_fw.type & ~F8MHZ, &new_fw.id);

760
	if (rc < 0)
761 762 763 764 765 766 767 768
		goto fail;

skip_std_specific:
	if (priv->cur_fw.scode_table == new_fw.scode_table &&
	    priv->cur_fw.scode_nr == new_fw.scode_nr) {
		tuner_dbg("SCODE firmware already loaded.\n");
		goto check_device;
	}
769

770 771 772
	if (new_fw.type & FM)
		goto check_device;

773
	/* Load SCODE firmware, if exists */
774
	tuner_dbg("Trying to load scode %d\n", new_fw.scode_nr);
775

776 777
	rc = load_scode(fe, new_fw.type | new_fw.scode_table, &new_fw.id,
			new_fw.int_freq, new_fw.scode_nr);
778

779
check_device:
780 781 782 783 784
	if (xc2028_get_reg(priv, 0x0004, &version) < 0 ||
	    xc2028_get_reg(priv, 0x0008, &hwmodel) < 0) {
		tuner_err("Unable to read tuner registers.\n");
		goto fail;
	}
785

786 787 788 789
	tuner_dbg("Device is Xceive %d version %d.%d, "
		  "firmware version %d.%d\n",
		  hwmodel, (version & 0xf000) >> 12, (version & 0xf00) >> 8,
		  (version & 0xf0) >> 4, version & 0xf);
790

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
	/* Check firmware version against what we downloaded. */
	if (priv->firm_version != ((version & 0xf0) << 4 | (version & 0x0f))) {
		tuner_err("Incorrect readback of firmware version.\n");
		goto fail;
	}

	/* Check that the tuner hardware model remains consistent over time. */
	if (priv->hwmodel == 0 && (hwmodel == 2028 || hwmodel == 3028)) {
		priv->hwmodel = hwmodel;
		priv->hwvers  = version & 0xff00;
	} else if (priv->hwmodel == 0 || priv->hwmodel != hwmodel ||
		   priv->hwvers != (version & 0xff00)) {
		tuner_err("Read invalid device hardware information - tuner "
			  "hung?\n");
		goto fail;
	}

808 809 810 811 812 813 814 815 816
	memcpy(&priv->cur_fw, &new_fw, sizeof(priv->cur_fw));

	/*
	 * By setting BASE in cur_fw.type only after successfully loading all
	 * firmwares, we can:
	 * 1. Identify that BASE firmware with type=0 has been loaded;
	 * 2. Tell whether BASE firmware was just changed the next time through.
	 */
	priv->cur_fw.type |= BASE;
817 818

	return 0;
819 820 821

fail:
	memset(&priv->cur_fw, 0, sizeof(priv->cur_fw));
822 823 824 825 826 827 828
	if (!is_retry) {
		msleep(50);
		is_retry = 1;
		tuner_dbg("Retrying firmware load\n");
		goto retry;
	}

829 830 831
	if (rc == -ENOENT)
		rc = -EINVAL;
	return rc;
832 833
}

834
static int xc2028_signal(struct dvb_frontend *fe, u16 *strength)
835
{
836
	struct xc2028_data *priv = fe->tuner_priv;
837 838
	u16                 frq_lock, signal = 0;
	int                 rc;
839

840
	tuner_dbg("%s called\n", __func__);
841

842
	mutex_lock(&priv->lock);
843

844
	/* Sync Lock Indicator */
845
	rc = xc2028_get_reg(priv, 0x0002, &frq_lock);
846
	if (rc < 0)
847
		goto ret;
848

849 850 851
	/* Frequency is locked */
	if (frq_lock == 1)
		signal = 32768;
852

853
	/* Get SNR of the video signal */
854 855
	rc = xc2028_get_reg(priv, 0x0040, &signal);
	if (rc < 0)
856 857 858 859
		goto ret;

	/* Use both frq_lock and signal to generate the result */
	signal = signal || ((signal & 0x07) << 12);
860 861

ret:
862 863 864
	mutex_unlock(&priv->lock);

	*strength = signal;
865

866 867
	tuner_dbg("signal strength is %d\n", signal);

868
	return rc;
869 870 871 872
}

#define DIV 15625

873
static int generic_set_freq(struct dvb_frontend *fe, u32 freq /* in HZ */,
874 875 876 877
			    enum tuner_mode new_mode,
			    unsigned int type,
			    v4l2_std_id std,
			    u16 int_freq)
878
{
879
	struct xc2028_data *priv = fe->tuner_priv;
880
	int		   rc = -EINVAL;
881
	unsigned char	   buf[4];
882
	u32		   div, offset = 0;
883

884
	tuner_dbg("%s called\n", __func__);
885

886 887
	mutex_lock(&priv->lock);

888
	tuner_dbg("should set frequency %d kHz\n", freq / 1000);
889

890
	if (check_firmware(fe, type, std, int_freq) < 0)
891
		goto ret;
892

893 894 895 896 897 898 899
	/* On some cases xc2028 can disable video output, if
	 * very weak signals are received. By sending a soft
	 * reset, this is re-enabled. So, it is better to always
	 * send a soft reset before changing channels, to be sure
	 * that xc2028 will be in a safe state.
	 * Maybe this might also be needed for DTV.
	 */
900
	if (new_mode == T_ANALOG_TV) {
901
		rc = send_seq(priv, {0x00, 0x00});
902 903 904
	} else if (priv->cur_fw.type & ATSC) {
		offset = 1750000;
	} else {
905
		offset = 2750000;
906 907 908 909 910 911 912 913 914 915
		/*
		 * We must adjust the offset by 500kHz in two cases in order
		 * to correctly center the IF output:
		 * 1) When the ZARLINK456 or DIBCOM52 tables were explicitly
		 *    selected and a 7MHz channel is tuned;
		 * 2) When tuning a VHF channel with DTV78 firmware.
		 */
		if (((priv->cur_fw.type & DTV7) &&
		     (priv->cur_fw.scode_table & (ZARLINK456 | DIBCOM52))) ||
		    ((priv->cur_fw.type & DTV78) && freq < 470000000))
916 917
			offset -= 500000;
	}
918

919
	div = (freq - offset + DIV / 2) / DIV;
920

921
	/* CMD= Set frequency */
922
	if (priv->firm_version < 0x0202)
923 924 925 926 927
		rc = send_seq(priv, {0x00, 0x02, 0x00, 0x00});
	else
		rc = send_seq(priv, {0x80, 0x02, 0x00, 0x00});
	if (rc < 0)
		goto ret;
928

929 930 931 932 933
	/* Return code shouldn't be checked.
	   The reset CLK is needed only with tm6000.
	   Driver should work fine even if this fails.
	 */
	priv->tuner_callback(priv->video_dev, XC2028_RESET_CLK, 1);
934 935

	msleep(10);
936

937 938 939 940
	buf[0] = 0xff & (div >> 24);
	buf[1] = 0xff & (div >> 16);
	buf[2] = 0xff & (div >> 8);
	buf[3] = 0xff & (div);
941

942
	rc = i2c_send(priv, buf, sizeof(buf));
943
	if (rc < 0)
944
		goto ret;
945 946
	msleep(100);

947
	priv->frequency = freq;
948

949 950 951
	tuner_dbg("divisor= %02x %02x %02x %02x (freq=%d.%03d)\n",
	       buf[0], buf[1], buf[2], buf[3],
	       freq / 1000000, (freq % 1000000) / 1000);
952

953
	rc = 0;
954

955 956
ret:
	mutex_unlock(&priv->lock);
957

958
	return rc;
959 960
}

961
static int xc2028_set_analog_freq(struct dvb_frontend *fe,
962
			      struct analog_parameters *p)
963
{
964
	struct xc2028_data *priv = fe->tuner_priv;
965 966
	unsigned int       type=0;

967
	tuner_dbg("%s called\n", __func__);
968

969 970 971 972 973
	if (p->mode == V4L2_TUNER_RADIO) {
		type |= FM;
		if (priv->ctrl.input1)
			type |= INPUT1;
		return generic_set_freq(fe, (625l * p->frequency) / 10,
974
				T_ANALOG_TV, type, 0, 0);
975 976
	}

977 978 979 980 981
	/* if std is not defined, choose one */
	if (!p->std)
		p->std = V4L2_STD_MN;

	/* PAL/M, PAL/N, PAL/Nc and NTSC variants should use 6MHz firmware */
982 983
	if (!(p->std & V4L2_STD_MN))
		type |= F8MHZ;
984

985 986
	/* Add audio hack to std mask */
	p->std |= parse_audio_std_option();
987

988
	return generic_set_freq(fe, 62500l * p->frequency,
989
				T_ANALOG_TV, type, p->std, 0);
990
}
991

992 993
static int xc2028_set_params(struct dvb_frontend *fe,
			     struct dvb_frontend_parameters *p)
994
{
995
	struct xc2028_data *priv = fe->tuner_priv;
996
	unsigned int       type=0;
997
	fe_bandwidth_t     bw = BANDWIDTH_8_MHZ;
998
	u16                demod = 0;
999

1000
	tuner_dbg("%s called\n", __func__);
1001

1002 1003 1004 1005 1006
	if (priv->ctrl.d2633)
		type |= D2633;
	else
		type |= D2620;

1007 1008 1009 1010 1011
	switch(fe->ops.info.type) {
	case FE_OFDM:
		bw = p->u.ofdm.bandwidth;
		break;
	case FE_QAM:
1012 1013 1014 1015
		tuner_info("WARN: There are some reports that "
			   "QAM 6 MHz doesn't work.\n"
			   "If this works for you, please report by "
			   "e-mail to: v4l-dvb-maintainer@linuxtv.org\n");
1016 1017 1018 1019 1020
		bw = BANDWIDTH_6_MHZ;
		type |= QAM;
		break;
	case FE_ATSC:
		bw = BANDWIDTH_6_MHZ;
1021 1022
		/* The only ATSC firmware (at least on v2.7) is D2633,
		   so overrides ctrl->d2633 */
1023
		type |= ATSC| D2633;
1024
		type &= ~D2620;
1025
		break;
1026 1027 1028
	/* DVB-S is not supported */
	default:
		return -EINVAL;
1029 1030
	}

1031 1032
	switch (bw) {
	case BANDWIDTH_8_MHZ:
1033 1034 1035 1036 1037 1038
		if (p->frequency < 470000000)
			priv->ctrl.vhfbw7 = 0;
		else
			priv->ctrl.uhfbw8 = 1;
		type |= (priv->ctrl.vhfbw7 && priv->ctrl.uhfbw8) ? DTV78 : DTV8;
		type |= F8MHZ;
1039 1040
		break;
	case BANDWIDTH_7_MHZ:
1041 1042 1043 1044 1045 1046
		if (p->frequency < 470000000)
			priv->ctrl.vhfbw7 = 1;
		else
			priv->ctrl.uhfbw8 = 0;
		type |= (priv->ctrl.vhfbw7 && priv->ctrl.uhfbw8) ? DTV78 : DTV7;
		type |= F8MHZ;
1047 1048
		break;
	case BANDWIDTH_6_MHZ:
1049 1050 1051
		type |= DTV6;
		priv->ctrl.vhfbw7 = 0;
		priv->ctrl.uhfbw8 = 0;
1052 1053 1054 1055 1056
		break;
	default:
		tuner_err("error: bandwidth not supported.\n");
	};

1057 1058
	/* All S-code tables need a 200kHz shift */
	if (priv->ctrl.demod)
1059
		demod = priv->ctrl.demod + 200;
1060

1061
	return generic_set_freq(fe, p->frequency,
1062
				T_DIGITAL_TV, type, 0, demod);
1063
}
1064

1065

1066
static int xc2028_dvb_release(struct dvb_frontend *fe)
1067
{
1068 1069
	struct xc2028_data *priv = fe->tuner_priv;

1070
	tuner_dbg("%s called\n", __func__);
1071

1072 1073
	mutex_lock(&xc2028_list_mutex);

1074 1075
	/* only perform final cleanup if this is the last instance */
	if (hybrid_tuner_report_instance_count(priv) == 1) {
1076
		kfree(priv->ctrl.fname);
1077 1078
		free_firmware(priv);
	}
1079

1080 1081 1082
	if (priv)
		hybrid_tuner_release_state(priv);

1083 1084
	mutex_unlock(&xc2028_list_mutex);

1085 1086
	fe->tuner_priv = NULL;

1087 1088 1089
	return 0;
}

1090
static int xc2028_get_frequency(struct dvb_frontend *fe, u32 *frequency)
1091
{
1092
	struct xc2028_data *priv = fe->tuner_priv;
1093

1094
	tuner_dbg("%s called\n", __func__);
1095

1096
	*frequency = priv->frequency;
1097 1098 1099 1100

	return 0;
}

1101
static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg)
1102 1103 1104
{
	struct xc2028_data *priv = fe->tuner_priv;
	struct xc2028_ctrl *p    = priv_cfg;
1105
	int                 rc   = 0;
1106

1107
	tuner_dbg("%s called\n", __func__);
1108

1109 1110
	mutex_lock(&priv->lock);

1111
	memcpy(&priv->ctrl, p, sizeof(priv->ctrl));
1112 1113
	if (priv->ctrl.max_len < 9)
		priv->ctrl.max_len = 13;
1114

1115
	if (p->fname) {
1116 1117 1118 1119 1120
		if (priv->ctrl.fname && strcmp(p->fname, priv->ctrl.fname)) {
			kfree(priv->ctrl.fname);
			free_firmware(priv);
		}

1121 1122 1123
		priv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL);
		if (priv->ctrl.fname == NULL)
			rc = -ENOMEM;
1124 1125
	}

1126 1127
	mutex_unlock(&priv->lock);

1128
	return rc;
1129 1130
}

1131
static const struct dvb_tuner_ops xc2028_dvb_tuner_ops = {
1132
	.info = {
1133 1134 1135 1136 1137
		 .name = "Xceive XC3028",
		 .frequency_min = 42000000,
		 .frequency_max = 864000000,
		 .frequency_step = 50000,
		 },
1138

1139
	.set_config	   = xc2028_set_config,
1140
	.set_analog_params = xc2028_set_analog_freq,
1141 1142 1143 1144
	.release           = xc2028_dvb_release,
	.get_frequency     = xc2028_get_frequency,
	.get_rf_strength   = xc2028_signal,
	.set_params        = xc2028_set_params,
1145 1146
};

1147 1148
struct dvb_frontend *xc2028_attach(struct dvb_frontend *fe,
				   struct xc2028_config *cfg)
1149
{
1150
	struct xc2028_data *priv;
1151
	int instance;
1152

1153
	if (debug)
1154
		printk(KERN_DEBUG "xc2028: Xcv2028/3028 init called!\n");
1155

1156
	if (NULL == cfg)
1157
		return NULL;
1158

1159
	if (!fe) {
1160
		printk(KERN_ERR "xc2028: No frontend!\n");
1161
		return NULL;
1162 1163
	}

1164 1165
	mutex_lock(&xc2028_list_mutex);

1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
	instance = hybrid_tuner_request_state(struct xc2028_data, priv,
					      hybrid_tuner_instance_list,
					      cfg->i2c_adap, cfg->i2c_addr,
					      "xc2028");
	switch (instance) {
	case 0:
		/* memory allocation failure */
		goto fail;
		break;
	case 1:
		/* new tuner instance */
1177
		priv->tuner_callback = cfg->callback;
1178
		priv->ctrl.max_len = 13;
1179

1180 1181
		mutex_init(&priv->lock);

1182 1183 1184 1185 1186 1187 1188 1189
		/* analog side (tuner-core) uses i2c_adap->algo_data.
		 * digital side is not guaranteed to have algo_data defined.
		 *
		 * digital side will always have fe->dvb defined.
		 * analog side (tuner-core) doesn't (yet) define fe->dvb.
		 */
		priv->video_dev = ((fe->dvb) && (fe->dvb->priv)) ?
				   fe->dvb->priv : cfg->i2c_adap->algo_data;
1190

1191 1192 1193 1194 1195 1196 1197
		fe->tuner_priv = priv;
		break;
	case 2:
		/* existing tuner instance */
		fe->tuner_priv = priv;
		break;
	}
1198

1199
	memcpy(&fe->ops.tuner_ops, &xc2028_dvb_tuner_ops,
1200
	       sizeof(xc2028_dvb_tuner_ops));
1201 1202 1203

	tuner_info("type set to %s\n", "XCeive xc2028/xc3028 tuner");

1204 1205 1206
	if (cfg->ctrl)
		xc2028_set_config(fe, cfg->ctrl);

1207 1208
	mutex_unlock(&xc2028_list_mutex);

1209
	return fe;
1210 1211 1212 1213 1214
fail:
	mutex_unlock(&xc2028_list_mutex);

	xc2028_dvb_release(fe);
	return NULL;
1215
}
1216

1217 1218
EXPORT_SYMBOL(xc2028_attach);

1219
MODULE_DESCRIPTION("Xceive xc2028/xc3028 tuner driver");
1220
MODULE_AUTHOR("Michel Ludwig <michel.ludwig@gmail.com>");
1221 1222
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>");
MODULE_LICENSE("GPL");