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