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