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