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