1 /*
2  * DVB USB Linux driver for Afatech AF9015 DVB-T USB2.0 receiver
3  *
4  * Copyright (C) 2007 Antti Palosaari <crope@iki.fi>
5  *
6  * Thanks to Afatech who kindly provided information.
7  *
8  *    This program is free software; you can redistribute it and/or modify
9  *    it under the terms of the GNU General Public License as published by
10  *    the Free Software Foundation; either version 2 of the License, or
11  *    (at your option) any later version.
12  *
13  *    This program is distributed in the hope that it will be useful,
14  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *    GNU General Public License for more details.
17  *
18  */
19 
20 #include "af9015.h"
21 
22 static int dvb_usb_af9015_remote;
23 module_param_named(remote, dvb_usb_af9015_remote, int, 0644);
24 MODULE_PARM_DESC(remote, "select remote");
25 DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
26 
27 static int af9015_ctrl_msg(struct dvb_usb_device *d, struct req_t *req)
28 {
29 #define REQ_HDR_LEN 8 /* send header size */
30 #define ACK_HDR_LEN 2 /* rece header size */
31 	struct af9015_state *state = d_to_priv(d);
32 	int ret, wlen, rlen;
33 	u8 write = 1;
34 
35 	mutex_lock(&d->usb_mutex);
36 
37 	state->buf[0] = req->cmd;
38 	state->buf[1] = state->seq++;
39 	state->buf[2] = req->i2c_addr << 1;
40 	state->buf[3] = req->addr >> 8;
41 	state->buf[4] = req->addr & 0xff;
42 	state->buf[5] = req->mbox;
43 	state->buf[6] = req->addr_len;
44 	state->buf[7] = req->data_len;
45 
46 	switch (req->cmd) {
47 	case GET_CONFIG:
48 	case READ_MEMORY:
49 	case RECONNECT_USB:
50 		write = 0;
51 		break;
52 	case READ_I2C:
53 		write = 0;
54 		state->buf[2] |= 0x01; /* set I2C direction */
55 		/* fall through */
56 	case WRITE_I2C:
57 		state->buf[0] = READ_WRITE_I2C;
58 		break;
59 	case WRITE_MEMORY:
60 		if (((req->addr & 0xff00) == 0xff00) ||
61 		    ((req->addr & 0xff00) == 0xae00))
62 			state->buf[0] = WRITE_VIRTUAL_MEMORY;
63 	case WRITE_VIRTUAL_MEMORY:
64 	case COPY_FIRMWARE:
65 	case DOWNLOAD_FIRMWARE:
66 	case BOOT:
67 		break;
68 	default:
69 		dev_err(&d->udev->dev, "%s: unknown command=%d\n",
70 				KBUILD_MODNAME, req->cmd);
71 		ret = -EIO;
72 		goto error;
73 	}
74 
75 	/* buffer overflow check */
76 	if ((write && (req->data_len > BUF_LEN - REQ_HDR_LEN)) ||
77 			(!write && (req->data_len > BUF_LEN - ACK_HDR_LEN))) {
78 		dev_err(&d->udev->dev, "%s: too much data; cmd=%d len=%d\n",
79 				KBUILD_MODNAME, req->cmd, req->data_len);
80 		ret = -EINVAL;
81 		goto error;
82 	}
83 
84 	/* write receives seq + status = 2 bytes
85 	   read receives seq + status + data = 2 + N bytes */
86 	wlen = REQ_HDR_LEN;
87 	rlen = ACK_HDR_LEN;
88 	if (write) {
89 		wlen += req->data_len;
90 		memcpy(&state->buf[REQ_HDR_LEN], req->data, req->data_len);
91 	} else {
92 		rlen += req->data_len;
93 	}
94 
95 	/* no ack for these packets */
96 	if (req->cmd == DOWNLOAD_FIRMWARE || req->cmd == RECONNECT_USB)
97 		rlen = 0;
98 
99 	ret = dvb_usbv2_generic_rw_locked(d,
100 			state->buf, wlen, state->buf, rlen);
101 	if (ret)
102 		goto error;
103 
104 	/* check status */
105 	if (rlen && state->buf[1]) {
106 		dev_err(&d->udev->dev, "%s: command failed=%d\n",
107 				KBUILD_MODNAME, state->buf[1]);
108 		ret = -EIO;
109 		goto error;
110 	}
111 
112 	/* read request, copy returned data to return buf */
113 	if (!write)
114 		memcpy(req->data, &state->buf[ACK_HDR_LEN], req->data_len);
115 error:
116 	mutex_unlock(&d->usb_mutex);
117 
118 	return ret;
119 }
120 
121 static int af9015_write_regs(struct dvb_usb_device *d, u16 addr, u8 *val,
122 	u8 len)
123 {
124 	struct req_t req = {WRITE_MEMORY, AF9015_I2C_DEMOD, addr, 0, 0, len,
125 		val};
126 	return af9015_ctrl_msg(d, &req);
127 }
128 
129 static int af9015_read_regs(struct dvb_usb_device *d, u16 addr, u8 *val, u8 len)
130 {
131 	struct req_t req = {READ_MEMORY, AF9015_I2C_DEMOD, addr, 0, 0, len,
132 		val};
133 	return af9015_ctrl_msg(d, &req);
134 }
135 
136 static int af9015_write_reg(struct dvb_usb_device *d, u16 addr, u8 val)
137 {
138 	return af9015_write_regs(d, addr, &val, 1);
139 }
140 
141 static int af9015_read_reg(struct dvb_usb_device *d, u16 addr, u8 *val)
142 {
143 	return af9015_read_regs(d, addr, val, 1);
144 }
145 
146 static int af9015_write_reg_i2c(struct dvb_usb_device *d, u8 addr, u16 reg,
147 	u8 val)
148 {
149 	struct af9015_state *state = d_to_priv(d);
150 	struct req_t req = {WRITE_I2C, addr, reg, 1, 1, 1, &val};
151 
152 	if (addr == state->af9013_config[0].i2c_addr ||
153 	    addr == state->af9013_config[1].i2c_addr)
154 		req.addr_len = 3;
155 
156 	return af9015_ctrl_msg(d, &req);
157 }
158 
159 static int af9015_read_reg_i2c(struct dvb_usb_device *d, u8 addr, u16 reg,
160 	u8 *val)
161 {
162 	struct af9015_state *state = d_to_priv(d);
163 	struct req_t req = {READ_I2C, addr, reg, 0, 1, 1, val};
164 
165 	if (addr == state->af9013_config[0].i2c_addr ||
166 	    addr == state->af9013_config[1].i2c_addr)
167 		req.addr_len = 3;
168 
169 	return af9015_ctrl_msg(d, &req);
170 }
171 
172 static int af9015_do_reg_bit(struct dvb_usb_device *d, u16 addr, u8 bit, u8 op)
173 {
174 	int ret;
175 	u8 val, mask = 0x01;
176 
177 	ret = af9015_read_reg(d, addr, &val);
178 	if (ret)
179 		return ret;
180 
181 	mask <<= bit;
182 	if (op) {
183 		/* set bit */
184 		val |= mask;
185 	} else {
186 		/* clear bit */
187 		mask ^= 0xff;
188 		val &= mask;
189 	}
190 
191 	return af9015_write_reg(d, addr, val);
192 }
193 
194 static int af9015_set_reg_bit(struct dvb_usb_device *d, u16 addr, u8 bit)
195 {
196 	return af9015_do_reg_bit(d, addr, bit, 1);
197 }
198 
199 static int af9015_clear_reg_bit(struct dvb_usb_device *d, u16 addr, u8 bit)
200 {
201 	return af9015_do_reg_bit(d, addr, bit, 0);
202 }
203 
204 static int af9015_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
205 	int num)
206 {
207 	struct dvb_usb_device *d = i2c_get_adapdata(adap);
208 	struct af9015_state *state = d_to_priv(d);
209 	int ret = 0, i = 0;
210 	u16 addr;
211 	u8 uninitialized_var(mbox), addr_len;
212 	struct req_t req;
213 
214 /*
215 The bus lock is needed because there is two tuners both using same I2C-address.
216 Due to that the only way to select correct tuner is use demodulator I2C-gate.
217 
218 ................................................
219 . AF9015 includes integrated AF9013 demodulator.
220 . ____________                   ____________  .                ____________
221 .|     uC     |                 |   demod    | .               |    tuner   |
222 .|------------|                 |------------| .               |------------|
223 .|   AF9015   |                 |  AF9013/5  | .               |   MXL5003  |
224 .|            |--+----I2C-------|-----/ -----|-.-----I2C-------|            |
225 .|            |  |              | addr 0x38  | .               |  addr 0xc6 |
226 .|____________|  |              |____________| .               |____________|
227 .................|..............................
228 		 |               ____________                   ____________
229 		 |              |   demod    |                 |    tuner   |
230 		 |              |------------|                 |------------|
231 		 |              |   AF9013   |                 |   MXL5003  |
232 		 +----I2C-------|-----/ -----|-------I2C-------|            |
233 				| addr 0x3a  |                 |  addr 0xc6 |
234 				|____________|                 |____________|
235 */
236 	if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
237 		return -EAGAIN;
238 
239 	while (i < num) {
240 		if (msg[i].addr == state->af9013_config[0].i2c_addr ||
241 		    msg[i].addr == state->af9013_config[1].i2c_addr) {
242 			addr = msg[i].buf[0] << 8;
243 			addr += msg[i].buf[1];
244 			mbox = msg[i].buf[2];
245 			addr_len = 3;
246 		} else {
247 			addr = msg[i].buf[0];
248 			addr_len = 1;
249 			/* mbox is don't care in that case */
250 		}
251 
252 		if (num > i + 1 && (msg[i+1].flags & I2C_M_RD)) {
253 			if (msg[i].len > 3 || msg[i+1].len > 61) {
254 				ret = -EOPNOTSUPP;
255 				goto error;
256 			}
257 			if (msg[i].addr == state->af9013_config[0].i2c_addr)
258 				req.cmd = READ_MEMORY;
259 			else
260 				req.cmd = READ_I2C;
261 			req.i2c_addr = msg[i].addr;
262 			req.addr = addr;
263 			req.mbox = mbox;
264 			req.addr_len = addr_len;
265 			req.data_len = msg[i+1].len;
266 			req.data = &msg[i+1].buf[0];
267 			ret = af9015_ctrl_msg(d, &req);
268 			i += 2;
269 		} else if (msg[i].flags & I2C_M_RD) {
270 			if (msg[i].len > 61) {
271 				ret = -EOPNOTSUPP;
272 				goto error;
273 			}
274 			if (msg[i].addr == state->af9013_config[0].i2c_addr) {
275 				ret = -EINVAL;
276 				goto error;
277 			}
278 			req.cmd = READ_I2C;
279 			req.i2c_addr = msg[i].addr;
280 			req.addr = addr;
281 			req.mbox = mbox;
282 			req.addr_len = addr_len;
283 			req.data_len = msg[i].len;
284 			req.data = &msg[i].buf[0];
285 			ret = af9015_ctrl_msg(d, &req);
286 			i += 1;
287 		} else {
288 			if (msg[i].len > 21) {
289 				ret = -EOPNOTSUPP;
290 				goto error;
291 			}
292 			if (msg[i].addr == state->af9013_config[0].i2c_addr)
293 				req.cmd = WRITE_MEMORY;
294 			else
295 				req.cmd = WRITE_I2C;
296 			req.i2c_addr = msg[i].addr;
297 			req.addr = addr;
298 			req.mbox = mbox;
299 			req.addr_len = addr_len;
300 			req.data_len = msg[i].len-addr_len;
301 			req.data = &msg[i].buf[addr_len];
302 			ret = af9015_ctrl_msg(d, &req);
303 			i += 1;
304 		}
305 		if (ret)
306 			goto error;
307 
308 	}
309 	ret = i;
310 
311 error:
312 	mutex_unlock(&d->i2c_mutex);
313 
314 	return ret;
315 }
316 
317 static u32 af9015_i2c_func(struct i2c_adapter *adapter)
318 {
319 	return I2C_FUNC_I2C;
320 }
321 
322 static struct i2c_algorithm af9015_i2c_algo = {
323 	.master_xfer = af9015_i2c_xfer,
324 	.functionality = af9015_i2c_func,
325 };
326 
327 static int af9015_identify_state(struct dvb_usb_device *d, const char **name)
328 {
329 	int ret;
330 	u8 reply;
331 	struct req_t req = {GET_CONFIG, 0, 0, 0, 0, 1, &reply};
332 
333 	ret = af9015_ctrl_msg(d, &req);
334 	if (ret)
335 		return ret;
336 
337 	dev_dbg(&d->udev->dev, "%s: reply=%02x\n", __func__, reply);
338 
339 	if (reply == 0x02)
340 		ret = WARM;
341 	else
342 		ret = COLD;
343 
344 	return ret;
345 }
346 
347 static int af9015_download_firmware(struct dvb_usb_device *d,
348 	const struct firmware *fw)
349 {
350 	struct af9015_state *state = d_to_priv(d);
351 	int i, len, remaining, ret;
352 	struct req_t req = {DOWNLOAD_FIRMWARE, 0, 0, 0, 0, 0, NULL};
353 	u16 checksum = 0;
354 	dev_dbg(&d->udev->dev, "%s:\n", __func__);
355 
356 	/* calc checksum */
357 	for (i = 0; i < fw->size; i++)
358 		checksum += fw->data[i];
359 
360 	state->firmware_size = fw->size;
361 	state->firmware_checksum = checksum;
362 
363 	#define FW_ADDR 0x5100 /* firmware start address */
364 	#define LEN_MAX 55 /* max packet size */
365 	for (remaining = fw->size; remaining > 0; remaining -= LEN_MAX) {
366 		len = remaining;
367 		if (len > LEN_MAX)
368 			len = LEN_MAX;
369 
370 		req.data_len = len;
371 		req.data = (u8 *) &fw->data[fw->size - remaining];
372 		req.addr = FW_ADDR + fw->size - remaining;
373 
374 		ret = af9015_ctrl_msg(d, &req);
375 		if (ret) {
376 			dev_err(&d->udev->dev,
377 					"%s: firmware download failed=%d\n",
378 					KBUILD_MODNAME, ret);
379 			goto error;
380 		}
381 	}
382 
383 	/* firmware loaded, request boot */
384 	req.cmd = BOOT;
385 	req.data_len = 0;
386 	ret = af9015_ctrl_msg(d, &req);
387 	if (ret) {
388 		dev_err(&d->udev->dev, "%s: firmware boot failed=%d\n",
389 				KBUILD_MODNAME, ret);
390 		goto error;
391 	}
392 
393 error:
394 	return ret;
395 }
396 
397 #define AF9015_EEPROM_SIZE 256
398 /* 2^31 + 2^29 - 2^25 + 2^22 - 2^19 - 2^16 + 1 */
399 #define GOLDEN_RATIO_PRIME_32 0x9e370001UL
400 
401 /* hash (and dump) eeprom */
402 static int af9015_eeprom_hash(struct dvb_usb_device *d)
403 {
404 	struct af9015_state *state = d_to_priv(d);
405 	int ret, i;
406 	u8 buf[AF9015_EEPROM_SIZE];
407 	struct req_t req = {READ_I2C, AF9015_I2C_EEPROM, 0, 0, 1, 1, NULL};
408 
409 	/* read eeprom */
410 	for (i = 0; i < AF9015_EEPROM_SIZE; i++) {
411 		req.addr = i;
412 		req.data = &buf[i];
413 		ret = af9015_ctrl_msg(d, &req);
414 		if (ret < 0)
415 			goto err;
416 	}
417 
418 	/* calculate checksum */
419 	for (i = 0; i < AF9015_EEPROM_SIZE / sizeof(u32); i++) {
420 		state->eeprom_sum *= GOLDEN_RATIO_PRIME_32;
421 		state->eeprom_sum += le32_to_cpu(((__le32 *)buf)[i]);
422 	}
423 
424 	for (i = 0; i < AF9015_EEPROM_SIZE; i += 16)
425 		dev_dbg(&d->udev->dev, "%s: %*ph\n", __func__, 16, buf + i);
426 
427 	dev_dbg(&d->udev->dev, "%s: eeprom sum=%.8x\n",
428 			__func__, state->eeprom_sum);
429 	return 0;
430 err:
431 	dev_err(&d->udev->dev, "%s: eeprom failed=%d\n", KBUILD_MODNAME, ret);
432 	return ret;
433 }
434 
435 static int af9015_read_config(struct dvb_usb_device *d)
436 {
437 	struct af9015_state *state = d_to_priv(d);
438 	int ret;
439 	u8 val, i, offset = 0;
440 	struct req_t req = {READ_I2C, AF9015_I2C_EEPROM, 0, 0, 1, 1, &val};
441 
442 	dev_dbg(&d->udev->dev, "%s:\n", __func__);
443 
444 	/* IR remote controller */
445 	req.addr = AF9015_EEPROM_IR_MODE;
446 	/* first message will timeout often due to possible hw bug */
447 	for (i = 0; i < 4; i++) {
448 		ret = af9015_ctrl_msg(d, &req);
449 		if (!ret)
450 			break;
451 	}
452 	if (ret)
453 		goto error;
454 
455 	ret = af9015_eeprom_hash(d);
456 	if (ret)
457 		goto error;
458 
459 	state->ir_mode = val;
460 	dev_dbg(&d->udev->dev, "%s: IR mode=%d\n", __func__, val);
461 
462 	/* TS mode - one or two receivers */
463 	req.addr = AF9015_EEPROM_TS_MODE;
464 	ret = af9015_ctrl_msg(d, &req);
465 	if (ret)
466 		goto error;
467 
468 	state->dual_mode = val;
469 	dev_dbg(&d->udev->dev, "%s: TS mode=%d\n", __func__, state->dual_mode);
470 
471 	/* disable 2nd adapter because we don't have PID-filters */
472 	if (d->udev->speed == USB_SPEED_FULL)
473 		state->dual_mode = 0;
474 
475 	state->af9013_config[0].i2c_addr = AF9015_I2C_DEMOD;
476 
477 	if (state->dual_mode) {
478 		/* read 2nd demodulator I2C address */
479 		req.addr = AF9015_EEPROM_DEMOD2_I2C;
480 		ret = af9015_ctrl_msg(d, &req);
481 		if (ret)
482 			goto error;
483 
484 		state->af9013_config[1].i2c_addr = val >> 1;
485 	}
486 
487 	for (i = 0; i < state->dual_mode + 1; i++) {
488 		if (i == 1)
489 			offset = AF9015_EEPROM_OFFSET;
490 		/* xtal */
491 		req.addr = AF9015_EEPROM_XTAL_TYPE1 + offset;
492 		ret = af9015_ctrl_msg(d, &req);
493 		if (ret)
494 			goto error;
495 		switch (val) {
496 		case 0:
497 			state->af9013_config[i].clock = 28800000;
498 			break;
499 		case 1:
500 			state->af9013_config[i].clock = 20480000;
501 			break;
502 		case 2:
503 			state->af9013_config[i].clock = 28000000;
504 			break;
505 		case 3:
506 			state->af9013_config[i].clock = 25000000;
507 			break;
508 		}
509 		dev_dbg(&d->udev->dev, "%s: [%d] xtal=%d set clock=%d\n",
510 				__func__, i, val,
511 				state->af9013_config[i].clock);
512 
513 		/* IF frequency */
514 		req.addr = AF9015_EEPROM_IF1H + offset;
515 		ret = af9015_ctrl_msg(d, &req);
516 		if (ret)
517 			goto error;
518 
519 		state->af9013_config[i].if_frequency = val << 8;
520 
521 		req.addr = AF9015_EEPROM_IF1L + offset;
522 		ret = af9015_ctrl_msg(d, &req);
523 		if (ret)
524 			goto error;
525 
526 		state->af9013_config[i].if_frequency += val;
527 		state->af9013_config[i].if_frequency *= 1000;
528 		dev_dbg(&d->udev->dev, "%s: [%d] IF frequency=%d\n", __func__,
529 				i, state->af9013_config[i].if_frequency);
530 
531 		/* MT2060 IF1 */
532 		req.addr = AF9015_EEPROM_MT2060_IF1H  + offset;
533 		ret = af9015_ctrl_msg(d, &req);
534 		if (ret)
535 			goto error;
536 		state->mt2060_if1[i] = val << 8;
537 		req.addr = AF9015_EEPROM_MT2060_IF1L + offset;
538 		ret = af9015_ctrl_msg(d, &req);
539 		if (ret)
540 			goto error;
541 		state->mt2060_if1[i] += val;
542 		dev_dbg(&d->udev->dev, "%s: [%d] MT2060 IF1=%d\n", __func__, i,
543 				state->mt2060_if1[i]);
544 
545 		/* tuner */
546 		req.addr =  AF9015_EEPROM_TUNER_ID1 + offset;
547 		ret = af9015_ctrl_msg(d, &req);
548 		if (ret)
549 			goto error;
550 		switch (val) {
551 		case AF9013_TUNER_ENV77H11D5:
552 		case AF9013_TUNER_MT2060:
553 		case AF9013_TUNER_QT1010:
554 		case AF9013_TUNER_UNKNOWN:
555 		case AF9013_TUNER_MT2060_2:
556 		case AF9013_TUNER_TDA18271:
557 		case AF9013_TUNER_QT1010A:
558 		case AF9013_TUNER_TDA18218:
559 			state->af9013_config[i].spec_inv = 1;
560 			break;
561 		case AF9013_TUNER_MXL5003D:
562 		case AF9013_TUNER_MXL5005D:
563 		case AF9013_TUNER_MXL5005R:
564 		case AF9013_TUNER_MXL5007T:
565 			state->af9013_config[i].spec_inv = 0;
566 			break;
567 		case AF9013_TUNER_MC44S803:
568 			state->af9013_config[i].gpio[1] = AF9013_GPIO_LO;
569 			state->af9013_config[i].spec_inv = 1;
570 			break;
571 		default:
572 			dev_err(&d->udev->dev, "%s: tuner id=%d not " \
573 					"supported, please report!\n",
574 					KBUILD_MODNAME, val);
575 			return -ENODEV;
576 		}
577 
578 		state->af9013_config[i].tuner = val;
579 		dev_dbg(&d->udev->dev, "%s: [%d] tuner id=%d\n",
580 				__func__, i, val);
581 	}
582 
583 error:
584 	if (ret)
585 		dev_err(&d->udev->dev, "%s: eeprom read failed=%d\n",
586 				KBUILD_MODNAME, ret);
587 
588 	/* AverMedia AVerTV Volar Black HD (A850) device have bad EEPROM
589 	   content :-( Override some wrong values here. Ditto for the
590 	   AVerTV Red HD+ (A850T) device. */
591 	if (le16_to_cpu(d->udev->descriptor.idVendor) == USB_VID_AVERMEDIA &&
592 		((le16_to_cpu(d->udev->descriptor.idProduct) ==
593 			USB_PID_AVERMEDIA_A850) ||
594 		(le16_to_cpu(d->udev->descriptor.idProduct) ==
595 			USB_PID_AVERMEDIA_A850T))) {
596 		dev_dbg(&d->udev->dev,
597 				"%s: AverMedia A850: overriding config\n",
598 				__func__);
599 		/* disable dual mode */
600 		state->dual_mode = 0;
601 
602 		/* set correct IF */
603 		state->af9013_config[0].if_frequency = 4570000;
604 	}
605 
606 	return ret;
607 }
608 
609 static int af9015_get_stream_config(struct dvb_frontend *fe, u8 *ts_type,
610 		struct usb_data_stream_properties *stream)
611 {
612 	struct dvb_usb_device *d = fe_to_d(fe);
613 	dev_dbg(&d->udev->dev, "%s: adap=%d\n", __func__, fe_to_adap(fe)->id);
614 
615 	if (d->udev->speed == USB_SPEED_FULL)
616 		stream->u.bulk.buffersize = TS_USB11_FRAME_SIZE;
617 
618 	return 0;
619 }
620 
621 static int af9015_get_adapter_count(struct dvb_usb_device *d)
622 {
623 	struct af9015_state *state = d_to_priv(d);
624 	return state->dual_mode + 1;
625 }
626 
627 /* override demod callbacks for resource locking */
628 static int af9015_af9013_set_frontend(struct dvb_frontend *fe)
629 {
630 	int ret;
631 	struct af9015_state *state = fe_to_priv(fe);
632 
633 	if (mutex_lock_interruptible(&state->fe_mutex))
634 		return -EAGAIN;
635 
636 	ret = state->set_frontend[fe_to_adap(fe)->id](fe);
637 
638 	mutex_unlock(&state->fe_mutex);
639 
640 	return ret;
641 }
642 
643 /* override demod callbacks for resource locking */
644 static int af9015_af9013_read_status(struct dvb_frontend *fe,
645 	enum fe_status *status)
646 {
647 	int ret;
648 	struct af9015_state *state = fe_to_priv(fe);
649 
650 	if (mutex_lock_interruptible(&state->fe_mutex))
651 		return -EAGAIN;
652 
653 	ret = state->read_status[fe_to_adap(fe)->id](fe, status);
654 
655 	mutex_unlock(&state->fe_mutex);
656 
657 	return ret;
658 }
659 
660 /* override demod callbacks for resource locking */
661 static int af9015_af9013_init(struct dvb_frontend *fe)
662 {
663 	int ret;
664 	struct af9015_state *state = fe_to_priv(fe);
665 
666 	if (mutex_lock_interruptible(&state->fe_mutex))
667 		return -EAGAIN;
668 
669 	ret = state->init[fe_to_adap(fe)->id](fe);
670 
671 	mutex_unlock(&state->fe_mutex);
672 
673 	return ret;
674 }
675 
676 /* override demod callbacks for resource locking */
677 static int af9015_af9013_sleep(struct dvb_frontend *fe)
678 {
679 	int ret;
680 	struct af9015_state *state = fe_to_priv(fe);
681 
682 	if (mutex_lock_interruptible(&state->fe_mutex))
683 		return -EAGAIN;
684 
685 	ret = state->sleep[fe_to_adap(fe)->id](fe);
686 
687 	mutex_unlock(&state->fe_mutex);
688 
689 	return ret;
690 }
691 
692 /* override tuner callbacks for resource locking */
693 static int af9015_tuner_init(struct dvb_frontend *fe)
694 {
695 	int ret;
696 	struct af9015_state *state = fe_to_priv(fe);
697 
698 	if (mutex_lock_interruptible(&state->fe_mutex))
699 		return -EAGAIN;
700 
701 	ret = state->tuner_init[fe_to_adap(fe)->id](fe);
702 
703 	mutex_unlock(&state->fe_mutex);
704 
705 	return ret;
706 }
707 
708 /* override tuner callbacks for resource locking */
709 static int af9015_tuner_sleep(struct dvb_frontend *fe)
710 {
711 	int ret;
712 	struct af9015_state *state = fe_to_priv(fe);
713 
714 	if (mutex_lock_interruptible(&state->fe_mutex))
715 		return -EAGAIN;
716 
717 	ret = state->tuner_sleep[fe_to_adap(fe)->id](fe);
718 
719 	mutex_unlock(&state->fe_mutex);
720 
721 	return ret;
722 }
723 
724 static int af9015_copy_firmware(struct dvb_usb_device *d)
725 {
726 	struct af9015_state *state = d_to_priv(d);
727 	int ret;
728 	u8 fw_params[4];
729 	u8 val, i;
730 	struct req_t req = {COPY_FIRMWARE, 0, 0x5100, 0, 0, sizeof(fw_params),
731 		fw_params };
732 	dev_dbg(&d->udev->dev, "%s:\n", __func__);
733 
734 	fw_params[0] = state->firmware_size >> 8;
735 	fw_params[1] = state->firmware_size & 0xff;
736 	fw_params[2] = state->firmware_checksum >> 8;
737 	fw_params[3] = state->firmware_checksum & 0xff;
738 
739 	/* wait 2nd demodulator ready */
740 	msleep(100);
741 
742 	ret = af9015_read_reg_i2c(d, state->af9013_config[1].i2c_addr,
743 			0x98be, &val);
744 	if (ret)
745 		goto error;
746 	else
747 		dev_dbg(&d->udev->dev, "%s: firmware status=%02x\n",
748 				__func__, val);
749 
750 	if (val == 0x0c) /* fw is running, no need for download */
751 		goto exit;
752 
753 	/* set I2C master clock to fast (to speed up firmware copy) */
754 	ret = af9015_write_reg(d, 0xd416, 0x04); /* 0x04 * 400ns */
755 	if (ret)
756 		goto error;
757 
758 	msleep(50);
759 
760 	/* copy firmware */
761 	ret = af9015_ctrl_msg(d, &req);
762 	if (ret)
763 		dev_err(&d->udev->dev, "%s: firmware copy cmd failed=%d\n",
764 				KBUILD_MODNAME, ret);
765 
766 	dev_dbg(&d->udev->dev, "%s: firmware copy done\n", __func__);
767 
768 	/* set I2C master clock back to normal */
769 	ret = af9015_write_reg(d, 0xd416, 0x14); /* 0x14 * 400ns */
770 	if (ret)
771 		goto error;
772 
773 	/* request boot firmware */
774 	ret = af9015_write_reg_i2c(d, state->af9013_config[1].i2c_addr,
775 			0xe205, 1);
776 	dev_dbg(&d->udev->dev, "%s: firmware boot cmd status=%d\n",
777 			__func__, ret);
778 	if (ret)
779 		goto error;
780 
781 	for (i = 0; i < 15; i++) {
782 		msleep(100);
783 
784 		/* check firmware status */
785 		ret = af9015_read_reg_i2c(d, state->af9013_config[1].i2c_addr,
786 				0x98be, &val);
787 		dev_dbg(&d->udev->dev, "%s: firmware status cmd status=%d " \
788 				"firmware status=%02x\n", __func__, ret, val);
789 		if (ret)
790 			goto error;
791 
792 		if (val == 0x0c || val == 0x04) /* success or fail */
793 			break;
794 	}
795 
796 	if (val == 0x04) {
797 		dev_err(&d->udev->dev, "%s: firmware did not run\n",
798 				KBUILD_MODNAME);
799 		ret = -ETIMEDOUT;
800 	} else if (val != 0x0c) {
801 		dev_err(&d->udev->dev, "%s: firmware boot timeout\n",
802 				KBUILD_MODNAME);
803 		ret = -ETIMEDOUT;
804 	}
805 
806 error:
807 exit:
808 	return ret;
809 }
810 
811 static int af9015_af9013_frontend_attach(struct dvb_usb_adapter *adap)
812 {
813 	int ret;
814 	struct af9015_state *state = adap_to_priv(adap);
815 
816 	if (adap->id == 0) {
817 		state->af9013_config[0].ts_mode = AF9013_TS_USB;
818 		memcpy(state->af9013_config[0].api_version, "\x0\x1\x9\x0", 4);
819 		state->af9013_config[0].gpio[0] = AF9013_GPIO_HI;
820 		state->af9013_config[0].gpio[3] = AF9013_GPIO_TUNER_ON;
821 	} else if (adap->id == 1) {
822 		state->af9013_config[1].ts_mode = AF9013_TS_SERIAL;
823 		memcpy(state->af9013_config[1].api_version, "\x0\x1\x9\x0", 4);
824 		state->af9013_config[1].gpio[0] = AF9013_GPIO_TUNER_ON;
825 		state->af9013_config[1].gpio[1] = AF9013_GPIO_LO;
826 
827 		/* copy firmware to 2nd demodulator */
828 		if (state->dual_mode) {
829 			ret = af9015_copy_firmware(adap_to_d(adap));
830 			if (ret) {
831 				dev_err(&adap_to_d(adap)->udev->dev,
832 						"%s: firmware copy to 2nd " \
833 						"frontend failed, will " \
834 						"disable it\n", KBUILD_MODNAME);
835 				state->dual_mode = 0;
836 				return -ENODEV;
837 			}
838 		} else {
839 			return -ENODEV;
840 		}
841 	}
842 
843 	/* attach demodulator */
844 	adap->fe[0] = dvb_attach(af9013_attach,
845 		&state->af9013_config[adap->id], &adap_to_d(adap)->i2c_adap);
846 
847 	/*
848 	 * AF9015 firmware does not like if it gets interrupted by I2C adapter
849 	 * request on some critical phases. During normal operation I2C adapter
850 	 * is used only 2nd demodulator and tuner on dual tuner devices.
851 	 * Override demodulator callbacks and use mutex for limit access to
852 	 * those "critical" paths to keep AF9015 happy.
853 	 */
854 	if (adap->fe[0]) {
855 		state->set_frontend[adap->id] =
856 			adap->fe[0]->ops.set_frontend;
857 		adap->fe[0]->ops.set_frontend =
858 			af9015_af9013_set_frontend;
859 
860 		state->read_status[adap->id] =
861 			adap->fe[0]->ops.read_status;
862 		adap->fe[0]->ops.read_status =
863 			af9015_af9013_read_status;
864 
865 		state->init[adap->id] = adap->fe[0]->ops.init;
866 		adap->fe[0]->ops.init = af9015_af9013_init;
867 
868 		state->sleep[adap->id] = adap->fe[0]->ops.sleep;
869 		adap->fe[0]->ops.sleep = af9015_af9013_sleep;
870 	}
871 
872 	return adap->fe[0] == NULL ? -ENODEV : 0;
873 }
874 
875 static struct mt2060_config af9015_mt2060_config = {
876 	.i2c_address = 0x60,
877 	.clock_out = 0,
878 };
879 
880 static struct qt1010_config af9015_qt1010_config = {
881 	.i2c_address = 0x62,
882 };
883 
884 static struct tda18271_config af9015_tda18271_config = {
885 	.gate = TDA18271_GATE_DIGITAL,
886 	.small_i2c = TDA18271_16_BYTE_CHUNK_INIT,
887 };
888 
889 static struct mxl5005s_config af9015_mxl5003_config = {
890 	.i2c_address     = 0x63,
891 	.if_freq         = IF_FREQ_4570000HZ,
892 	.xtal_freq       = CRYSTAL_FREQ_16000000HZ,
893 	.agc_mode        = MXL_SINGLE_AGC,
894 	.tracking_filter = MXL_TF_DEFAULT,
895 	.rssi_enable     = MXL_RSSI_ENABLE,
896 	.cap_select      = MXL_CAP_SEL_ENABLE,
897 	.div_out         = MXL_DIV_OUT_4,
898 	.clock_out       = MXL_CLOCK_OUT_DISABLE,
899 	.output_load     = MXL5005S_IF_OUTPUT_LOAD_200_OHM,
900 	.top		 = MXL5005S_TOP_25P2,
901 	.mod_mode        = MXL_DIGITAL_MODE,
902 	.if_mode         = MXL_ZERO_IF,
903 	.AgcMasterByte   = 0x00,
904 };
905 
906 static struct mxl5005s_config af9015_mxl5005_config = {
907 	.i2c_address     = 0x63,
908 	.if_freq         = IF_FREQ_4570000HZ,
909 	.xtal_freq       = CRYSTAL_FREQ_16000000HZ,
910 	.agc_mode        = MXL_SINGLE_AGC,
911 	.tracking_filter = MXL_TF_OFF,
912 	.rssi_enable     = MXL_RSSI_ENABLE,
913 	.cap_select      = MXL_CAP_SEL_ENABLE,
914 	.div_out         = MXL_DIV_OUT_4,
915 	.clock_out       = MXL_CLOCK_OUT_DISABLE,
916 	.output_load     = MXL5005S_IF_OUTPUT_LOAD_200_OHM,
917 	.top		 = MXL5005S_TOP_25P2,
918 	.mod_mode        = MXL_DIGITAL_MODE,
919 	.if_mode         = MXL_ZERO_IF,
920 	.AgcMasterByte   = 0x00,
921 };
922 
923 static struct mc44s803_config af9015_mc44s803_config = {
924 	.i2c_address = 0x60,
925 	.dig_out = 1,
926 };
927 
928 static struct tda18218_config af9015_tda18218_config = {
929 	.i2c_address = 0x60,
930 	.i2c_wr_max = 21, /* max wr bytes AF9015 I2C adap can handle at once */
931 };
932 
933 static struct mxl5007t_config af9015_mxl5007t_config = {
934 	.xtal_freq_hz = MxL_XTAL_24_MHZ,
935 	.if_freq_hz = MxL_IF_4_57_MHZ,
936 };
937 
938 static int af9015_tuner_attach(struct dvb_usb_adapter *adap)
939 {
940 	struct dvb_usb_device *d = adap_to_d(adap);
941 	struct af9015_state *state = d_to_priv(d);
942 	int ret;
943 	dev_dbg(&d->udev->dev, "%s:\n", __func__);
944 
945 	switch (state->af9013_config[adap->id].tuner) {
946 	case AF9013_TUNER_MT2060:
947 	case AF9013_TUNER_MT2060_2:
948 		ret = dvb_attach(mt2060_attach, adap->fe[0],
949 			&adap_to_d(adap)->i2c_adap, &af9015_mt2060_config,
950 			state->mt2060_if1[adap->id])
951 			== NULL ? -ENODEV : 0;
952 		break;
953 	case AF9013_TUNER_QT1010:
954 	case AF9013_TUNER_QT1010A:
955 		ret = dvb_attach(qt1010_attach, adap->fe[0],
956 			&adap_to_d(adap)->i2c_adap,
957 			&af9015_qt1010_config) == NULL ? -ENODEV : 0;
958 		break;
959 	case AF9013_TUNER_TDA18271:
960 		ret = dvb_attach(tda18271_attach, adap->fe[0], 0x60,
961 			&adap_to_d(adap)->i2c_adap,
962 			&af9015_tda18271_config) == NULL ? -ENODEV : 0;
963 		break;
964 	case AF9013_TUNER_TDA18218:
965 		ret = dvb_attach(tda18218_attach, adap->fe[0],
966 			&adap_to_d(adap)->i2c_adap,
967 			&af9015_tda18218_config) == NULL ? -ENODEV : 0;
968 		break;
969 	case AF9013_TUNER_MXL5003D:
970 		ret = dvb_attach(mxl5005s_attach, adap->fe[0],
971 			&adap_to_d(adap)->i2c_adap,
972 			&af9015_mxl5003_config) == NULL ? -ENODEV : 0;
973 		break;
974 	case AF9013_TUNER_MXL5005D:
975 	case AF9013_TUNER_MXL5005R:
976 		ret = dvb_attach(mxl5005s_attach, adap->fe[0],
977 			&adap_to_d(adap)->i2c_adap,
978 			&af9015_mxl5005_config) == NULL ? -ENODEV : 0;
979 		break;
980 	case AF9013_TUNER_ENV77H11D5:
981 		ret = dvb_attach(dvb_pll_attach, adap->fe[0], 0x60,
982 			&adap_to_d(adap)->i2c_adap,
983 			DVB_PLL_TDA665X) == NULL ? -ENODEV : 0;
984 		break;
985 	case AF9013_TUNER_MC44S803:
986 		ret = dvb_attach(mc44s803_attach, adap->fe[0],
987 			&adap_to_d(adap)->i2c_adap,
988 			&af9015_mc44s803_config) == NULL ? -ENODEV : 0;
989 		break;
990 	case AF9013_TUNER_MXL5007T:
991 		ret = dvb_attach(mxl5007t_attach, adap->fe[0],
992 			&adap_to_d(adap)->i2c_adap,
993 			0x60, &af9015_mxl5007t_config) == NULL ? -ENODEV : 0;
994 		break;
995 	case AF9013_TUNER_UNKNOWN:
996 	default:
997 		dev_err(&d->udev->dev, "%s: unknown tuner id=%d\n",
998 				KBUILD_MODNAME,
999 				state->af9013_config[adap->id].tuner);
1000 		ret = -ENODEV;
1001 	}
1002 
1003 	if (adap->fe[0]->ops.tuner_ops.init) {
1004 		state->tuner_init[adap->id] =
1005 			adap->fe[0]->ops.tuner_ops.init;
1006 		adap->fe[0]->ops.tuner_ops.init = af9015_tuner_init;
1007 	}
1008 
1009 	if (adap->fe[0]->ops.tuner_ops.sleep) {
1010 		state->tuner_sleep[adap->id] =
1011 			adap->fe[0]->ops.tuner_ops.sleep;
1012 		adap->fe[0]->ops.tuner_ops.sleep = af9015_tuner_sleep;
1013 	}
1014 
1015 	return ret;
1016 }
1017 
1018 static int af9015_pid_filter_ctrl(struct dvb_usb_adapter *adap, int onoff)
1019 {
1020 	struct dvb_usb_device *d = adap_to_d(adap);
1021 	int ret;
1022 	dev_dbg(&d->udev->dev, "%s: onoff=%d\n", __func__, onoff);
1023 
1024 	if (onoff)
1025 		ret = af9015_set_reg_bit(d, 0xd503, 0);
1026 	else
1027 		ret = af9015_clear_reg_bit(d, 0xd503, 0);
1028 
1029 	return ret;
1030 }
1031 
1032 static int af9015_pid_filter(struct dvb_usb_adapter *adap, int index, u16 pid,
1033 	int onoff)
1034 {
1035 	struct dvb_usb_device *d = adap_to_d(adap);
1036 	int ret;
1037 	u8 idx;
1038 	dev_dbg(&d->udev->dev, "%s: index=%d pid=%04x onoff=%d\n",
1039 			__func__, index, pid, onoff);
1040 
1041 	ret = af9015_write_reg(d, 0xd505, (pid & 0xff));
1042 	if (ret)
1043 		goto error;
1044 
1045 	ret = af9015_write_reg(d, 0xd506, (pid >> 8));
1046 	if (ret)
1047 		goto error;
1048 
1049 	idx = ((index & 0x1f) | (1 << 5));
1050 	ret = af9015_write_reg(d, 0xd504, idx);
1051 
1052 error:
1053 	return ret;
1054 }
1055 
1056 static int af9015_init_endpoint(struct dvb_usb_device *d)
1057 {
1058 	struct af9015_state *state = d_to_priv(d);
1059 	int ret;
1060 	u16 frame_size;
1061 	u8  packet_size;
1062 	dev_dbg(&d->udev->dev, "%s: USB speed=%d\n", __func__, d->udev->speed);
1063 
1064 	if (d->udev->speed == USB_SPEED_FULL) {
1065 		frame_size = TS_USB11_FRAME_SIZE/4;
1066 		packet_size = TS_USB11_MAX_PACKET_SIZE/4;
1067 	} else {
1068 		frame_size = TS_USB20_FRAME_SIZE/4;
1069 		packet_size = TS_USB20_MAX_PACKET_SIZE/4;
1070 	}
1071 
1072 	ret = af9015_set_reg_bit(d, 0xd507, 2); /* assert EP4 reset */
1073 	if (ret)
1074 		goto error;
1075 	ret = af9015_set_reg_bit(d, 0xd50b, 1); /* assert EP5 reset */
1076 	if (ret)
1077 		goto error;
1078 	ret = af9015_clear_reg_bit(d, 0xdd11, 5); /* disable EP4 */
1079 	if (ret)
1080 		goto error;
1081 	ret = af9015_clear_reg_bit(d, 0xdd11, 6); /* disable EP5 */
1082 	if (ret)
1083 		goto error;
1084 	ret = af9015_set_reg_bit(d, 0xdd11, 5); /* enable EP4 */
1085 	if (ret)
1086 		goto error;
1087 	if (state->dual_mode) {
1088 		ret = af9015_set_reg_bit(d, 0xdd11, 6); /* enable EP5 */
1089 		if (ret)
1090 			goto error;
1091 	}
1092 	ret = af9015_clear_reg_bit(d, 0xdd13, 5); /* disable EP4 NAK */
1093 	if (ret)
1094 		goto error;
1095 	if (state->dual_mode) {
1096 		ret = af9015_clear_reg_bit(d, 0xdd13, 6); /* disable EP5 NAK */
1097 		if (ret)
1098 			goto error;
1099 	}
1100 	/* EP4 xfer length */
1101 	ret = af9015_write_reg(d, 0xdd88, frame_size & 0xff);
1102 	if (ret)
1103 		goto error;
1104 	ret = af9015_write_reg(d, 0xdd89, frame_size >> 8);
1105 	if (ret)
1106 		goto error;
1107 	/* EP5 xfer length */
1108 	ret = af9015_write_reg(d, 0xdd8a, frame_size & 0xff);
1109 	if (ret)
1110 		goto error;
1111 	ret = af9015_write_reg(d, 0xdd8b, frame_size >> 8);
1112 	if (ret)
1113 		goto error;
1114 	ret = af9015_write_reg(d, 0xdd0c, packet_size); /* EP4 packet size */
1115 	if (ret)
1116 		goto error;
1117 	ret = af9015_write_reg(d, 0xdd0d, packet_size); /* EP5 packet size */
1118 	if (ret)
1119 		goto error;
1120 	ret = af9015_clear_reg_bit(d, 0xd507, 2); /* negate EP4 reset */
1121 	if (ret)
1122 		goto error;
1123 	if (state->dual_mode) {
1124 		ret = af9015_clear_reg_bit(d, 0xd50b, 1); /* negate EP5 reset */
1125 		if (ret)
1126 			goto error;
1127 	}
1128 
1129 	/* enable / disable mp2if2 */
1130 	if (state->dual_mode)
1131 		ret = af9015_set_reg_bit(d, 0xd50b, 0);
1132 	else
1133 		ret = af9015_clear_reg_bit(d, 0xd50b, 0);
1134 
1135 error:
1136 	if (ret)
1137 		dev_err(&d->udev->dev, "%s: endpoint init failed=%d\n",
1138 				KBUILD_MODNAME, ret);
1139 
1140 	return ret;
1141 }
1142 
1143 static int af9015_init(struct dvb_usb_device *d)
1144 {
1145 	struct af9015_state *state = d_to_priv(d);
1146 	int ret;
1147 	dev_dbg(&d->udev->dev, "%s:\n", __func__);
1148 
1149 	mutex_init(&state->fe_mutex);
1150 
1151 	/* init RC canary */
1152 	ret = af9015_write_reg(d, 0x98e9, 0xff);
1153 	if (ret)
1154 		goto error;
1155 
1156 	ret = af9015_init_endpoint(d);
1157 	if (ret)
1158 		goto error;
1159 
1160 error:
1161 	return ret;
1162 }
1163 
1164 #if IS_ENABLED(CONFIG_RC_CORE)
1165 struct af9015_rc_setup {
1166 	unsigned int id;
1167 	char *rc_codes;
1168 };
1169 
1170 static char *af9015_rc_setup_match(unsigned int id,
1171 	const struct af9015_rc_setup *table)
1172 {
1173 	for (; table->rc_codes; table++)
1174 		if (table->id == id)
1175 			return table->rc_codes;
1176 	return NULL;
1177 }
1178 
1179 static const struct af9015_rc_setup af9015_rc_setup_modparam[] = {
1180 	{ AF9015_REMOTE_A_LINK_DTU_M, RC_MAP_ALINK_DTU_M },
1181 	{ AF9015_REMOTE_MSI_DIGIVOX_MINI_II_V3, RC_MAP_MSI_DIGIVOX_II },
1182 	{ AF9015_REMOTE_MYGICTV_U718, RC_MAP_TOTAL_MEDIA_IN_HAND },
1183 	{ AF9015_REMOTE_DIGITTRADE_DVB_T, RC_MAP_DIGITTRADE },
1184 	{ AF9015_REMOTE_AVERMEDIA_KS, RC_MAP_AVERMEDIA_RM_KS },
1185 	{ }
1186 };
1187 
1188 static const struct af9015_rc_setup af9015_rc_setup_hashes[] = {
1189 	{ 0xb8feb708, RC_MAP_MSI_DIGIVOX_II },
1190 	{ 0xa3703d00, RC_MAP_ALINK_DTU_M },
1191 	{ 0x9b7dc64e, RC_MAP_TOTAL_MEDIA_IN_HAND }, /* MYGICTV U718 */
1192 	{ 0x5d49e3db, RC_MAP_DIGITTRADE }, /* LC-Power LC-USB-DVBT */
1193 	{ }
1194 };
1195 
1196 static int af9015_rc_query(struct dvb_usb_device *d)
1197 {
1198 	struct af9015_state *state = d_to_priv(d);
1199 	int ret;
1200 	u8 buf[17];
1201 
1202 	/* read registers needed to detect remote controller code */
1203 	ret = af9015_read_regs(d, 0x98d9, buf, sizeof(buf));
1204 	if (ret)
1205 		goto error;
1206 
1207 	/* If any of these are non-zero, assume invalid data */
1208 	if (buf[1] || buf[2] || buf[3]) {
1209 		dev_dbg(&d->udev->dev, "%s: invalid data\n", __func__);
1210 		return ret;
1211 	}
1212 
1213 	/* Check for repeat of previous code */
1214 	if ((state->rc_repeat != buf[6] || buf[0]) &&
1215 			!memcmp(&buf[12], state->rc_last, 4)) {
1216 		dev_dbg(&d->udev->dev, "%s: key repeated\n", __func__);
1217 		rc_repeat(d->rc_dev);
1218 		state->rc_repeat = buf[6];
1219 		return ret;
1220 	}
1221 
1222 	/* Only process key if canary killed */
1223 	if (buf[16] != 0xff && buf[0] != 0x01) {
1224 		enum rc_type proto;
1225 		dev_dbg(&d->udev->dev, "%s: key pressed %*ph\n",
1226 				__func__, 4, buf + 12);
1227 
1228 		/* Reset the canary */
1229 		ret = af9015_write_reg(d, 0x98e9, 0xff);
1230 		if (ret)
1231 			goto error;
1232 
1233 		/* Remember this key */
1234 		memcpy(state->rc_last, &buf[12], 4);
1235 		if (buf[14] == (u8) ~buf[15]) {
1236 			if (buf[12] == (u8) ~buf[13]) {
1237 				/* NEC */
1238 				state->rc_keycode = RC_SCANCODE_NEC(buf[12],
1239 								    buf[14]);
1240 				proto = RC_TYPE_NEC;
1241 			} else {
1242 				/* NEC extended*/
1243 				state->rc_keycode = RC_SCANCODE_NECX(buf[12] << 8 |
1244 								     buf[13],
1245 								     buf[14]);
1246 				proto = RC_TYPE_NECX;
1247 			}
1248 		} else {
1249 			/* 32 bit NEC */
1250 			state->rc_keycode = RC_SCANCODE_NEC32(buf[12] << 24 |
1251 							      buf[13] << 16 |
1252 							      buf[14] << 8  |
1253 							      buf[15]);
1254 			proto = RC_TYPE_NEC32;
1255 		}
1256 		rc_keydown(d->rc_dev, proto, state->rc_keycode, 0);
1257 	} else {
1258 		dev_dbg(&d->udev->dev, "%s: no key press\n", __func__);
1259 		/* Invalidate last keypress */
1260 		/* Not really needed, but helps with debug */
1261 		state->rc_last[2] = state->rc_last[3];
1262 	}
1263 
1264 	state->rc_repeat = buf[6];
1265 	state->rc_failed = false;
1266 
1267 error:
1268 	if (ret) {
1269 		dev_warn(&d->udev->dev, "%s: rc query failed=%d\n",
1270 				KBUILD_MODNAME, ret);
1271 
1272 		/* allow random errors as dvb-usb will stop polling on error */
1273 		if (!state->rc_failed)
1274 			ret = 0;
1275 
1276 		state->rc_failed = true;
1277 	}
1278 
1279 	return ret;
1280 }
1281 
1282 static int af9015_get_rc_config(struct dvb_usb_device *d, struct dvb_usb_rc *rc)
1283 {
1284 	struct af9015_state *state = d_to_priv(d);
1285 	u16 vid = le16_to_cpu(d->udev->descriptor.idVendor);
1286 
1287 	if (state->ir_mode == AF9015_IR_MODE_DISABLED)
1288 		return 0;
1289 
1290 	/* try to load remote based module param */
1291 	if (!rc->map_name)
1292 		rc->map_name = af9015_rc_setup_match(dvb_usb_af9015_remote,
1293 				af9015_rc_setup_modparam);
1294 
1295 	/* try to load remote based eeprom hash */
1296 	if (!rc->map_name)
1297 		rc->map_name = af9015_rc_setup_match(state->eeprom_sum,
1298 				af9015_rc_setup_hashes);
1299 
1300 	/* try to load remote based USB iManufacturer string */
1301 	if (!rc->map_name && vid == USB_VID_AFATECH) {
1302 		/* Check USB manufacturer and product strings and try
1303 		   to determine correct remote in case of chip vendor
1304 		   reference IDs are used.
1305 		   DO NOT ADD ANYTHING NEW HERE. Use hashes instead. */
1306 		char manufacturer[10];
1307 		memset(manufacturer, 0, sizeof(manufacturer));
1308 		usb_string(d->udev, d->udev->descriptor.iManufacturer,
1309 			manufacturer, sizeof(manufacturer));
1310 		if (!strcmp("MSI", manufacturer)) {
1311 			/* iManufacturer 1 MSI
1312 			   iProduct      2 MSI K-VOX */
1313 			rc->map_name = af9015_rc_setup_match(
1314 					AF9015_REMOTE_MSI_DIGIVOX_MINI_II_V3,
1315 					af9015_rc_setup_modparam);
1316 		}
1317 	}
1318 
1319 	/* load empty to enable rc */
1320 	if (!rc->map_name)
1321 		rc->map_name = RC_MAP_EMPTY;
1322 
1323 	rc->allowed_protos = RC_BIT_NEC | RC_BIT_NECX | RC_BIT_NEC32;
1324 	rc->query = af9015_rc_query;
1325 	rc->interval = 500;
1326 
1327 	return 0;
1328 }
1329 #else
1330 	#define af9015_get_rc_config NULL
1331 #endif
1332 
1333 static int af9015_probe(struct usb_interface *intf,
1334 		const struct usb_device_id *id)
1335 {
1336 	struct usb_device *udev = interface_to_usbdev(intf);
1337 	char manufacturer[sizeof("ITE Technologies, Inc.")];
1338 
1339 	memset(manufacturer, 0, sizeof(manufacturer));
1340 	usb_string(udev, udev->descriptor.iManufacturer,
1341 			manufacturer, sizeof(manufacturer));
1342 	/*
1343 	 * There is two devices having same ID but different chipset. One uses
1344 	 * AF9015 and the other IT9135 chipset. Only difference seen on lsusb
1345 	 * is iManufacturer string.
1346 	 *
1347 	 * idVendor           0x0ccd TerraTec Electronic GmbH
1348 	 * idProduct          0x0099
1349 	 * bcdDevice            2.00
1350 	 * iManufacturer           1 Afatech
1351 	 * iProduct                2 DVB-T 2
1352 	 *
1353 	 * idVendor           0x0ccd TerraTec Electronic GmbH
1354 	 * idProduct          0x0099
1355 	 * bcdDevice            2.00
1356 	 * iManufacturer           1 ITE Technologies, Inc.
1357 	 * iProduct                2 DVB-T TV Stick
1358 	 */
1359 	if ((le16_to_cpu(udev->descriptor.idVendor) == USB_VID_TERRATEC) &&
1360 			(le16_to_cpu(udev->descriptor.idProduct) == 0x0099)) {
1361 		if (!strcmp("ITE Technologies, Inc.", manufacturer)) {
1362 			dev_dbg(&udev->dev, "%s: rejecting device\n", __func__);
1363 			return -ENODEV;
1364 		}
1365 	}
1366 
1367 	return dvb_usbv2_probe(intf, id);
1368 }
1369 
1370 /* interface 0 is used by DVB-T receiver and
1371    interface 1 is for remote controller (HID) */
1372 static struct dvb_usb_device_properties af9015_props = {
1373 	.driver_name = KBUILD_MODNAME,
1374 	.owner = THIS_MODULE,
1375 	.adapter_nr = adapter_nr,
1376 	.size_of_priv = sizeof(struct af9015_state),
1377 
1378 	.generic_bulk_ctrl_endpoint = 0x02,
1379 	.generic_bulk_ctrl_endpoint_response = 0x81,
1380 
1381 	.identify_state = af9015_identify_state,
1382 	.firmware = AF9015_FIRMWARE,
1383 	.download_firmware = af9015_download_firmware,
1384 
1385 	.i2c_algo = &af9015_i2c_algo,
1386 	.read_config = af9015_read_config,
1387 	.frontend_attach = af9015_af9013_frontend_attach,
1388 	.tuner_attach = af9015_tuner_attach,
1389 	.init = af9015_init,
1390 	.get_rc_config = af9015_get_rc_config,
1391 	.get_stream_config = af9015_get_stream_config,
1392 
1393 	.get_adapter_count = af9015_get_adapter_count,
1394 	.adapter = {
1395 		{
1396 			.caps = DVB_USB_ADAP_HAS_PID_FILTER |
1397 				DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,
1398 			.pid_filter_count = 32,
1399 			.pid_filter = af9015_pid_filter,
1400 			.pid_filter_ctrl = af9015_pid_filter_ctrl,
1401 
1402 			.stream = DVB_USB_STREAM_BULK(0x84, 8, TS_USB20_FRAME_SIZE),
1403 		}, {
1404 			.stream = DVB_USB_STREAM_BULK(0x85, 8, TS_USB20_FRAME_SIZE),
1405 		},
1406 	},
1407 };
1408 
1409 static const struct usb_device_id af9015_id_table[] = {
1410 	{ DVB_USB_DEVICE(USB_VID_AFATECH, USB_PID_AFATECH_AF9015_9015,
1411 		&af9015_props, "Afatech AF9015 reference design", NULL) },
1412 	{ DVB_USB_DEVICE(USB_VID_AFATECH, USB_PID_AFATECH_AF9015_9016,
1413 		&af9015_props, "Afatech AF9015 reference design", NULL) },
1414 	{ DVB_USB_DEVICE(USB_VID_LEADTEK, USB_PID_WINFAST_DTV_DONGLE_GOLD,
1415 		&af9015_props, "Leadtek WinFast DTV Dongle Gold", RC_MAP_LEADTEK_Y04G0051) },
1416 	{ DVB_USB_DEVICE(USB_VID_PINNACLE, USB_PID_PINNACLE_PCTV71E,
1417 		&af9015_props, "Pinnacle PCTV 71e", NULL) },
1418 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_399U,
1419 		&af9015_props, "KWorld PlusTV Dual DVB-T Stick (DVB-T 399U)", NULL) },
1420 	{ DVB_USB_DEVICE(USB_VID_VISIONPLUS, USB_PID_TINYTWIN,
1421 		&af9015_props, "DigitalNow TinyTwin", RC_MAP_AZUREWAVE_AD_TU700) },
1422 	{ DVB_USB_DEVICE(USB_VID_VISIONPLUS, USB_PID_AZUREWAVE_AD_TU700,
1423 		&af9015_props, "TwinHan AzureWave AD-TU700(704J)", RC_MAP_AZUREWAVE_AD_TU700) },
1424 	{ DVB_USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_T_USB_XE_REV2,
1425 		&af9015_props, "TerraTec Cinergy T USB XE", NULL) },
1426 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_PC160_2T,
1427 		&af9015_props, "KWorld PlusTV Dual DVB-T PCI (DVB-T PC160-2T)", NULL) },
1428 	{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_VOLAR_X,
1429 		&af9015_props, "AVerMedia AVerTV DVB-T Volar X", RC_MAP_AVERMEDIA_M135A) },
1430 	{ DVB_USB_DEVICE(USB_VID_XTENSIONS, USB_PID_XTENSIONS_XD_380,
1431 		&af9015_props, "Xtensions XD-380", NULL) },
1432 	{ DVB_USB_DEVICE(USB_VID_MSI_2, USB_PID_MSI_DIGIVOX_DUO,
1433 		&af9015_props, "MSI DIGIVOX Duo", RC_MAP_MSI_DIGIVOX_III) },
1434 	{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_VOLAR_X_2,
1435 		&af9015_props, "Fujitsu-Siemens Slim Mobile USB DVB-T", NULL) },
1436 	{ DVB_USB_DEVICE(USB_VID_TELESTAR,  USB_PID_TELESTAR_STARSTICK_2,
1437 		&af9015_props, "Telestar Starstick 2", NULL) },
1438 	{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A309,
1439 		&af9015_props, "AVerMedia A309", NULL) },
1440 	{ DVB_USB_DEVICE(USB_VID_MSI_2, USB_PID_MSI_DIGI_VOX_MINI_III,
1441 		&af9015_props, "MSI Digi VOX mini III", RC_MAP_MSI_DIGIVOX_III) },
1442 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_395U,
1443 		&af9015_props, "KWorld USB DVB-T TV Stick II (VS-DVB-T 395U)", NULL) },
1444 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_395U_2,
1445 		&af9015_props, "KWorld USB DVB-T TV Stick II (VS-DVB-T 395U)", NULL) },
1446 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_395U_3,
1447 		&af9015_props, "KWorld USB DVB-T TV Stick II (VS-DVB-T 395U)", NULL) },
1448 	{ DVB_USB_DEVICE(USB_VID_AFATECH, USB_PID_TREKSTOR_DVBT,
1449 		&af9015_props, "TrekStor DVB-T USB Stick", RC_MAP_TREKSTOR) },
1450 	{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A850,
1451 		&af9015_props, "AverMedia AVerTV Volar Black HD (A850)", NULL) },
1452 	{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A805,
1453 		&af9015_props, "AverMedia AVerTV Volar GPS 805 (A805)", NULL) },
1454 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_CONCEPTRONIC_CTVDIGRCU,
1455 		&af9015_props, "Conceptronic USB2.0 DVB-T CTVDIGRCU V3.0", NULL) },
1456 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_MC810,
1457 		&af9015_props, "KWorld Digital MC-810", NULL) },
1458 	{ DVB_USB_DEVICE(USB_VID_KYE, USB_PID_GENIUS_TVGO_DVB_T03,
1459 		&af9015_props, "Genius TVGo DVB-T03", NULL) },
1460 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_399U_2,
1461 		&af9015_props, "KWorld PlusTV Dual DVB-T Stick (DVB-T 399U)", NULL) },
1462 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_PC160_T,
1463 		&af9015_props, "KWorld PlusTV DVB-T PCI Pro Card (DVB-T PC160-T)", NULL) },
1464 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_SVEON_STV20,
1465 		&af9015_props, "Sveon STV20 Tuner USB DVB-T HDTV", NULL) },
1466 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_TINYTWIN_2,
1467 		&af9015_props, "DigitalNow TinyTwin v2", RC_MAP_DIGITALNOW_TINYTWIN) },
1468 	{ DVB_USB_DEVICE(USB_VID_LEADTEK, USB_PID_WINFAST_DTV2000DS,
1469 		&af9015_props, "Leadtek WinFast DTV2000DS", RC_MAP_LEADTEK_Y04G0051) },
1470 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_UB383_T,
1471 		&af9015_props, "KWorld USB DVB-T Stick Mobile (UB383-T)", NULL) },
1472 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_395U_4,
1473 		&af9015_props, "KWorld USB DVB-T TV Stick II (VS-DVB-T 395U)", NULL) },
1474 	{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A815M,
1475 		&af9015_props, "AverMedia AVerTV Volar M (A815Mac)", NULL) },
1476 	{ DVB_USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_T_STICK_RC,
1477 		&af9015_props, "TerraTec Cinergy T Stick RC", RC_MAP_TERRATEC_SLIM_2) },
1478 	/* XXX: that same ID [0ccd:0099] is used by af9035 driver too */
1479 	{ DVB_USB_DEVICE(USB_VID_TERRATEC, USB_PID_TERRATEC_CINERGY_T_STICK_DUAL_RC,
1480 		&af9015_props, "TerraTec Cinergy T Stick Dual RC", RC_MAP_TERRATEC_SLIM) },
1481 	{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A850T,
1482 		&af9015_props, "AverMedia AVerTV Red HD+ (A850T)", NULL) },
1483 	{ DVB_USB_DEVICE(USB_VID_GTEK, USB_PID_TINYTWIN_3,
1484 		&af9015_props, "DigitalNow TinyTwin v3", RC_MAP_DIGITALNOW_TINYTWIN) },
1485 	{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_SVEON_STV22,
1486 		&af9015_props, "Sveon STV22 Dual USB DVB-T Tuner HDTV", RC_MAP_MSI_DIGIVOX_III) },
1487 	{ }
1488 };
1489 MODULE_DEVICE_TABLE(usb, af9015_id_table);
1490 
1491 /* usb specific object needed to register this driver with the usb subsystem */
1492 static struct usb_driver af9015_usb_driver = {
1493 	.name = KBUILD_MODNAME,
1494 	.id_table = af9015_id_table,
1495 	.probe = af9015_probe,
1496 	.disconnect = dvb_usbv2_disconnect,
1497 	.suspend = dvb_usbv2_suspend,
1498 	.resume = dvb_usbv2_resume,
1499 	.reset_resume = dvb_usbv2_reset_resume,
1500 	.no_dynamic_id = 1,
1501 	.soft_unbind = 1,
1502 };
1503 
1504 module_usb_driver(af9015_usb_driver);
1505 
1506 MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
1507 MODULE_DESCRIPTION("Afatech AF9015 driver");
1508 MODULE_LICENSE("GPL");
1509 MODULE_FIRMWARE(AF9015_FIRMWARE);
1510