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