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