xref: /OK3568_Linux_fs/yocto/meta-rockchip/recipes-devtools/rtl-tools/files/hciattach_rtk.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 /*
2  *  Copyright (C) 2013 Realtek Semiconductor Corp.
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  Module Name:
15  *     hciattach_rtk.c
16  *
17  *  Description:
18  *     H4/H5 specific initialization
19  *
20  *  Revision History:
21  *      Date         Version      Author             Comment
22  *     ----------   ---------    ---------------    -----------------------
23  *     2013-06-06    1.0.0        gordon_yang        Create
24  *     2013-06-18    1.0.1        lory_xu            add support for multi fw
25  *     2013-06-21    1.0.2        gordon_yang        add timeout for get version cmd
26  *     2013-07-01    1.0.3        lory_xu            close file handle
27  *     2013-07-01    2.0          champion_chen      add IC check
28  *     2013-12-16    2.1          champion_chen      fix bug in Additional packet number
29  *     2013-12-25    2.2          champion_chen      open host flow control after send last fw packet
30  */
31 
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>
34 #endif
35 
36 #include <stdio.h>
37 #include <errno.h>
38 #include <unistd.h>
39 #include <stdlib.h>
40 #include <termios.h>
41 #include <time.h>
42 #include <sys/time.h>
43 #include <sys/types.h>
44 #include <sys/param.h>
45 #include <sys/ioctl.h>
46 #include <sys/socket.h>
47 #include <sys/uio.h>
48 #include <sys/stat.h>
49 #include <fcntl.h>
50 #include <signal.h>
51 #include <stdint.h>
52 #include <string.h>
53 #include <endian.h>
54 #include <byteswap.h>
55 #include <netinet/in.h>
56 
57 #include "hciattach.h"
58 
59 #define RTK_VERSION "4.1"
60 
61 /* #define RTL_8703A_SUPPORT */
62 
63 #define USE_CUSTOMER_ADDRESS
64 
65 #define BAUDRATE_4BYTES
66 #define FIRMWARE_DIRECTORY  "/lib/firmware/rtlbt/"
67 #define BT_CONFIG_DIRECTORY "/lib/firmware/rtlbt/"
68 
69 #ifdef USE_CUSTOMER_ADDRESS
70 #define BT_ADDR_FILE        "/opt/bdaddr"
71 static uint8_t customer_bdaddr = 0;
72 #endif
73 
74 #define CONFIG_TXPOWER	(1 << 0)
75 #define CONFIG_XTAL	(1 << 1)
76 #define CONFIG_BTMAC	(1 << 2)
77 
78 #define EXTRA_CONFIG_OPTION
79 #ifdef EXTRA_CONFIG_OPTION
80 #define EXTRA_CONFIG_FILE	"/opt/rtk_btconfig.txt"
81 static uint32_t config_flags;
82 static uint8_t txpower_cfg[4];
83 static uint8_t txpower_len;
84 static uint8_t xtal_cfg;
85 #endif
86 
87 #if __BYTE_ORDER == __LITTLE_ENDIAN
88 #define cpu_to_le16(d)  (d)
89 #define cpu_to_le32(d)  (d)
90 #define le16_to_cpu(d)  (d)
91 #define le32_to_cpu(d)  (d)
92 #elif __BYTE_ORDER == __BIG_ENDIAN
93 #define cpu_to_le16(d)  bswap_16(d)
94 #define cpu_to_le32(d)  bswap_32(d)
95 #define le16_to_cpu(d)  bswap_16(d)
96 #define le32_to_cpu(d)  bswap_32(d)
97 #else
98 #error "Unknown byte order"
99 #endif
100 
101 typedef uint8_t RT_U8, *PRT_U8;
102 typedef int8_t RT_S8, *PRT_S8;
103 typedef uint16_t RT_U16, *PRT_U16;
104 typedef int32_t RT_S32, *PRT_S32;
105 typedef uint32_t RT_U32, *PRT_U32;
106 
107 RT_U8 DBG_ON = 1;
108 #define LOG_STR     "Realtek Bluetooth"
109 #define RS_DBG(fmt, arg...) \
110     do{ \
111         if (DBG_ON) \
112             fprintf(stderr, "%s :" fmt "\n" , LOG_STR, ##arg); \
113     }while(0)
114 
115 #define RS_INFO(fmt, arg...) \
116     do{ \
117         fprintf(stderr, "%s :" fmt "\n", LOG_STR, ##arg); \
118     }while(0)
119 
120 #define RS_ERR(fmt, arg...) \
121     do{ \
122         fprintf(stderr, "%s ERROR: " fmt "\n", LOG_STR, ##arg); \
123     }while(0)
124 
125 #define HCI_COMMAND_HDR_SIZE        3
126 #define HCI_EVENT_HDR_SIZE          2
127 /* #define RTK_PATCH_LENGTH_MAX        24576	*/ //24*1024
128 #define RTK_PATCH_LENGTH_MAX        (40 * 1024)
129 #define PATCH_DATA_FIELD_MAX_SIZE   252
130 #define READ_DATA_SIZE              16
131 #define H5_MAX_RETRY_COUNT          40
132 
133 #define RTK_VENDOR_CONFIG_MAGIC     0x8723ab55
134 const RT_U8 RTK_EPATCH_SIGNATURE[8] =
135     { 0x52, 0x65, 0x61, 0x6C, 0x74, 0x65, 0x63, 0x68 };
136 const RT_U8 Extension_Section_SIGNATURE[4] = { 0x51, 0x04, 0xFD, 0x77 };
137 
138 #define HCI_CMD_READ_BD_ADDR                0x1009
139 #define HCI_VENDOR_CHANGE_BDRATE            0xfc17
140 #define HCI_VENDOR_READ_RTK_ROM_VERISION    0xfc6d
141 #define HCI_CMD_READ_LOCAL_VERISION         0x1001
142 #define HCI_VENDOR_READ_CHIP_TYPE           0xfc61
143 
144 #define ROM_LMP_NONE            0x0000
145 #define ROM_LMP_8723a           0x1200
146 #define ROM_LMP_8723b           0x8723
147 #define ROM_LMP_8821a           0x8821
148 #define ROM_LMP_8761a           0x8761
149 #define ROM_LMP_8761btc		0x8763
150 
151 #define ROM_LMP_8703a           0x87b3
152 #define ROM_LMP_8763a           0x8763
153 #define ROM_LMP_8703b           0x8703
154 #define ROM_LMP_8723c           0x87c3 /* ??????? */
155 #define ROM_LMP_8822b           0x8822
156 #define ROM_LMP_8723cs_xx       0x8704
157 #define ROM_LMP_8723cs_cg       0x8705
158 #define ROM_LMP_8723cs_vf       0x8706
159 
160 /* Chip type */
161 #define CHIP_8703AS    1
162 #define CHIP_8723CS_CG 3
163 #define CHIP_8723CS_VF 4
164 #define CHIP_RTL8723CS_XX 5
165 #define CHIP_8703BS   7
166 
167 /* software id */
168 #define CHIP_UNKNOWN	0x00
169 #define CHIP_8761AT	0x1F
170 #define CHIP_8761ATF	0x2F
171 #define CHIP_8761BTC	0x3F
172 #define CHIP_8761B	0x4F
173 #define CHIP_BEFORE	0x6F
174 #define CHIP_8822BS	0x70
175 #define CHIP_8723DS	0x71
176 #define CHIP_8821CS	0x72
177 
178 /* HCI data types */
179 #define H5_ACK_PKT              0x00
180 #define HCI_COMMAND_PKT         0x01
181 #define HCI_ACLDATA_PKT         0x02
182 #define HCI_SCODATA_PKT         0x03
183 #define HCI_EVENT_PKT           0x04
184 #define H5_VDRSPEC_PKT          0x0E
185 #define H5_LINK_CTL_PKT         0x0F
186 
187 #define H5_HDR_SEQ(hdr)         ((hdr)[0] & 0x07)
188 #define H5_HDR_ACK(hdr)         (((hdr)[0] >> 3) & 0x07)
189 #define H5_HDR_CRC(hdr)         (((hdr)[0] >> 6) & 0x01)
190 #define H5_HDR_RELIABLE(hdr)    (((hdr)[0] >> 7) & 0x01)
191 #define H5_HDR_PKT_TYPE(hdr)    ((hdr)[1] & 0x0f)
192 #define H5_HDR_LEN(hdr)         ((((hdr)[1] >> 4) & 0xff) + ((hdr)[2] << 4))
193 #define H5_HDR_SIZE             4
194 
195 struct sk_buff {
196 	RT_U32 max_len;
197 	RT_U32 data_len;
198 	RT_U8 data[0];
199 };
200 
201 /* Skb helpers */
202 struct bt_skb_cb {
203 	RT_U8 pkt_type;
204 	RT_U8 incoming;
205 	RT_U16 expect;
206 	RT_U8 tx_seq;
207 	RT_U8 retries;
208 	RT_U8 sar;
209 	unsigned short channel;
210 };
211 
212 typedef struct {
213 	uint8_t index;
214 	uint8_t data[252];
215 } __attribute__ ((packed)) download_vendor_patch_cp;
216 
217 struct hci_command_hdr {
218 	RT_U16 opcode;
219 	RT_U8 plen;
220 } __attribute__ ((packed));
221 
222 struct hci_event_hdr {
223 	RT_U8 evt;
224 	RT_U8 plen;
225 } __attribute__ ((packed));
226 
227 struct hci_ev_cmd_complete {
228 	RT_U8 ncmd;
229 	RT_U16 opcode;
230 } __attribute__ ((packed));
231 
232 struct rtk_bt_vendor_config_entry {
233 	RT_U16 offset;
234 	RT_U8 entry_len;
235 	RT_U8 entry_data[0];
236 } __attribute__ ((packed));
237 
238 struct rtk_bt_vendor_config {
239 	RT_U32 signature;
240 	RT_U16 data_len;
241 	struct rtk_bt_vendor_config_entry entry[0];
242 } __attribute__ ((packed));
243 
244 struct rtk_epatch_entry {
245 	RT_U16 chipID;
246 	RT_U16 patch_length;
247 	RT_U32 start_offset;
248 	RT_U32 svn_ver;
249 	RT_U32 coex_ver;
250 } __attribute__ ((packed));
251 
252 struct rtk_epatch {
253 	RT_U8 signature[8];
254 	RT_U32 fw_version;
255 	RT_U16 number_of_patch;
256 	struct rtk_epatch_entry entry[0];
257 } __attribute__ ((packed));
258 
259 struct rtk_extension_entry {
260 	uint8_t opcode;
261 	uint8_t length;
262 	uint8_t *data;
263 } __attribute__ ((packed));
264 
265 typedef enum _RTK_ROM_VERSION_CMD_STATE {
266 	cmd_not_send,
267 	cmd_has_sent,
268 	event_received
269 } RTK_ROM_VERSION_CMD_STATE;
270 
271 typedef enum _H5_RX_STATE {
272 	H5_W4_PKT_DELIMITER,
273 	H5_W4_PKT_START,
274 	H5_W4_HDR,
275 	H5_W4_DATA,
276 	H5_W4_CRC
277 } H5_RX_STATE;
278 
279 typedef enum _H5_RX_ESC_STATE {
280 	H5_ESCSTATE_NOESC,
281 	H5_ESCSTATE_ESC
282 } H5_RX_ESC_STATE;
283 
284 typedef enum _H5_LINK_STATE {
285 	H5_SYNC,
286 	H5_CONFIG,
287 	H5_INIT,
288 	H5_PATCH,
289 	H5_ACTIVE
290 } H5_LINK_STATE;
291 
292 uint16_t project_id[]=
293 {
294 	ROM_LMP_8723a,
295 	ROM_LMP_8723b, /* RTL8723BS */
296 	ROM_LMP_8821a, /* RTL8821AS */
297 	ROM_LMP_8761a, /* RTL8761ATV */
298 
299 	ROM_LMP_8703a,
300 	ROM_LMP_8763a,
301 	ROM_LMP_8703b,
302 	ROM_LMP_8723c, /* index 7 for 8723CS. What is for other 8723CS  */
303 	ROM_LMP_8822b, /* RTL8822BS */
304 	ROM_LMP_8723b, /* RTL8723DS */
305 	ROM_LMP_8821a, /* id 10 for RTL8821CS, lmp subver 0x8821 */
306 	ROM_LMP_NONE
307 };
308 
309 #define RTL_FW_MATCH_CHIP_TYPE  (1 << 0)
310 #define RTL_FW_MATCH_HCI_VER    (1 << 1)
311 #define RTL_FW_MATCH_HCI_REV    (1 << 2)
312 struct patch_info {
313 	uint32_t    match_flags;
314 	uint8_t     chip_type;
315 	uint16_t    lmp_subver;
316 	uint16_t    proj_id;
317 	uint8_t     hci_ver;
318 	uint16_t    hci_rev;
319 	char        *patch_file;
320 	char        *config_file;
321 	char        *ic_name;
322 };
323 
324 static struct patch_info h4_patch_table[] = {
325 	/* match flags, chip type, lmp subver, proj id(unused), hci_ver,
326 	 * hci_rev, ...
327 	 */
328 
329 	/* RTL8761AT */
330 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_8761AT,
331 		0x8761, 0xffff, 0, 0x000a,
332 		"rtl8761at_fw", "rtl8761at_config", "RTL8761AT" },
333 	/* RTL8761ATF */
334 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_8761ATF,
335 		0x8761, 0xffff, 0, 0x000a,
336 		"rtl8761atf_fw", "rtl8761atf_config", "RTL8761ATF" },
337 	/* RTL8761B TC
338 	 * FW/Config is not used.
339 	 */
340 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_8761BTC,
341 		0x8763, 0xffff, 0, 0x000b,
342 		"rtl8761btc_fw", "rtl8761btc_config", "RTL8761BTC" },
343 	/* RTL8761B */
344 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_8761B,
345 		0x8761, 0xffff, 0, 0x000b,
346 		"rtl8761b_fw", "rtl8761b_config", "RTL8761B" },
347 
348 	{ 0, 0, 0, ROM_LMP_NONE, 0, 0, "rtl_none_fw", "rtl_none_config", "NONE"}
349 };
350 
351 static struct patch_info patch_table[] = {
352 	/* match flags, chip type, lmp subver, proj id(unused), hci_ver,
353 	 * hci_rev, ...
354 	 */
355 
356 	/* RTL8723AS */
357 	{ 0, 0, ROM_LMP_8723a, ROM_LMP_8723a, 0, 0,
358 		"rtl8723a_fw", "rtl8723a_config", "RTL8723AS"},
359 	/* RTL8821CS */
360 	{ RTL_FW_MATCH_HCI_REV, CHIP_8821CS,
361 		ROM_LMP_8821a, ROM_LMP_8821a, 0, 0x000c,
362 		"rtl8821c_fw", "rtl8821c_config", "RTL8821CS"},
363 	/* RTL8821AS */
364 	{ 0, 0, ROM_LMP_8821a, ROM_LMP_8821a, 0, 0,
365 		"rtl8821a_fw", "rtl8821a_config", "RTL8821AS"},
366 	/* RTL8761ATV */
367 	{ 0, 0, ROM_LMP_8761a, ROM_LMP_8761a, 0, 0,
368 		"rtl8761a_fw", "rtl8761a_config", "RTL8761ATV"},
369 
370 	/* RTL8703AS
371 	 * RTL8822BS
372 	 * */
373 #ifdef RTL_8703A_SUPPORT
374 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_8703AS,
375 		ROM_LMP_8723b, ROM_LMP_8723b, 0, 0,
376 		"rtl8703a_fw", "rtl8703a_config", "RTL8703AS"},
377 #endif
378 	{ 0, CHIP_8822BS, ROM_LMP_8822b, ROM_LMP_8822b, 0, 0,
379 		"rtl8822b_fw", "rtl8822b_config", "RTL8822BS"},
380 
381 	/* RTL8703BS
382 	 * RTL8723CS_XX
383 	 * RTL8723CS_CG
384 	 * RTL8723CS_VF
385 	 * */
386 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_8703BS,
387 		ROM_LMP_8703b, ROM_LMP_8703b, 0, 0,
388 		"rtl8703b_fw", "rtl8703b_config", "RTL8703BS"},
389 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_RTL8723CS_XX,
390 		ROM_LMP_8703b, ROM_LMP_8723cs_xx, 0, 0,
391 		"rtl8723cs_xx_fw", "rtl8723cs_xx_config", "RTL8723CS_XX"},
392 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_8723CS_CG,
393 		ROM_LMP_8703b, ROM_LMP_8723cs_cg, 0, 0,
394 		"rtl8723cs_cg_fw", "rtl8723cs_cg_config", "RTL8723CS_CG"},
395 	{ RTL_FW_MATCH_CHIP_TYPE, CHIP_8723CS_VF,
396 		ROM_LMP_8703b, ROM_LMP_8723cs_vf, 0, 0,
397 		"rtl8723cs_vf_fw", "rtl8723cs_vf_config", "RTL8723CS_VF"},
398 
399 	/* RTL8723BS */
400 	{ RTL_FW_MATCH_HCI_VER | RTL_FW_MATCH_HCI_REV, 0,
401 		ROM_LMP_8723b, ROM_LMP_8723b, 6, 0x000b,
402 		"rtl8723b_fw", "rtl8723b_config", "RTL8723BS"},
403 	/* RTL8723DS */
404 	{ RTL_FW_MATCH_HCI_VER | RTL_FW_MATCH_HCI_REV, CHIP_8723DS,
405 		ROM_LMP_8723b, ROM_LMP_8723b, 8, 0x000d,
406 		"rtl8723d_fw", "rtl8723d_config", "RTL8723DS"},
407 	/* add entries here*/
408 
409 	{ 0, 0, 0, ROM_LMP_NONE, 0, 0, "rtl_none_fw", "rtl_none_config", "NONE"}
410 };
411 
412 typedef struct btrtl_info {
413 /**********************h5 releated*************************/
414 	RT_U8 rxseq_txack;	/* expected rx seq number */
415 	RT_U8 rxack;	/* last packet sent by us that the peer ack'ed */
416 	RT_U8 use_crc;
417 	RT_U8 is_txack_req;	/* txack required */
418 	RT_U8 msgq_txseq;	/* next pkt seq */
419 	RT_U16 message_crc;
420 	RT_U32 rx_count;	/* expected pkts to recv */
421 
422 	H5_RX_STATE rx_state;
423 	H5_RX_ESC_STATE rx_esc_state;
424 	H5_LINK_STATE link_estab_state;
425 
426 	struct sk_buff *rx_skb;
427 	struct sk_buff *host_last_cmd;
428 
429 	uint16_t num_of_cmd_sent;
430 	RT_U16 lmp_subver;
431 	uint16_t hci_rev;
432 	uint8_t hci_ver;
433 	RT_U8 eversion;
434 	int h5_max_retries;
435 	RT_U8 chip_type;
436 
437 /**********************patch related************************/
438 	uint32_t baudrate;
439 	uint8_t dl_fw_flag;
440 	int serial_fd;
441 	int hw_flow_control;
442 	int final_speed;
443 	int total_num;	/* total pkt number */
444 	int tx_index;	/* current sending pkt number */
445 	int rx_index;	/* ack index from board */
446 	int fw_len;	/* fw patch file len */
447 	int config_len;	/* config patch file len */
448 	int total_len;	/* fw & config extracted buf len */
449 	uint8_t *fw_buf;	/* fw patch file buf */
450 	uint8_t *config_buf;	/* config patch file buf */
451 	uint8_t *total_buf;	/* fw & config extracted buf */
452 	RTK_ROM_VERSION_CMD_STATE rom_version_cmd_state;
453 	RTK_ROM_VERSION_CMD_STATE hci_version_cmd_state;
454 	RTK_ROM_VERSION_CMD_STATE chip_type_cmd_state;
455 
456 	struct patch_info *patch_ent;
457 
458 	int proto;
459 } rtk_hw_cfg_t;
460 
461 static rtk_hw_cfg_t rtk_hw_cfg;
462 
util_hexdump(const uint8_t * buf,size_t len)463 void util_hexdump(const uint8_t *buf, size_t len)
464 {
465 	static const char hexdigits[] = "0123456789abcdef";
466 	char str[16 * 3];
467 	size_t i;
468 
469 	if (!buf || !len)
470 		return;
471 
472 	for (i = 0; i < len; i++) {
473 		str[((i % 16) * 3)] = hexdigits[buf[i] >> 4];
474 		str[((i % 16) * 3) + 1] = hexdigits[buf[i] & 0xf];
475 		str[((i % 16) * 3) + 2] = ' ';
476 		if ((i + 1) % 16 == 0) {
477 			str[16 * 3 - 1] = '\0';
478 			RS_INFO("%s", str);
479 		}
480 	}
481 
482 	if (i % 16 > 0) {
483 		str[(i % 16) * 3 - 1] = '\0';
484 		RS_INFO("%s", str);
485 	}
486 }
487 
488 #ifdef EXTRA_CONFIG_OPTION
489 
xtalset_supported(void)490 static inline int xtalset_supported(void)
491 {
492 	struct patch_info *pent = rtk_hw_cfg.patch_ent;
493 
494 	/* Only support rtl8723ds, rtl8822bs and rtl8821cs xtal config */
495 	if (pent->chip_type != CHIP_8723DS &&
496 	    pent->chip_type != CHIP_8822BS &&
497 	    pent->chip_type != CHIP_8821CS)
498 		return 0;
499 
500 	return 1;
501 }
502 
line_proc(char * buff,int len)503 static void line_proc(char *buff, int len)
504 {
505 	char *argv[32];
506 	int nargs = 0;
507 	RS_INFO("%s", buff);
508 
509 	while (nargs < 32) {
510 		/* skip any white space */
511 		while ((*buff == ' ') || (*buff == '\t') ||
512 			*buff == ',') {
513 			++buff;
514 		}
515 
516 		if (*buff == '\0') {
517 			/* end of line, no more args */
518 			argv[nargs] = NULL;
519 			break;
520 		}
521 
522 		/* begin of argument string */
523 		argv[nargs++] = buff;
524 
525 		/* find end of string */
526 		while (*buff && (*buff != ' ') && (*buff != '\t')) {
527 			++buff;
528 		}
529 
530 		if (*buff == '\r' || *buff == '\n')
531 			++buff;
532 
533 		if (*buff == '\0') {
534 			/* end of line, no more args */
535 			argv[nargs] = NULL;
536 			break;
537 		}
538 
539 		*buff++ = '\0';	/* terminate current arg */
540 	}
541 
542 	/* valid config */
543 	if (nargs >= 4) {
544 		unsigned long int offset;
545 		uint8_t l;
546 		uint8_t i = 0;
547 
548 		offset = strtoul(argv[0], NULL, 16);
549 		offset = offset | (strtoul(argv[1], NULL, 16) << 8);
550 		RS_INFO("extra config offset %04lx", offset);
551 		l = strtoul(argv[2], NULL, 16);
552 		if (l != (uint8_t)(nargs - 3)) {
553 			RS_ERR("invalid len %u", l);
554 			return;
555 		}
556 
557 		if (offset == 0x015b && l <= 4) {
558 			/* Tx power */
559 			for (i = 0; i < l; i++)
560 				txpower_cfg[i] = (uint8_t)strtoul(argv[3 + i], NULL, 16);
561 			txpower_len = l;
562 			config_flags |= CONFIG_TXPOWER;
563 		} else if (offset == 0x01e6) {
564 			/* XTAL for 8822B, 8821C 8723D */
565 			xtal_cfg = (uint8_t)strtoul(argv[3], NULL, 16);
566 			config_flags |= CONFIG_XTAL;
567 		} else {
568 			RS_ERR("extra config %04lx is not supported", offset);
569 		}
570 	}
571 }
572 
config_proc(uint8_t * buff,int len)573 static void config_proc(uint8_t *buff, int len)
574 {
575 	uint8_t *head = buff;
576 	uint8_t *ptr = buff;
577 	int l;
578 
579 	while (len > 0) {
580 		ptr = strchr(head, '\n');
581 		if (!ptr)
582 			break;
583 		*ptr++ = '\0';
584 		while (*head == ' ' || *head == '\t')
585 			head++;
586 		l = ptr - head;
587 		if (l > 0 && *head != '#')
588 			line_proc(head, l);
589 		head = ptr;
590 		len -= l;
591 	}
592 }
593 
config_file_proc(const char * path)594 static void config_file_proc(const char *path)
595 {
596 	int fd;
597 	uint8_t buff[256];
598 	int result;
599 
600 	fd = open(path, O_RDONLY);
601 	if (fd == -1) {
602 		RS_INFO("Couldnt open extra config %s, %s", path, strerror(errno));
603 		return;
604 	}
605 
606 	result = read(fd, buff, sizeof(buff));
607 	if (result == -1) {
608 		RS_ERR("Couldnt read %s, %s", path, strerror(errno));
609 		close(fd);
610 		return;
611 	} else if (result == 0) {
612 		RS_ERR("File is empty");
613 		close(fd);
614 		return;
615 	}
616 
617 	config_proc(buff, result);
618 
619 	close(fd);
620 }
621 #endif
622 
623 /* Get the entry from patch_table according to LMP subversion */
get_patch_entry(struct btrtl_info * btrtl)624 struct patch_info *get_patch_entry(struct btrtl_info *btrtl)
625 {
626 	struct patch_info *n = NULL;
627 
628 	if (btrtl->proto == HCI_UART_3WIRE)
629 		n = patch_table;
630 	else
631 		n = h4_patch_table;
632 	for (; n->lmp_subver; n++) {
633 		if ((n->match_flags & RTL_FW_MATCH_CHIP_TYPE) &&
634 		    n->chip_type != btrtl->chip_type)
635 			continue;
636 		if ((n->match_flags & RTL_FW_MATCH_HCI_VER) &&
637 		    n->hci_ver != btrtl->hci_ver)
638 			continue;
639 		if ((n->match_flags & RTL_FW_MATCH_HCI_REV) &&
640 		    n->hci_rev != btrtl->hci_rev)
641 			continue;
642 		if (n->lmp_subver != btrtl->lmp_subver)
643 			continue;
644 
645 		break;
646 	}
647 
648 	return n;
649 }
650 
651 // bite reverse in bytes
652 // 00000001 -> 10000000
653 // 00000100 -> 00100000
654 const RT_U8 byte_rev_table[256] = {
655 	0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
656 	0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
657 	0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
658 	0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
659 	0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
660 	0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
661 	0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
662 	0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
663 	0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
664 	0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
665 	0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
666 	0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
667 	0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
668 	0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
669 	0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
670 	0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
671 	0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
672 	0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
673 	0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
674 	0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
675 	0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
676 	0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
677 	0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
678 	0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
679 	0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
680 	0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
681 	0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
682 	0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
683 	0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
684 	0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
685 	0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
686 	0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
687 };
688 
bit_rev8(RT_U8 byte)689 static __inline RT_U8 bit_rev8(RT_U8 byte)
690 {
691 	return byte_rev_table[byte];
692 }
693 
bit_rev16(RT_U16 x)694 static __inline RT_U16 bit_rev16(RT_U16 x)
695 {
696 	return (bit_rev8(x & 0xff) << 8) | bit_rev8(x >> 8);
697 }
698 
699 static const RT_U16 crc_table[] = {
700 	0x0000, 0x1081, 0x2102, 0x3183,
701 	0x4204, 0x5285, 0x6306, 0x7387,
702 	0x8408, 0x9489, 0xa50a, 0xb58b,
703 	0xc60c, 0xd68d, 0xe70e, 0xf78f
704 };
705 
706 // Initialise the crc calculator
707 #define H5_CRC_INIT(x) x = 0xffff
708 
709 /**
710 * Malloc the socket buffer
711 *
712 * @param skb socket buffer
713 * @return the point to the malloc buffer
714 */
skb_alloc(unsigned int len)715 static __inline struct sk_buff *skb_alloc(unsigned int len)
716 {
717 	struct sk_buff *skb = NULL;
718 	if ((skb = malloc(len + 8))) {
719 		skb->max_len = len;
720 		skb->data_len = 0;
721 	} else {
722 		RS_ERR("Allocate skb fails!!!");
723 		skb = NULL;
724 	}
725 	memset(skb->data, 0, len);
726 	return skb;
727 }
728 
729 /**
730 * Free the socket buffer
731 *
732 * @param skb socket buffer
733 */
skb_free(struct sk_buff * skb)734 static __inline void skb_free(struct sk_buff *skb)
735 {
736 	free(skb);
737 	return;
738 }
739 
740 /**
741 * Increase the date length in sk_buffer by len,
742 * and return the increased header pointer
743 *
744 * @param skb socket buffer
745 * @param len length want to increase
746 * @return the pointer to increased header
747 */
skb_put(struct sk_buff * skb,RT_U32 len)748 static RT_U8 *skb_put(struct sk_buff *skb, RT_U32 len)
749 {
750 	RT_U32 old_len = skb->data_len;
751 	if ((skb->data_len + len) > (skb->max_len)) {
752 		RS_ERR("Buffer too small");
753 		return NULL;
754 	}
755 	skb->data_len += len;
756 	return (skb->data + old_len);
757 }
758 
759 /**
760 * decrease data length in sk_buffer by to len by cut the tail
761 *
762 * @warning len should be less than skb->len
763 *
764 * @param skb socket buffer
765 * @param len length want to be changed
766 */
skb_trim(struct sk_buff * skb,unsigned int len)767 static void skb_trim(struct sk_buff *skb, unsigned int len)
768 {
769 	if (skb->data_len > len) {
770 		skb->data_len = len;
771 	} else {
772 		RS_ERR("Error: skb->data_len(%d) < len(%d)", skb->data_len,
773 		       len);
774 	}
775 }
776 
777 /**
778 * Decrease the data length in sk_buffer by len,
779 * and move the content forward to the header.
780 * the data in header will be removed.
781 *
782 * @param skb socket buffer
783 * @param len length of data
784 * @return new data
785 */
skb_pull(struct sk_buff * skb,RT_U32 len)786 static RT_U8 *skb_pull(struct sk_buff *skb, RT_U32 len)
787 {
788 	skb->data_len -= len;
789 	unsigned char *buf;
790 	if (!(buf = malloc(skb->data_len))) {
791 		RS_ERR("Unable to allocate file buffer");
792 		exit(1);
793 	}
794 	memcpy(buf, skb->data + len, skb->data_len);
795 	memcpy(skb->data, buf, skb->data_len);
796 	free(buf);
797 	return (skb->data);
798 }
799 
800 /**
801 * Add "d" into crc scope, caculate the new crc value
802 *
803 * @param crc crc data
804 * @param d one byte data
805 */
h5_crc_update(RT_U16 * crc,RT_U8 d)806 static void h5_crc_update(RT_U16 * crc, RT_U8 d)
807 {
808 	RT_U16 reg = *crc;
809 
810 	reg = (reg >> 4) ^ crc_table[(reg ^ d) & 0x000f];
811 	reg = (reg >> 4) ^ crc_table[(reg ^ (d >> 4)) & 0x000f];
812 
813 	*crc = reg;
814 }
815 
816 struct __una_u16 {
817 	RT_U16 x;
818 };
__get_unaligned_cpu16(const void * p)819 static __inline RT_U16 __get_unaligned_cpu16(const void *p)
820 {
821 	const struct __una_u16 *ptr = (const struct __una_u16 *)p;
822 	return ptr->x;
823 }
824 
get_unaligned_be16(const void * p)825 static __inline RT_U16 get_unaligned_be16(const void *p)
826 {
827 	return __get_unaligned_cpu16((const RT_U8 *)p);
828 }
829 
get_unaligned_le16(RT_U8 * p)830 static __inline RT_U16 get_unaligned_le16(RT_U8 * p)
831 {
832 	return (RT_U16) (*p) + ((RT_U16) (*(p + 1)) << 8);
833 }
834 
get_unaligned_le32(RT_U8 * p)835 static __inline RT_U32 get_unaligned_le32(RT_U8 * p)
836 {
837 	return (RT_U32) (*p) + ((RT_U32) (*(p + 1)) << 8) +
838 	    ((RT_U32) (*(p + 2)) << 16) + ((RT_U32) (*(p + 3)) << 24);
839 }
840 
841 /**
842 * Get crc data.
843 *
844 * @param h5 realtek h5 struct
845 * @return crc data
846 */
h5_get_crc(rtk_hw_cfg_t * h5)847 static RT_U16 h5_get_crc(rtk_hw_cfg_t * h5)
848 {
849 	RT_U16 crc = 0;
850 	RT_U8 *data = h5->rx_skb->data + h5->rx_skb->data_len - 2;
851 	crc = data[1] + (data[0] << 8);
852 	return crc;
853 //    return get_unaligned_be16(&h5->rx_skb->data[h5->rx_skb->data_len - 2]);
854 }
855 
856 /**
857 * Just add 0xc0 at the end of skb,
858 * we can also use this to add 0xc0 at start while there is no data in skb
859 *
860 * @param skb socket buffer
861 */
h5_slip_msgdelim(struct sk_buff * skb)862 static void h5_slip_msgdelim(struct sk_buff *skb)
863 {
864 	const char pkt_delim = 0xc0;
865 	memcpy(skb_put(skb, 1), &pkt_delim, 1);
866 }
867 
868 /**
869 * Slip ecode one byte in h5 proto, as follows:
870 * 0xc0 -> 0xdb, 0xdc
871 * 0xdb -> 0xdb, 0xdd
872 * 0x11 -> 0xdb, 0xde
873 * 0x13 -> 0xdb, 0xdf
874 * others will not change
875 *
876 * @param skb socket buffer
877 * @c pure data in the one byte
878 */
h5_slip_one_byte(struct sk_buff * skb,RT_U8 c)879 static void h5_slip_one_byte(struct sk_buff *skb, RT_U8 c)
880 {
881 	const RT_S8 esc_c0[2] = { 0xdb, 0xdc };
882 	const RT_S8 esc_db[2] = { 0xdb, 0xdd };
883 	const RT_S8 esc_11[2] = { 0xdb, 0xde };
884 	const RT_S8 esc_13[2] = { 0xdb, 0xdf };
885 
886 	switch (c) {
887 	case 0xc0:
888 		memcpy(skb_put(skb, 2), &esc_c0, 2);
889 		break;
890 
891 	case 0xdb:
892 		memcpy(skb_put(skb, 2), &esc_db, 2);
893 		break;
894 
895 	case 0x11:
896 		memcpy(skb_put(skb, 2), &esc_11, 2);
897 		break;
898 
899 	case 0x13:
900 		memcpy(skb_put(skb, 2), &esc_13, 2);
901 		break;
902 
903 	default:
904 		memcpy(skb_put(skb, 1), &c, 1);
905 		break;
906 	}
907 }
908 
909 /**
910 * Decode one byte in h5 proto, as follows:
911 * 0xdb, 0xdc -> 0xc0
912 * 0xdb, 0xdd -> 0xdb
913 * 0xdb, 0xde -> 0x11
914 * 0xdb, 0xdf -> 0x13
915 * others will not change
916 *
917 * @param h5 realtek h5 struct
918 * @byte pure data in the one byte
919 */
h5_unslip_one_byte(rtk_hw_cfg_t * h5,unsigned char byte)920 static void h5_unslip_one_byte(rtk_hw_cfg_t * h5, unsigned char byte)
921 {
922 	const RT_U8 c0 = 0xc0, db = 0xdb;
923 	const RT_U8 oof1 = 0x11, oof2 = 0x13;
924 
925 	if (H5_ESCSTATE_NOESC == h5->rx_esc_state) {
926 		if (0xdb == byte) {
927 			h5->rx_esc_state = H5_ESCSTATE_ESC;
928 		} else {
929 			memcpy(skb_put(h5->rx_skb, 1), &byte, 1);
930 			//Check Pkt Header's CRC enable bit
931 			if ((h5->rx_skb->data[0] & 0x40) != 0
932 			    && h5->rx_state != H5_W4_CRC) {
933 				h5_crc_update(&h5->message_crc, byte);
934 			}
935 			h5->rx_count--;
936 		}
937 	} else if (H5_ESCSTATE_ESC == h5->rx_esc_state) {
938 		switch (byte) {
939 		case 0xdc:
940 			memcpy(skb_put(h5->rx_skb, 1), &c0, 1);
941 			if ((h5->rx_skb->data[0] & 0x40) != 0
942 			    && h5->rx_state != H5_W4_CRC)
943 				h5_crc_update(&h5->message_crc, 0xc0);
944 			h5->rx_esc_state = H5_ESCSTATE_NOESC;
945 			h5->rx_count--;
946 			break;
947 
948 		case 0xdd:
949 			memcpy(skb_put(h5->rx_skb, 1), &db, 1);
950 			if ((h5->rx_skb->data[0] & 0x40) != 0
951 			    && h5->rx_state != H5_W4_CRC)
952 				h5_crc_update(&h5->message_crc, 0xdb);
953 			h5->rx_esc_state = H5_ESCSTATE_NOESC;
954 			h5->rx_count--;
955 			break;
956 
957 		case 0xde:
958 			memcpy(skb_put(h5->rx_skb, 1), &oof1, 1);
959 			if ((h5->rx_skb->data[0] & 0x40) != 0
960 			    && h5->rx_state != H5_W4_CRC)
961 				h5_crc_update(&h5->message_crc, oof1);
962 			h5->rx_esc_state = H5_ESCSTATE_NOESC;
963 			h5->rx_count--;
964 			break;
965 
966 		case 0xdf:
967 			memcpy(skb_put(h5->rx_skb, 1), &oof2, 1);
968 			if ((h5->rx_skb->data[0] & 0x40) != 0
969 			    && h5->rx_state != H5_W4_CRC)
970 				h5_crc_update(&h5->message_crc, oof2);
971 			h5->rx_esc_state = H5_ESCSTATE_NOESC;
972 			h5->rx_count--;
973 			break;
974 
975 		default:
976 			RS_ERR("Error: Invalid byte %02x after esc byte", byte);
977 			skb_free(h5->rx_skb);
978 			h5->rx_skb = NULL;
979 			h5->rx_state = H5_W4_PKT_DELIMITER;
980 			h5->rx_count = 0;
981 			break;
982 		}
983 	}
984 }
985 
986 /**
987 * Prepare h5 packet, packet format as follow:
988 *  | LSB 4 octets  | 0 ~4095| 2 MSB
989 *  |packet header | payload | data integrity check |
990 *
991 * pakcket header fromat is show below:
992 *  | LSB 3 bits         | 3 bits				   | 1 bits   				     | 1 bits  		  |
993 *  | 4 bits 		   | 12 bits     | 8 bits MSB
994 *  |sequence number | acknowledgement number | data integrity check present | reliable packet |
995 *  |packet type | payload length | header checksum
996 *
997 * @param h5 realtek h5 struct
998 * @param data pure data
999 * @param len the length of data
1000 * @param pkt_type packet type
1001 * @return socket buff after prepare in h5 proto
1002 */
h5_prepare_pkt(rtk_hw_cfg_t * h5,RT_U8 * data,RT_S32 len,RT_S32 pkt_type)1003 static struct sk_buff *h5_prepare_pkt(rtk_hw_cfg_t * h5, RT_U8 * data,
1004 				      RT_S32 len, RT_S32 pkt_type)
1005 {
1006 	struct sk_buff *nskb;
1007 	RT_U8 hdr[4];
1008 	RT_U16 H5_CRC_INIT(h5_txmsg_crc);
1009 	int rel, i;
1010 
1011 	switch (pkt_type) {
1012 	case HCI_ACLDATA_PKT:
1013 	case HCI_COMMAND_PKT:
1014 	case HCI_EVENT_PKT:
1015 		rel = 1;	// reliable
1016 		break;
1017 
1018 	case H5_ACK_PKT:
1019 	case H5_VDRSPEC_PKT:
1020 	case H5_LINK_CTL_PKT:
1021 		rel = 0;	// unreliable
1022 		break;
1023 
1024 	default:
1025 		RS_ERR("Unknown packet type");
1026 		return NULL;
1027 	}
1028 
1029 	// Max len of packet: (original len +4(h5 hdr) +2(crc))*2
1030 	//   (because bytes 0xc0 and 0xdb are escaped, worst case is
1031 	//   when the packet is all made of 0xc0 and 0xdb :) )
1032 	//   + 2 (0xc0 delimiters at start and end).
1033 
1034 	nskb = skb_alloc((len + 6) * 2 + 2);
1035 	if (!nskb)
1036 		return NULL;
1037 
1038 	//Add SLIP start byte: 0xc0
1039 	h5_slip_msgdelim(nskb);
1040 	// set AckNumber in SlipHeader
1041 	hdr[0] = h5->rxseq_txack << 3;
1042 	h5->is_txack_req = 0;
1043 
1044 	//RS_DBG("We request packet no(%u) to card", h5->rxseq_txack);
1045 	//RS_DBG("Sending packet with seqno %u and wait %u", h5->msgq_txseq, h5->rxseq_txack);
1046 	if (rel) {
1047 		// set reliable pkt bit and SeqNumber
1048 		hdr[0] |= 0x80 + h5->msgq_txseq;
1049 		//RS_DBG("Sending packet with seqno(%u)", h5->msgq_txseq);
1050 		++(h5->msgq_txseq);
1051 		h5->msgq_txseq = (h5->msgq_txseq) & 0x07;
1052 	}
1053 	// set DicPresent bit
1054 	if (h5->use_crc)
1055 		hdr[0] |= 0x40;
1056 
1057 	// set packet type and payload length
1058 	hdr[1] = ((len << 4) & 0xff) | pkt_type;
1059 	hdr[2] = (RT_U8) (len >> 4);
1060 	// set checksum
1061 	hdr[3] = ~(hdr[0] + hdr[1] + hdr[2]);
1062 
1063 	// Put h5 header */
1064 	for (i = 0; i < 4; i++) {
1065 		h5_slip_one_byte(nskb, hdr[i]);
1066 
1067 		if (h5->use_crc)
1068 			h5_crc_update(&h5_txmsg_crc, hdr[i]);
1069 	}
1070 
1071 	// Put payload */
1072 	for (i = 0; i < len; i++) {
1073 		h5_slip_one_byte(nskb, data[i]);
1074 
1075 		if (h5->use_crc)
1076 			h5_crc_update(&h5_txmsg_crc, data[i]);
1077 	}
1078 
1079 	// Put CRC */
1080 	if (h5->use_crc) {
1081 		h5_txmsg_crc = bit_rev16(h5_txmsg_crc);
1082 		h5_slip_one_byte(nskb, (RT_U8) ((h5_txmsg_crc >> 8) & 0x00ff));
1083 		h5_slip_one_byte(nskb, (RT_U8) (h5_txmsg_crc & 0x00ff));
1084 	}
1085 	// Add SLIP end byte: 0xc0
1086 	h5_slip_msgdelim(nskb);
1087 	return nskb;
1088 }
1089 
1090 /**
1091 * Removed controller acked packet from Host's unacked lists
1092 *
1093 * @param h5 realtek h5 struct
1094 */
h5_remove_acked_pkt(rtk_hw_cfg_t * h5)1095 static void h5_remove_acked_pkt(rtk_hw_cfg_t * h5)
1096 {
1097 	int pkts_to_be_removed = 0;
1098 	int seqno = 0;
1099 	int i = 0;
1100 
1101 	seqno = h5->msgq_txseq;
1102 	//pkts_to_be_removed = GetListLength(h5->unacked);
1103 
1104 	while (pkts_to_be_removed) {
1105 		if (h5->rxack == seqno)
1106 			break;
1107 
1108 		pkts_to_be_removed--;
1109 		seqno = (seqno - 1) & 0x07;
1110 	}
1111 
1112 	if (h5->rxack != seqno) {
1113 		RS_DBG("Peer acked invalid packet");
1114 	}
1115 	//skb_queue_walk_safe(&h5->unack, skb, tmp) // remove ack'ed packet from h5->unack queue
1116 	for (i = 0; i < 5; ++i) {
1117 		if (i >= pkts_to_be_removed)
1118 			break;
1119 		i++;
1120 		//__skb_unlink(skb, &h5->unack);
1121 		//skb_free(skb);
1122 	}
1123 
1124 	//  if (skb_queue_empty(&h5->unack))
1125 	//          del_timer(&h5->th5);
1126 	//  spin_unlock_irqrestore(&h5->unack.lock, flags);
1127 
1128 	if (i != pkts_to_be_removed)
1129 		RS_DBG("Removed only (%u) out of (%u) pkts", i,
1130 		       pkts_to_be_removed);
1131 }
1132 
1133 /**
1134 * Realtek send pure ack, send a packet only with an ack
1135 *
1136 * @param fd uart file descriptor
1137 *
1138 */
rtk_send_pure_ack_down(int fd)1139 static void rtk_send_pure_ack_down(int fd)
1140 {
1141 	struct sk_buff *nskb = h5_prepare_pkt(&rtk_hw_cfg, NULL, 0, H5_ACK_PKT);
1142 	write(fd, nskb->data, nskb->data_len);
1143 	skb_free(nskb);
1144 	return;
1145 }
1146 
1147 /**
1148 * Parse hci event command complete, pull the cmd complete event header
1149 *
1150 * @param skb socket buffer
1151 *
1152 */
hci_event_cmd_complete(struct sk_buff * skb)1153 static void hci_event_cmd_complete(struct sk_buff *skb)
1154 {
1155 	struct hci_event_hdr *hdr = (struct hci_event_hdr *)skb->data;
1156 	struct hci_ev_cmd_complete *ev = NULL;
1157 	RT_U16 opcode = 0;
1158 	RT_U8 status = 0;
1159 
1160 	//pull hdr
1161 	skb_pull(skb, HCI_EVENT_HDR_SIZE);
1162 	ev = (struct hci_ev_cmd_complete *)skb->data;
1163 	opcode = le16_to_cpu(ev->opcode);
1164 
1165 	RS_DBG("receive hci command complete event with command:%x\n", opcode);
1166 
1167 	//pull command complete event header
1168 	skb_pull(skb, sizeof(struct hci_ev_cmd_complete));
1169 
1170 	switch (opcode) {
1171 	case HCI_VENDOR_CHANGE_BDRATE:
1172 		status = skb->data[0];
1173 		RS_DBG("Change BD Rate with status:%x", status);
1174 		skb_free(rtk_hw_cfg.host_last_cmd);
1175 		rtk_hw_cfg.host_last_cmd = NULL;
1176 		rtk_hw_cfg.link_estab_state = H5_PATCH;
1177 		break;
1178 
1179 	case HCI_CMD_READ_BD_ADDR:
1180 		status = skb->data[0];
1181 		RS_DBG("Read BD Address with Status:%x", status);
1182 		if (!status) {
1183 			RS_DBG("BD Address: %8x%8x", *(int *)&skb->data[1],
1184 			       *(int *)&skb->data[5]);
1185 		}
1186 		break;
1187 
1188 	case HCI_CMD_READ_LOCAL_VERISION:
1189 		rtk_hw_cfg.hci_version_cmd_state = event_received;
1190 		status = skb->data[0];
1191 		RS_DBG("Read Local Version Information with Status:%x", status);
1192 		if (0 == status) {
1193 			rtk_hw_cfg.hci_ver = skb->data[1];
1194 			rtk_hw_cfg.hci_rev = (skb->data[2] | skb->data[3] << 8);
1195 			rtk_hw_cfg.lmp_subver =
1196 			    (skb->data[7] | (skb->data[8] << 8));
1197 			RS_DBG("HCI Version 0x%02x", rtk_hw_cfg.hci_ver);
1198 			RS_DBG("HCI Revision 0x%04x", rtk_hw_cfg.hci_rev);
1199 			RS_DBG("LMP Subversion 0x%04x", rtk_hw_cfg.lmp_subver);
1200 		} else {
1201 			RS_ERR("Read Local Version Info status error!");
1202 			//Need to do more
1203 		}
1204 		skb_free(rtk_hw_cfg.host_last_cmd);
1205 		rtk_hw_cfg.host_last_cmd = NULL;
1206 		break;
1207 
1208 	case HCI_VENDOR_READ_RTK_ROM_VERISION:
1209 		rtk_hw_cfg.rom_version_cmd_state = event_received;
1210 		status = skb->data[0];
1211 		RS_DBG("Read RTK rom version with Status:%x", status);
1212 		if (0 == status)
1213 			rtk_hw_cfg.eversion = skb->data[1];
1214 		else if (1 == status)
1215 			rtk_hw_cfg.eversion = 0;
1216 		else {
1217 			RS_ERR("READ_RTK_ROM_VERISION return status error!");
1218 			//Need to do more
1219 		}
1220 
1221 		skb_free(rtk_hw_cfg.host_last_cmd);
1222 		rtk_hw_cfg.host_last_cmd = NULL;
1223 		break;
1224 	case HCI_VENDOR_READ_CHIP_TYPE:
1225 		rtk_hw_cfg.chip_type_cmd_state = event_received;
1226 		status = skb->data[0];
1227 		RS_DBG("Read RTK chip type with Status:%x", status);
1228 		if (0 == status)
1229 			rtk_hw_cfg.chip_type= (skb->data[1] & 0x0f);
1230 		else
1231 			RS_ERR("READ_RTK_CHIP_TYPE return status error!");
1232 		skb_free(rtk_hw_cfg.host_last_cmd);
1233 		rtk_hw_cfg.host_last_cmd = NULL;
1234 		break;
1235 	default:
1236 		return;
1237 	}
1238 	rtk_hw_cfg.num_of_cmd_sent++;
1239 }
1240 
1241 /**
1242 * Check if it's a hci frame, if it is, complete it with response or parse the cmd complete event
1243 *
1244 * @param skb socket buffer
1245 *
1246 */
hci_recv_frame(struct sk_buff * skb)1247 static void hci_recv_frame(struct sk_buff *skb)
1248 {
1249 	int len;
1250 	unsigned char h5sync[2] = { 0x01, 0x7E }, h5syncresp[2] = {
1251 	0x02, 0x7D}, h5_sync_resp_pkt[0x8] = {
1252 	0xc0, 0x00, 0x2F, 0x00, 0xD0, 0x02, 0x7D, 0xc0},
1253 	    h5_conf_resp_pkt_to_Ctrl[0x8] = {
1254 	0xc0, 0x00, 0x2F, 0x00, 0xD0, 0x04, 0x7B, 0xc0}, h5conf[3] = {
1255 	0x03, 0xFC, 0x10}, h5confresp[3] = {
1256 	0x04, 0x7B, 0x10}, cmd_complete_evt_code = 0xe;
1257 
1258 	if (rtk_hw_cfg.link_estab_state == H5_SYNC) {
1259 		if (!memcmp(skb->data, h5sync, 2)) {
1260 			RS_DBG("Get SYNC Pkt\n");
1261 			len =
1262 			    write(rtk_hw_cfg.serial_fd, &h5_sync_resp_pkt, 0x8);
1263 		} else if (!memcmp(skb->data, h5syncresp, 2)) {
1264 			RS_DBG("Get SYNC Resp Pkt\n");
1265 			rtk_hw_cfg.link_estab_state = H5_CONFIG;
1266 		}
1267 		skb_free(skb);
1268 	} else if (rtk_hw_cfg.link_estab_state == H5_CONFIG) {
1269 		if (!memcmp(skb->data, h5sync, 0x2)) {
1270 			len =
1271 			    write(rtk_hw_cfg.serial_fd, &h5_sync_resp_pkt, 0x8);
1272 			RS_DBG("Get SYNC pkt-active mode\n");
1273 		} else if (!memcmp(skb->data, h5conf, 0x2)) {
1274 			len =
1275 			    write(rtk_hw_cfg.serial_fd,
1276 				  &h5_conf_resp_pkt_to_Ctrl, 0x8);
1277 			RS_DBG("Get CONFG pkt-active mode\n");
1278 		} else if (!memcmp(skb->data, h5confresp, 0x2)) {
1279 			RS_DBG("Get CONFG resp pkt-active mode\n");
1280 			rtk_hw_cfg.link_estab_state = H5_INIT;
1281 		} else {
1282 			RS_DBG("H5_CONFIG receive event\n");
1283 			rtk_send_pure_ack_down(rtk_hw_cfg.serial_fd);
1284 		}
1285 		skb_free(skb);
1286 	} else if (rtk_hw_cfg.link_estab_state == H5_INIT) {
1287 		if (skb->data[0] == cmd_complete_evt_code) {
1288 			hci_event_cmd_complete(skb);
1289 		}
1290 
1291 		rtk_send_pure_ack_down(rtk_hw_cfg.serial_fd);
1292 		usleep(10000);
1293 		rtk_send_pure_ack_down(rtk_hw_cfg.serial_fd);
1294 		usleep(10000);
1295 		rtk_send_pure_ack_down(rtk_hw_cfg.serial_fd);
1296 		skb_free(skb);
1297 	} else if (rtk_hw_cfg.link_estab_state == H5_PATCH) {
1298 		if (skb->data[0] != 0x0e) {
1299 			RS_DBG("Received event 0x%x\n", skb->data[0]);
1300 			skb_free(skb);
1301 			rtk_send_pure_ack_down(rtk_hw_cfg.serial_fd);
1302 			return;
1303 		}
1304 
1305 		rtk_hw_cfg.rx_index = skb->data[6];
1306 
1307 		RS_DBG("rtk_hw_cfg.rx_index %d\n", rtk_hw_cfg.rx_index);
1308 
1309 		/* Download fw/config done */
1310 		if (rtk_hw_cfg.rx_index & 0x80) {
1311 			rtk_hw_cfg.rx_index &= ~0x80;
1312 			rtk_hw_cfg.link_estab_state = H5_ACTIVE;
1313 		}
1314 
1315 		skb_free(skb);
1316 	} else {
1317 		RS_ERR("receive packets in active state");
1318 		skb_free(skb);
1319 	}
1320 }
1321 
1322 /**
1323 * after rx data is parsed, and we got a rx frame saved in h5->rx_skb,
1324 * this routinue is called.
1325 * things todo in this function:
1326 * 1. check if it's a hci frame, if it is, complete it with response or ack
1327 * 2. see the ack number, free acked frame in queue
1328 * 3. reset h5->rx_state, set rx_skb to null.
1329 *
1330 * @param h5 realtek h5 struct
1331 *
1332 */
h5_complete_rx_pkt(rtk_hw_cfg_t * h5)1333 static void h5_complete_rx_pkt(rtk_hw_cfg_t * h5)
1334 {
1335 	int pass_up = 1;
1336 	uint8_t *h5_hdr = NULL;
1337 
1338 	h5_hdr = (uint8_t *) (h5->rx_skb->data);
1339 	if (H5_HDR_RELIABLE(h5_hdr)) {
1340 		RS_DBG("Received reliable seqno %u from card", h5->rxseq_txack);
1341 		h5->rxseq_txack = H5_HDR_SEQ(h5_hdr) + 1;
1342 		h5->rxseq_txack %= 8;
1343 		h5->is_txack_req = 1;
1344 	}
1345 
1346 	h5->rxack = H5_HDR_ACK(h5_hdr);
1347 
1348 	switch (H5_HDR_PKT_TYPE(h5_hdr)) {
1349 	case HCI_ACLDATA_PKT:
1350 	case HCI_EVENT_PKT:
1351 	case HCI_SCODATA_PKT:
1352 	case HCI_COMMAND_PKT:
1353 	case H5_LINK_CTL_PKT:
1354 		pass_up = 1;
1355 		break;
1356 
1357 	default:
1358 		pass_up = 0;
1359 		break;
1360 	}
1361 
1362 	h5_remove_acked_pkt(h5);
1363 
1364 	if (pass_up) {
1365 		skb_pull(h5->rx_skb, H5_HDR_SIZE);
1366 		hci_recv_frame(h5->rx_skb);
1367 	} else {
1368 		skb_free(h5->rx_skb);
1369 	}
1370 
1371 	h5->rx_state = H5_W4_PKT_DELIMITER;
1372 	h5->rx_skb = NULL;
1373 }
1374 
1375 /**
1376 * Parse the receive data in h5 proto.
1377 *
1378 * @param h5 realtek h5 struct
1379 * @param data point to data received before parse
1380 * @param count num of data
1381 * @return reserved count
1382 */
h5_recv(rtk_hw_cfg_t * h5,void * data,int count)1383 static int h5_recv(rtk_hw_cfg_t * h5, void *data, int count)
1384 {
1385 	unsigned char *ptr;
1386 	//RS_DBG("count %d rx_state %d rx_count %ld", count, h5->rx_state, h5->rx_count);
1387 	ptr = (unsigned char *)data;
1388 
1389 	while (count) {
1390 		if (h5->rx_count) {
1391 			if (*ptr == 0xc0) {
1392 				RS_ERR("short h5 packet");
1393 				skb_free(h5->rx_skb);
1394 				h5->rx_state = H5_W4_PKT_START;
1395 				h5->rx_count = 0;
1396 			} else
1397 				h5_unslip_one_byte(h5, *ptr);
1398 
1399 			ptr++;
1400 			count--;
1401 			continue;
1402 		}
1403 
1404 		switch (h5->rx_state) {
1405 		case H5_W4_HDR:
1406 			/* check header checksum. see Core Spec V4 "3-wire uart" page 67 */
1407 			if ((0xff & (RT_U8) ~
1408 			     (h5->rx_skb->data[0] + h5->rx_skb->data[1] +
1409 			      h5->rx_skb->data[2])) != h5->rx_skb->data[3]) {
1410 				RS_ERR("h5 hdr checksum error!!!");
1411 				skb_free(h5->rx_skb);
1412 				h5->rx_state = H5_W4_PKT_DELIMITER;
1413 				h5->rx_count = 0;
1414 				continue;
1415 			}
1416 
1417 			/* reliable pkt  & h5->hdr->SeqNumber != h5->Rxseq_txack */
1418 			if (h5->rx_skb->data[0] & 0x80
1419 			    && (h5->rx_skb->data[0] & 0x07) !=
1420 			    h5->rxseq_txack) {
1421 				RS_ERR
1422 				    ("Out-of-order packet arrived, got(%u)expected(%u)",
1423 				     h5->rx_skb->data[0] & 0x07,
1424 				     h5->rxseq_txack);
1425 				h5->is_txack_req = 1;
1426 
1427 				skb_free(h5->rx_skb);
1428 				h5->rx_state = H5_W4_PKT_DELIMITER;
1429 				h5->rx_count = 0;
1430 
1431 				/* depend on weather remote will reset ack numb or not!!!!!!special */
1432 				if (rtk_hw_cfg.tx_index == rtk_hw_cfg.total_num) {
1433 					rtk_hw_cfg.rxseq_txack =
1434 					    h5->rx_skb->data[0] & 0x07;
1435 				}
1436 				continue;
1437 			}
1438 			h5->rx_state = H5_W4_DATA;
1439 			h5->rx_count =
1440 			    (h5->rx_skb->data[1] >> 4) +
1441 			    (h5->rx_skb->data[2] << 4);
1442 			continue;
1443 
1444 		case H5_W4_DATA:
1445 			/* pkt with crc */
1446 			if (h5->rx_skb->data[0] & 0x40) {
1447 				h5->rx_state = H5_W4_CRC;
1448 				h5->rx_count = 2;
1449 			} else {
1450 				h5_complete_rx_pkt(h5);
1451 				//RS_DBG(DF_SLIP,("--------> H5_W4_DATA ACK\n"));
1452 			}
1453 			continue;
1454 
1455 		case H5_W4_CRC:
1456 			if (bit_rev16(h5->message_crc) != h5_get_crc(h5)) {
1457 				RS_ERR
1458 				    ("Checksum failed, computed(%04x)received(%04x)",
1459 				     bit_rev16(h5->message_crc),
1460 				     h5_get_crc(h5));
1461 				skb_free(h5->rx_skb);
1462 				h5->rx_state = H5_W4_PKT_DELIMITER;
1463 				h5->rx_count = 0;
1464 				continue;
1465 			}
1466 			skb_trim(h5->rx_skb, h5->rx_skb->data_len - 2);
1467 			h5_complete_rx_pkt(h5);
1468 			continue;
1469 
1470 		case H5_W4_PKT_DELIMITER:
1471 			switch (*ptr) {
1472 			case 0xc0:
1473 				h5->rx_state = H5_W4_PKT_START;
1474 				break;
1475 
1476 			default:
1477 				break;
1478 			}
1479 			ptr++;
1480 			count--;
1481 			break;
1482 
1483 		case H5_W4_PKT_START:
1484 			switch (*ptr) {
1485 			case 0xc0:
1486 				ptr++;
1487 				count--;
1488 				break;
1489 
1490 			default:
1491 				h5->rx_state = H5_W4_HDR;
1492 				h5->rx_count = 4;
1493 				h5->rx_esc_state = H5_ESCSTATE_NOESC;
1494 				H5_CRC_INIT(h5->message_crc);
1495 
1496 				// Do not increment ptr or decrement count
1497 				// Allocate packet. Max len of a H5 pkt=
1498 				// 0xFFF (payload) +4 (header) +2 (crc)
1499 				h5->rx_skb = skb_alloc(0x1005);
1500 				if (!h5->rx_skb) {
1501 					h5->rx_state = H5_W4_PKT_DELIMITER;
1502 					h5->rx_count = 0;
1503 					return 0;
1504 				}
1505 				break;
1506 			}
1507 			break;
1508 
1509 		default:
1510 			break;
1511 		}
1512 	}
1513 	return count;
1514 }
1515 
1516 /**
1517 * Read data to buf from uart.
1518 *
1519 * @param fd uart file descriptor
1520 * @param buf point to the addr where read data stored
1521 * @param count num of data want to read
1522 * @return num of data successfully read
1523 */
read_check_rtk(int fd,void * buf,int count)1524 static int read_check_rtk(int fd, void *buf, int count)
1525 {
1526 	int res;
1527 	do {
1528 		res = read(fd, buf, count);
1529 		if (res != -1) {
1530 			buf = (RT_U8 *) buf + res;
1531 			count -= res;
1532 			return res;
1533 		}
1534 	} while (count && (errno == 0 || errno == EINTR));
1535 	return res;
1536 }
1537 
1538 /**
1539 * Retry to sync when timeout in h5 proto, max retry times is 10.
1540 *
1541 * @warning Each time to retry, the time for timeout will be set as 1s.
1542 *
1543 * @param sig signaction for timeout
1544 *
1545 */
h5_tsync_sig_alarm(int sig)1546 static void h5_tsync_sig_alarm(int sig)
1547 {
1548 	unsigned char h5sync[2] = { 0x01, 0x7E };
1549 	static int retries = 0;
1550 	struct itimerval value;
1551 
1552 	if (retries < rtk_hw_cfg.h5_max_retries) {
1553 		retries++;
1554 		struct sk_buff *nskb =
1555 		    h5_prepare_pkt(&rtk_hw_cfg, h5sync, sizeof(h5sync),
1556 				   H5_LINK_CTL_PKT);
1557 		int len =
1558 		    write(rtk_hw_cfg.serial_fd, nskb->data, nskb->data_len);
1559 		RS_DBG("3-wire sync pattern resend : %d, len: %d\n", retries,
1560 		       len);
1561 
1562 		skb_free(nskb);
1563 		//gordon add 2013-6-7 retry per 250ms
1564 		value.it_value.tv_sec = 0;
1565 		value.it_value.tv_usec = 250000;
1566 		value.it_interval.tv_sec = 0;
1567 		value.it_interval.tv_usec = 250000;
1568 		setitimer(ITIMER_REAL, &value, NULL);
1569 		//gordon end
1570 
1571 		return;
1572 	}
1573 
1574 	tcflush(rtk_hw_cfg.serial_fd, TCIOFLUSH);
1575 	RS_ERR("H5 sync timed out\n");
1576 	exit(1);
1577 }
1578 
1579 /**
1580 * Retry to config when timeout in h5 proto, max retry times is 10.
1581 *
1582 * @warning Each time to retry, the time for timeout will be set as 1s.
1583 *
1584 * @param sig signaction for timeout
1585 *
1586 */
h5_tconf_sig_alarm(int sig)1587 static void h5_tconf_sig_alarm(int sig)
1588 {
1589 	unsigned char h5conf[3] = { 0x03, 0xFC, 0x14 };
1590 	static int retries = 0;
1591 	struct itimerval value;
1592 
1593 	if (retries < rtk_hw_cfg.h5_max_retries) {
1594 		retries++;
1595 		struct sk_buff *nskb =
1596 		    h5_prepare_pkt(&rtk_hw_cfg, h5conf, 3, H5_LINK_CTL_PKT);
1597 		int len =
1598 		    write(rtk_hw_cfg.serial_fd, nskb->data, nskb->data_len);
1599 		RS_DBG("3-wire config pattern resend : %d , len: %d", retries,
1600 		       len);
1601 		skb_free(nskb);
1602 
1603 		//gordon add 2013-6-7 retry per 250ms
1604 		value.it_value.tv_sec = 0;
1605 		value.it_value.tv_usec = 250000;
1606 		value.it_interval.tv_sec = 0;
1607 		value.it_interval.tv_usec = 250000;
1608 		setitimer(ITIMER_REAL, &value, NULL);
1609 
1610 		return;
1611 	}
1612 
1613 	tcflush(rtk_hw_cfg.serial_fd, TCIOFLUSH);
1614 	RS_ERR("H5 config timed out\n");
1615 	exit(1);
1616 }
1617 
1618 /**
1619 * Retry to init when timeout in h5 proto, max retry times is 10.
1620 *
1621 * @warning Each time to retry, the time for timeout will be set as 1s.
1622 *
1623 * @param sig signaction for timeout
1624 *
1625 */
h5_tinit_sig_alarm(int sig)1626 static void h5_tinit_sig_alarm(int sig)
1627 {
1628 	static int retries = 0;
1629 	if (retries < rtk_hw_cfg.h5_max_retries) {
1630 		retries++;
1631 		if (rtk_hw_cfg.host_last_cmd) {
1632 			int len =
1633 			    write(rtk_hw_cfg.serial_fd,
1634 				  rtk_hw_cfg.host_last_cmd->data,
1635 				  rtk_hw_cfg.host_last_cmd->data_len);
1636 			RS_DBG("3-wire change baudrate re send:%d, len:%d",
1637 			       retries, len);
1638 			alarm(1);
1639 			return;
1640 		} else {
1641 			RS_DBG
1642 			    ("3-wire init timeout without last command stored\n");
1643 		}
1644 	}
1645 
1646 	tcflush(rtk_hw_cfg.serial_fd, TCIOFLUSH);
1647 	RS_ERR("H5 init process timed out");
1648 	exit(1);
1649 }
1650 
1651 /**
1652 * Retry to download patch when timeout in h5 proto, max retry times is 10.
1653 *
1654 * @warning Each time to retry, the time for timeout will be set as 3s.
1655 *
1656 * @param sig signaction for timeout
1657 *
1658 */
h5_tpatch_sig_alarm(int sig)1659 static void h5_tpatch_sig_alarm(int sig)
1660 {
1661 	static int retries = 0;
1662 	if (retries < rtk_hw_cfg.h5_max_retries) {
1663 		RS_ERR("patch timerout, retry:\n");
1664 		if (rtk_hw_cfg.host_last_cmd) {
1665 			int len =
1666 			    write(rtk_hw_cfg.serial_fd,
1667 				  rtk_hw_cfg.host_last_cmd->data,
1668 				  rtk_hw_cfg.host_last_cmd->data_len);
1669 			RS_DBG("3-wire download patch re send:%d", retries);
1670 		}
1671 		retries++;
1672 		alarm(3);
1673 		return;
1674 	}
1675 	RS_ERR("H5 patch timed out\n");
1676 	exit(1);
1677 }
1678 
1679 /**
1680 * Download patch using hci. For h5 proto, not recv reply for 2s will timeout.
1681 * Call h5_tpatch_sig_alarm for retry.
1682 *
1683 * @param dd uart file descriptor
1684 * @param index current index
1685 * @param data point to the config file
1686 * @param len current buf length
1687 * @return #0 on success
1688 *
1689 */
hci_download_patch(int dd,int index,uint8_t * data,int len,struct termios * ti)1690 static int hci_download_patch(int dd, int index, uint8_t * data, int len,
1691 			      struct termios *ti)
1692 {
1693 	unsigned char hcipatch[256] = { 0x20, 0xfc, 00 };
1694 	unsigned char bytes[READ_DATA_SIZE];
1695 	int retlen;
1696 	struct sigaction sa;
1697 
1698 	sa.sa_handler = h5_tpatch_sig_alarm;
1699 	sigaction(SIGALRM, &sa, NULL);
1700 	alarm(2);
1701 
1702 	download_vendor_patch_cp cp;
1703 	memset(&cp, 0, sizeof(cp));
1704 	cp.index = index;
1705 	if (data != NULL) {
1706 		memcpy(cp.data, data, len);
1707 	}
1708 
1709 	if (index & 0x80)
1710 		rtk_hw_cfg.tx_index = index & 0x7f;
1711 	else
1712 		rtk_hw_cfg.tx_index = index;
1713 
1714 	hcipatch[2] = len + 1;
1715 	memcpy(hcipatch + 3, &cp, len + 1);
1716 
1717 	struct sk_buff *nskb = h5_prepare_pkt(&rtk_hw_cfg, hcipatch, len + 4, HCI_COMMAND_PKT);	//data:len+head:4
1718 
1719 	if (rtk_hw_cfg.host_last_cmd) {
1720 		skb_free(rtk_hw_cfg.host_last_cmd);
1721 		rtk_hw_cfg.host_last_cmd = NULL;
1722 	}
1723 
1724 	rtk_hw_cfg.host_last_cmd = nskb;
1725 
1726 	len = write(dd, nskb->data, nskb->data_len);
1727 	RS_DBG("hci_download_patch tx_index:%d rx_index: %d\n",
1728 	       rtk_hw_cfg.tx_index, rtk_hw_cfg.rx_index);
1729 
1730 	while (rtk_hw_cfg.rx_index != rtk_hw_cfg.tx_index) {	//receive data and wait last pkt
1731 		if ((retlen = read_check_rtk(dd, &bytes, READ_DATA_SIZE)) == -1) {
1732 			RS_ERR("read fail\n");
1733 			return -1;
1734 		}
1735 		h5_recv(&rtk_hw_cfg, &bytes, retlen);
1736 	}
1737 
1738 	alarm(0);
1739 
1740 	return 0;
1741 }
1742 
1743 #define READ_TRY_MAX	6
os_read(int fd,uint8_t * buff,int len)1744 int os_read(int fd, uint8_t * buff, int len)
1745 {
1746 	int n;
1747 	int i;
1748 	int try = 0;
1749 
1750 	i = 0;
1751 	n = 0;
1752 	while (n < len) {
1753 		i = read(fd, buff + n, len - n);
1754 		if (i > 0)
1755 			n += i;
1756 		else if (i == 0) {
1757 			RS_DBG("read nothing.");
1758 			continue;
1759 		} else {
1760 			RS_ERR("read error, %s\n", strerror(errno));
1761 			try++;
1762 			if (try > READ_TRY_MAX) {
1763 				RS_ERR("read reaches max try number.\n");
1764 				return -1;
1765 			}
1766 			continue;
1767 		}
1768 	}
1769 
1770 	return n;
1771 }
1772 
1773 #define DUMP_HCI_EVT
1774 #ifdef DUMP_HCI_EVT
1775 #define HCI_DUMP_BUF_LEN 128
1776 static char hci_dump_buf[HCI_DUMP_BUF_LEN];
hci_dump_evt(uint8_t * buf,uint16_t len)1777 void hci_dump_evt(uint8_t * buf, uint16_t len)
1778 {
1779 	int n;
1780 	int i;
1781 
1782 	if (!buf || !len) {
1783 		RS_ERR("Invalid parameters %p, %u.\n", buf, len);
1784 		return;
1785 	}
1786 
1787 	n = 0;
1788 	for (i = 0; i < len; i++) {
1789 		n += sprintf(hci_dump_buf + n, "%02x ", buf[i]);
1790 		if ((i + 1) % 16 == 0) {
1791 			RS_DBG(" %s\n", hci_dump_buf);
1792 			n = 0;
1793 		}
1794 	}
1795 
1796 	if (i % 16)
1797 		RS_DBG(" %s\n", hci_dump_buf);
1798 }
1799 #endif
1800 
read_hci_evt(int fd,uint8_t * buff,uint8_t evt_code)1801 int read_hci_evt(int fd, uint8_t * buff, uint8_t evt_code)
1802 {
1803 	uint8_t *evt_buff = buff;
1804 	int ret;
1805 	int try_type = 0;
1806 	uint8_t vendor_evt = 0xff;
1807 
1808 start_read:
1809 	do {
1810 		ret = os_read(fd, evt_buff, 1);
1811 		if (ret == 1 && evt_buff[0] == 0x04)
1812 			break;
1813 		else {
1814 			RS_DBG("no pkt type, continue.");
1815 			try_type++;
1816 			continue;
1817 		}
1818 	} while (try_type < 6);
1819 
1820 	if (try_type >= 6)
1821 		return -1;
1822 
1823 	ret = os_read(fd, evt_buff + 1, 1);
1824 	if (ret < 0) {
1825 		RS_ERR("%s: failed to read event code\n", __func__);
1826 		return -1;
1827 	}
1828 
1829 	ret = os_read(fd, evt_buff + 2, 1);
1830 	if (ret < 0) {
1831 		RS_ERR("%s: failed to read parameter total len.\n", __func__);
1832 		return -1;
1833 	}
1834 
1835 	ret = os_read(fd, evt_buff + 3, evt_buff[2]);
1836 	if (ret < 0) {
1837 		RS_ERR("%s: failed to read payload of event.\n", __func__);
1838 		return -1;
1839 	}
1840 #ifdef DUMP_HCI_EVT
1841 	hci_dump_evt(evt_buff, ret + 3);
1842 #endif
1843 
1844 	/* This event to wake up host. */
1845 	if (evt_buff[1] == vendor_evt) {
1846 		try_type = 0;
1847 		RS_DBG("%s: found vendor evt, continue reading.\n", __func__);
1848 		goto start_read;
1849 	}
1850 
1851 	if (evt_buff[1] != evt_code) {
1852 		RS_ERR("%s: event code mismatches, %x, expect %x.\n",
1853 		       __func__, evt_buff[1], evt_code);
1854 		return -1;
1855 	}
1856 
1857 	return (ret + 3);
1858 }
1859 
1860 /**
1861 * Download h4 patch
1862 *
1863 * @param dd uart file descriptor
1864 * @param index current index
1865 * @param data point to the config file
1866 * @param len current buf length
1867 * @return ret_index
1868 *
1869 */
hci_download_patch_h4(int dd,int index,uint8_t * data,int len)1870 static int hci_download_patch_h4(int dd, int index, uint8_t * data, int len)
1871 {
1872 	unsigned char bytes[257] = { 0 };
1873 	unsigned char buf[257] = { 0x01, 0x20, 0xfc, 00 };
1874 	uint16_t readbytes = 0;
1875 	int cur_index = index;
1876 	int ret_Index = -1;
1877 	uint16_t res = 0;
1878 	int i = 0;
1879 	size_t total_len;
1880 	uint16_t w_len;
1881 	uint8_t rstatus;
1882 	int ret;
1883 	uint8_t opcode[2] = {
1884 		0x20, 0xfc,
1885 	};
1886 
1887 	RS_DBG("dd:%d, index:%d, len:%d", dd, index, len);
1888 	if (NULL != data) {
1889 		memcpy(&buf[5], data, len);
1890 	}
1891 
1892 	buf[3] = len + 1;
1893 	buf[4] = cur_index;
1894 	total_len = len + 5;
1895 
1896 	w_len = write(dd, buf, total_len);
1897 	RS_DBG("h4 write success with len: %d\n", w_len);
1898 
1899 	ret = read_hci_evt(dd, bytes, 0x0e);
1900 	if (ret < 0) {
1901 		RS_ERR("%s: read hci evt error.\n", __func__);
1902 		return -1;
1903 	}
1904 
1905 	/* RS_DBG("%s: bytes: %x %x %x %x %x %x.\n",
1906 	 *      __func__, bytes[0], bytes[1], bytes[2],
1907 	 *      bytes[3], bytes[4], bytes[5]); */
1908 
1909 	if ((0x04 == bytes[0]) && (opcode[0] == bytes[4])
1910 	    && (opcode[1] == bytes[5])) {
1911 		ret_Index = bytes[7];
1912 		rstatus = bytes[6];
1913 		RS_DBG("---->ret_Index:%d, ----->rstatus:%d\n", ret_Index,
1914 		       rstatus);
1915 		if (0x00 != rstatus) {
1916 			RS_ERR("---->read event status is wrong\n");
1917 			return -1;
1918 		}
1919 	} else {
1920 		RS_ERR("==========>Didn't read curret data\n");
1921 		return -1;
1922 	}
1923 
1924 	return ret_Index;
1925 }
1926 
1927 /**
1928 * Realtek change speed with h4 proto. Using vendor specified command packet to achieve this.
1929 *
1930 * @warning before write, need to wait 1s for device up
1931 *
1932 * @param fd uart file descriptor
1933 * @param baudrate the speed want to change
1934 * @return #0 on success
1935 */
rtk_vendor_change_speed_h4(int fd,RT_U32 baudrate)1936 static int rtk_vendor_change_speed_h4(int fd, RT_U32 baudrate)
1937 {
1938 	int res;
1939 	unsigned char bytes[257];
1940 	RT_U8 cmd[8] = { 0 };
1941 
1942 	cmd[0] = 1;	//cmd;
1943 	cmd[1] = 0x17;	//ocf
1944 	cmd[2] = 0xfc;	//ogf
1945 	cmd[3] = 4;	//length;
1946 
1947 	baudrate = cpu_to_le32(baudrate);
1948 #ifdef BAUDRATE_4BYTES
1949 	memcpy((RT_U16 *) & cmd[4], &baudrate, 4);
1950 #else
1951 	memcpy((RT_U16 *) & cmd[4], &baudrate, 2);
1952 	cmd[6] = 0;
1953 	cmd[7] = 0;
1954 #endif
1955 
1956 	//wait for a while for device to up, just h4 need it
1957 	sleep(1);
1958 	RS_DBG("baudrate in change speed command: 0x%x 0x%x 0x%x 0x%x \n",
1959 	       cmd[4], cmd[5], cmd[6], cmd[7]);
1960 
1961 	if (write(fd, cmd, 8) != 8) {
1962 		RS_ERR
1963 		    ("H4 change uart speed error when writing vendor command");
1964 		return -1;
1965 	}
1966 	RS_DBG("H4 Change uart Baudrate after write ");
1967 
1968 	res = read_hci_evt(fd, bytes, 0x0e);
1969 	if (res < 0) {
1970 		RS_ERR("%s: Failed to read hci evt.\n", __func__);
1971 		return -1;
1972 	}
1973 
1974 	if ((0x04 == bytes[0]) && (0x17 == bytes[4]) && (0xfc == bytes[5])) {
1975 		RS_DBG("H4 change uart speed success, receving status:%x",
1976 		       bytes[6]);
1977 		if (bytes[6] == 0)
1978 			return 0;
1979 	}
1980 	return -1;
1981 }
1982 
1983 /**
1984 * Parse realtek Bluetooth config file.
1985 * The config file if begin with vendor magic: RTK_VENDOR_CONFIG_MAGIC(8723ab55)
1986 * bt_addr is followed by 0x3c offset, it will be changed by bt_addr param
1987 * proto, baudrate and flow control is followed by 0xc offset,
1988 *
1989 * @param config_buf point to config file content
1990 * @param *plen length of config file
1991 * @param bt_addr where bt addr is stored
1992 * @return
1993 *  1. new config buf
1994 *  2. new config length *plen
1995 *  3. result (for baudrate)
1996 *
1997 */
1998 
rtk_parse_config_file(RT_U8 * config_buf,size_t * plen,uint8_t bt_addr[6],uint32_t * result)1999 uint8_t *rtk_parse_config_file(RT_U8 *config_buf, size_t *plen,
2000 			       uint8_t bt_addr[6], uint32_t *result)
2001 {
2002 
2003 	struct rtk_bt_vendor_config *config =
2004 	    (struct rtk_bt_vendor_config *)config_buf;
2005 	RT_U16 config_len = 0, temp = 0;
2006 	struct rtk_bt_vendor_config_entry *entry = NULL;
2007 	RT_U16 i;
2008 	RT_U32 baudrate = 0;
2009 	uint32_t flags = 0;
2010 	uint32_t add_flags;
2011 #ifdef USE_CUSTOMER_ADDRESS
2012 	uint8_t j = 0;
2013 	struct patch_info *pent = rtk_hw_cfg.patch_ent;
2014 #endif
2015 #ifdef EXTRA_CONFIG_OPTION
2016 	uint8_t *head = config_buf;
2017 
2018 	add_flags = config_flags;
2019 #endif
2020 
2021 	if (!config || !plen)
2022 		return NULL;
2023 
2024 	RS_INFO("Original Cfg len %u", *plen);
2025 	config_len = le16_to_cpu(config->data_len);
2026 	entry = config->entry;
2027 
2028 	if (le32_to_cpu(config->signature) != RTK_VENDOR_CONFIG_MAGIC) {
2029 		RS_ERR("signature magic number(%x) is incorrect",
2030 		     (unsigned int)config->signature);
2031 		return NULL;
2032 	}
2033 
2034 	if (config_len != *plen - sizeof(struct rtk_bt_vendor_config)) {
2035 		RS_ERR("config len(%d) is incorrect(%zd)", config_len,
2036 		       *plen - sizeof(struct rtk_bt_vendor_config));
2037 		return NULL;
2038 	}
2039 
2040 	for (i = 0; i < config_len;) {
2041 
2042 		switch (le16_to_cpu(entry->offset)) {
2043 #ifdef USE_CUSTOMER_ADDRESS
2044 		case 0x003c:
2045 		case 0x0044:
2046 			if (!customer_bdaddr)
2047 				break;
2048 			if (pent->chip_type > CHIP_BEFORE &&
2049 			    le16_to_cpu(entry->offset) != 0x44)
2050 				break;
2051 			if (pent->chip_type <= CHIP_BEFORE &&
2052 			    le16_to_cpu(entry->offset) != 0x3c)
2053 				break;
2054 			for (j = 0; j < entry->entry_len; j++)
2055 				entry->entry_data[j] = bt_addr[j];
2056 			flags |= CONFIG_BTMAC;
2057 			RS_INFO("BT MAC found %02x:%02x:%02x:%02x:%02x:%02x",
2058 				entry->entry_data[5],
2059 				entry->entry_data[4],
2060 				entry->entry_data[3],
2061 				entry->entry_data[2],
2062 				entry->entry_data[1],
2063 				entry->entry_data[0]);
2064 			break;
2065 #endif
2066 		case 0xc:
2067 			{
2068 #ifdef BAUDRATE_4BYTES
2069 				baudrate =
2070 				    get_unaligned_le32(entry->entry_data);
2071 #else
2072 				baudrate =
2073 				    get_unaligned_le16(entry->entry_data);
2074 #endif
2075 
2076 				if (entry->entry_len >= 12)	//0ffset 0x18 - 0xc
2077 				{
2078 					rtk_hw_cfg.hw_flow_control = (entry->entry_data[12] & 0x4) ? 1 : 0;	//0x18 byte bit2
2079 					//rtk_hw_cfg.hw_flow_control = 0;
2080 				}
2081 				RS_DBG
2082 				    ("config baud rate to :0x%08x, hwflowcontrol:%x, %x",
2083 				     (unsigned int)baudrate,
2084 				     entry->entry_data[12],
2085 				     rtk_hw_cfg.hw_flow_control);
2086 				break;
2087 			}
2088 #ifdef EXTRA_CONFIG_OPTION
2089 		case 0x015b:
2090 			if (!(add_flags & CONFIG_TXPOWER))
2091 				break;
2092 			add_flags &= ~CONFIG_TXPOWER;
2093 			if (txpower_len != entry->entry_len) {
2094 				RS_ERR("invalid tx power cfg len %u, %u",
2095 				       txpower_len, entry->entry_len);
2096 				break;
2097 			}
2098 			memcpy(entry->entry_data, txpower_cfg, txpower_len);
2099 			RS_INFO("Replace Tx power Cfg %02x %02x %02x %02x",
2100 				txpower_cfg[0], txpower_cfg[1], txpower_cfg[2],
2101 				txpower_cfg[3]);
2102 			break;
2103 		case 0x01e6:
2104 			if (!(add_flags & CONFIG_XTAL))
2105 				break;
2106 			add_flags &= ~CONFIG_XTAL;
2107 			RS_INFO("Replace XTAL Cfg 0x%02x", xtal_cfg);
2108 			entry->entry_data[0] = xtal_cfg;
2109 			break;
2110 #endif
2111 		default:
2112 			RS_DBG("cfg offset (%04x),length (%02x)", entry->offset,
2113 			       entry->entry_len);
2114 			break;
2115 		}
2116 		temp = entry->entry_len +
2117 		       sizeof(struct rtk_bt_vendor_config_entry);
2118 		i += temp;
2119 		entry = (struct rtk_bt_vendor_config_entry *)((RT_U8 *)entry +
2120 							      temp);
2121 	}
2122 
2123 #ifdef USE_CUSTOMER_ADDRESS
2124 	if (!(flags & CONFIG_BTMAC) && customer_bdaddr) {
2125 		uint8_t *b;
2126 
2127 		b = config_buf + *plen;
2128 		if (pent->chip_type > CHIP_BEFORE) {
2129 			b[0] = 0x44;
2130 			b[1] = 0x00;
2131 		} else {
2132 			b[0] = 0x3c;
2133 			b[1] = 0x00;
2134 		}
2135 		RS_INFO("add bdaddr sec, offset %02x%02x", b[1], b[0]);
2136 		b[2] = 6;
2137 		for (j = 0; j < 6; j++)
2138 			b[3 + j] = bt_addr[j];
2139 
2140 		*plen += 9;
2141 		config_len += 9;
2142 		temp = *plen - 6;
2143 
2144 		config_buf[4] = (temp & 0xff);
2145 		config_buf[5] = ((temp >> 8) & 0xff);
2146 	}
2147 #endif
2148 
2149 #ifdef EXTRA_CONFIG_OPTION
2150 	temp = *plen;
2151 	if (add_flags & CONFIG_TXPOWER)
2152 		temp += (2 + 1 + txpower_len);
2153 	if ((add_flags & CONFIG_XTAL))
2154 		temp += (2 + 1 + 1);
2155 
2156 	if (add_flags) {
2157 		RS_INFO("Add extra configs");
2158 		config_buf = head;
2159 		temp -= sizeof(struct rtk_bt_vendor_config);
2160 		config_buf[4] = (temp & 0xff);
2161 		config_buf[5] = ((temp >> 8) & 0xff);
2162 		config_buf += *plen;
2163 		if (add_flags & CONFIG_TXPOWER) {
2164 			RS_INFO("Add Tx power Cfg");
2165 			*config_buf++ = 0x5b;
2166 			*config_buf++ = 0x01;
2167 			*config_buf++ = txpower_len;
2168 			memcpy(config_buf, txpower_cfg, txpower_len);
2169 			config_buf += txpower_len;
2170 		}
2171 		if ((add_flags & CONFIG_XTAL)) {
2172 			RS_INFO("Add XTAL Cfg");
2173 			*config_buf++ = 0xe6;
2174 			*config_buf++ = 0x01;
2175 			*config_buf++ = 1;
2176 			*config_buf++ = xtal_cfg;
2177 		}
2178 		*plen = config_buf - head;
2179 		config_buf = head;
2180 	}
2181 #endif
2182 
2183 done:
2184 	*result = baudrate;
2185 	return config_buf;
2186 }
2187 
2188 #ifdef USE_CUSTOMER_ADDRESS
bachk(const char * str)2189 int bachk(const char *str)
2190 {
2191 	if (!str)
2192 		return -1;
2193 
2194 	if (strlen(str) != 17)
2195 		return -1;
2196 
2197 	while (*str) {
2198 		if (!isxdigit(*str++))
2199 			return -1;
2200 
2201 		if (!isxdigit(*str++))
2202 			return -1;
2203 
2204 		if (*str == 0)
2205 			break;
2206 
2207 		if (*str++ != ':')
2208 			return -1;
2209 	}
2210 
2211 	return 0;
2212 }
2213 /**
2214 * get random realtek Bluetooth addr.
2215 *
2216 * @param bt_addr where bt addr is stored
2217 *
2218 */
2219 /* static void rtk_get_ram_addr(char bt_addr[0])
2220  * {
2221  * 	srand(time(NULL) + getpid() + getpid() * 987654 + rand());
2222  *
2223  * 	RT_U32 addr = rand();
2224  * 	memcpy(bt_addr, &addr, sizeof(RT_U8));
2225  * }
2226  */
2227 
2228 /**
2229 * Write the random bt addr to the file /data/misc/bluetoothd/bt_mac/btmac.txt.
2230 *
2231 * @param bt_addr where bt addr is stored
2232 *
2233 */
2234 /* static void rtk_write_btmac2file(char bt_addr[6])
2235  * {
2236  * 	int fd;
2237  * 	fd = open(BT_ADDR_FILE, O_CREAT | O_RDWR | O_TRUNC);
2238  *
2239  * 	if (fd > 0) {
2240  * 		chmod(BT_ADDR_FILE, 0666);
2241  * 		char addr[18] = { 0 };
2242  * 		addr[17] = '\0';
2243  * 		sprintf(addr, "%2x:%2x:%2x:%2x:%2x:%2x", bt_addr[0], bt_addr[1],
2244  * 			bt_addr[2], bt_addr[3], bt_addr[4], bt_addr[5]);
2245  * 		write(fd, addr, strlen(addr));
2246  * 		close(fd);
2247  * 	} else {
2248  * 		RS_ERR("open file error:%s\n", BT_ADDR_FILE);
2249  * 	}
2250  * }
2251  */
2252 #endif
2253 
2254 /**
2255 * Get realtek Bluetooth config file. The bt addr arg is stored in /data/btmac.txt, if there is not this file,
2256 * change to /data/misc/bluetoothd/bt_mac/btmac.txt. If both of them are not found, using
2257 * random bt addr.
2258 *
2259 * @param config_buf point to the content of realtek Bluetooth config file
2260 * @param config_baud_rate the baudrate set in the config file
2261 * @return file_len the length of config file
2262 */
rtk_get_bt_config(struct btrtl_info * btrtl,uint8_t ** config_buf,RT_U32 * config_baud_rate)2263 int rtk_get_bt_config(struct btrtl_info *btrtl, uint8_t **config_buf,
2264 		RT_U32 *config_baud_rate)
2265 {
2266 	char bt_config_file_name[PATH_MAX] = { 0 };
2267 	RT_U8 *bt_addr_temp = NULL;
2268 	uint8_t bt_addr[6] = { 0x00, 0xe0, 0x4c, 0x88, 0x88, 0x88 };
2269 	struct stat st;
2270 	size_t filelen;
2271 	size_t tlength;
2272 	int fd;
2273 	int ret = 0;
2274 	int i = 0;
2275 
2276 #ifdef USE_CUSTOMER_ADDRESS
2277 #define BDADDR_STRING_LEN	17
2278 	size_t size;
2279 	size_t result;
2280 	uint8_t tbuf[BDADDR_STRING_LEN + 1];
2281 	char *str;
2282 
2283 	if (stat(BT_ADDR_FILE, &st) < 0) {
2284 		RS_INFO("Couldnt access customer BT MAC file %s",
2285 		        BT_ADDR_FILE);
2286 
2287 		/* for (i = 0; i < 6; i++)
2288 		 * 	rtk_get_ram_addr(&bt_addr[i]);
2289 		 * rtk_write_btmac2file(bt_addr);
2290 		 */
2291 		goto GET_CONFIG;
2292 	}
2293 
2294 	size = st.st_size;
2295 	/* Only read the first 17-byte if the file length is larger */
2296 	if (size > BDADDR_STRING_LEN)
2297 		size = BDADDR_STRING_LEN;
2298 
2299 	fd = open(BT_ADDR_FILE, O_RDONLY);
2300 	if (fd == -1) {
2301 		RS_ERR("Couldnt open BT MAC file %s, %s", BT_ADDR_FILE,
2302 		       strerror(errno));
2303 	} else {
2304 		memset(tbuf, 0, sizeof(tbuf));
2305 		result = read(fd, tbuf, size);
2306 		close(fd);
2307 		if (result == -1) {
2308 			RS_ERR("Couldnt read BT MAC file %s, err %s",
2309 			       BT_ADDR_FILE, strerror(errno));
2310 			goto GET_CONFIG;
2311 		}
2312 
2313 		if (bachk(tbuf) < 0) {
2314 			goto GET_CONFIG;
2315 		}
2316 
2317 		str = tbuf;
2318 		for (i = 5; i >= 0; i--) {
2319 			bt_addr[i] = (uint8_t)strtoul(str, NULL, 16);
2320 			str += 3;
2321 		}
2322 
2323 		/*reserve LAP addr from 0x9e8b00 to 0x9e8b3f, change to 0x008b** */
2324 		if (0x9e == bt_addr[3] && 0x8b == bt_addr[4]
2325 		    && (bt_addr[5] <= 0x3f)) {
2326 			bt_addr[3] = 0x00;
2327 		}
2328 
2329 		RS_DBG("BT MAC is %02x:%02x:%02x:%02x:%02x:%02x",
2330 		       bt_addr[5], bt_addr[4],
2331 		       bt_addr[3], bt_addr[2],
2332 		       bt_addr[1], bt_addr[0]);
2333 		customer_bdaddr = 1;
2334 	}
2335 #endif
2336 
2337 GET_CONFIG:
2338 	//ret = sprintf(bt_config_file_name, BT_CONFIG_DIRECTORY "rtlbt_config");
2339 	ret = sprintf(bt_config_file_name, "%s", BT_CONFIG_DIRECTORY);
2340 	strcat(bt_config_file_name, btrtl->patch_ent->config_file);
2341 	if (stat(bt_config_file_name, &st) < 0) {
2342 		RS_ERR("can't access bt config file:%s, errno:%d\n",
2343 		       bt_config_file_name, errno);
2344 		return -1;
2345 	}
2346 
2347 	filelen = st.st_size;
2348 
2349 	if ((fd = open(bt_config_file_name, O_RDONLY)) < 0) {
2350 		perror("Can't open bt config file");
2351 		return -1;
2352 	}
2353 
2354 	tlength = filelen;
2355 #ifdef USE_CUSTOMER_ADDRESS
2356 	tlength += 9;
2357 #endif
2358 
2359 #ifdef EXTRA_CONFIG_OPTION
2360 	config_file_proc(EXTRA_CONFIG_FILE);
2361 	if (!xtalset_supported())
2362 		config_flags &= ~CONFIG_XTAL;
2363 	if (config_flags & CONFIG_TXPOWER)
2364 		tlength += 7;
2365 	if (config_flags & CONFIG_XTAL)
2366 		tlength += 4;
2367 #endif
2368 
2369 	if ((*config_buf = malloc(tlength)) == NULL) {
2370 		RS_DBG("Couldnt malloc buffer for config (%zd)\n", tlength);
2371 		close(fd);
2372 		return -1;
2373 	}
2374 	//we may need to parse this config file.
2375 	//for easy debug, only get need data.
2376 
2377 	if (read(fd, *config_buf, filelen) < (ssize_t) filelen) {
2378 		perror("Can't load bt config file");
2379 		free(*config_buf);
2380 		close(fd);
2381 		return -1;
2382 	}
2383 
2384 	*config_buf = rtk_parse_config_file(*config_buf, &filelen, bt_addr,
2385 					    config_baud_rate);
2386 	util_hexdump((const uint8_t *)*config_buf, filelen);
2387 	RS_INFO("Cfg length %u", filelen);
2388 	RS_DBG("Get config baud rate from config file:%x",
2389 	       (unsigned int)*config_baud_rate);
2390 
2391 	close(fd);
2392 	return filelen;
2393 }
2394 
2395 /**
2396 * Realtek change speed with h5 proto. Using vendor specified command packet to achieve this.
2397 *
2398 * @warning it will waiting 2s for reply.
2399 *
2400 * @param fd uart file descriptor
2401 * @param baudrate the speed want to change
2402 *
2403 */
rtk_vendor_change_speed_h5(int fd,RT_U32 baudrate)2404 int rtk_vendor_change_speed_h5(int fd, RT_U32 baudrate)
2405 {
2406 	struct sk_buff *cmd_change_bdrate = NULL;
2407 	unsigned char cmd[7] = { 0 };
2408 	int retlen;
2409 	unsigned char bytes[READ_DATA_SIZE];
2410 	struct sigaction sa;
2411 
2412 	sa.sa_handler = h5_tinit_sig_alarm;
2413 	sigaction(SIGALRM, &sa, NULL);
2414 
2415 	cmd[0] = 0x17;	//ocf
2416 	cmd[1] = 0xfc;	//ogf, vendor specified
2417 
2418 	cmd[2] = 4;	//length;
2419 
2420 	baudrate = cpu_to_le32(baudrate);
2421 #ifdef BAUDRATE_4BYTES
2422 	memcpy((RT_U16 *) & cmd[3], &baudrate, 4);
2423 #else
2424 	memcpy((RT_U16 *) & cmd[3], &baudrate, 2);
2425 
2426 	cmd[5] = 0;
2427 	cmd[6] = 0;
2428 #endif
2429 
2430 	RS_DBG("baudrate in change speed command: 0x%x 0x%x 0x%x 0x%x \n",
2431 	       cmd[3], cmd[4], cmd[5], cmd[6]);
2432 
2433 	cmd_change_bdrate =
2434 	    h5_prepare_pkt(&rtk_hw_cfg, cmd, 7, HCI_COMMAND_PKT);
2435 	if (!cmd_change_bdrate) {
2436 		RS_ERR("Prepare command packet for change speed fail");
2437 		return -1;
2438 	}
2439 
2440 	rtk_hw_cfg.host_last_cmd = cmd_change_bdrate;
2441 	alarm(1);
2442 	write(fd, cmd_change_bdrate->data, cmd_change_bdrate->data_len);
2443 
2444 	while (rtk_hw_cfg.link_estab_state == H5_INIT) {
2445 		if ((retlen = read_check_rtk(fd, &bytes, READ_DATA_SIZE)) == -1) {
2446 			perror("read fail");
2447 			return -1;
2448 		}
2449 		//add pure ack check
2450 		h5_recv(&rtk_hw_cfg, &bytes, retlen);
2451 	}
2452 
2453 	alarm(0);
2454 	return 0;
2455 }
2456 
2457 /**
2458 * Init realtek Bluetooth h5 proto. h5 proto is added by realtek in the right kernel.
2459 * Generally there are two steps: h5 sync and h5 config
2460 *
2461 * @param fd uart file descriptor
2462 * @param ti termios struct
2463 *
2464 */
rtk_init_h5(int fd,struct termios * ti)2465 int rtk_init_h5(int fd, struct termios *ti)
2466 {
2467 	unsigned char bytes[READ_DATA_SIZE];
2468 	struct sigaction sa;
2469 	int retlen;
2470 	struct itimerval value;
2471 
2472 	/* set even parity */
2473 	ti->c_cflag |= PARENB;
2474 	ti->c_cflag &= ~(PARODD);
2475 	if (tcsetattr(fd, TCSANOW, ti) < 0) {
2476 		RS_ERR("Can't set port settings");
2477 		return -1;
2478 	}
2479 
2480 	rtk_hw_cfg.h5_max_retries = H5_MAX_RETRY_COUNT;
2481 
2482 	alarm(0);
2483 	memset(&sa, 0, sizeof(sa));
2484 	sa.sa_flags = SA_NOCLDSTOP;
2485 	sa.sa_handler = h5_tsync_sig_alarm;
2486 	sigaction(SIGALRM, &sa, NULL);
2487 
2488 	/* h5 sync */
2489 	h5_tsync_sig_alarm(0);
2490 	rtk_hw_cfg.link_estab_state = H5_SYNC;
2491 	while (rtk_hw_cfg.link_estab_state == H5_SYNC) {
2492 		if ((retlen = read_check_rtk(fd, &bytes, READ_DATA_SIZE)) == -1) {
2493 			RS_ERR("H5 Read Sync Response Failed");
2494 
2495 			value.it_value.tv_sec = 0;
2496 			value.it_value.tv_usec = 0;
2497 			value.it_interval.tv_sec = 0;
2498 			value.it_interval.tv_usec = 0;
2499 			setitimer(ITIMER_REAL, &value, NULL);
2500 
2501 			return -1;
2502 		}
2503 		h5_recv(&rtk_hw_cfg, &bytes, retlen);
2504 	}
2505 
2506 	value.it_value.tv_sec = 0;
2507 	value.it_value.tv_usec = 0;
2508 	value.it_interval.tv_sec = 0;
2509 	value.it_interval.tv_usec = 0;
2510 	setitimer(ITIMER_REAL, &value, NULL);
2511 
2512 	/* h5 config */
2513 	sa.sa_handler = h5_tconf_sig_alarm;
2514 	sigaction(SIGALRM, &sa, NULL);
2515 	h5_tconf_sig_alarm(0);
2516 	while (rtk_hw_cfg.link_estab_state == H5_CONFIG) {
2517 		if ((retlen = read_check_rtk(fd, &bytes, READ_DATA_SIZE)) == -1) {
2518 			RS_ERR("H5 Read Config Response Failed");
2519 			value.it_value.tv_sec = 0;
2520 			value.it_value.tv_usec = 0;
2521 			value.it_interval.tv_sec = 0;
2522 			value.it_interval.tv_usec = 0;
2523 			setitimer(ITIMER_REAL, &value, NULL);
2524 			return -1;
2525 		}
2526 		h5_recv(&rtk_hw_cfg, &bytes, retlen);
2527 	}
2528 
2529 	value.it_value.tv_sec = 0;
2530 	value.it_value.tv_usec = 0;
2531 	value.it_interval.tv_sec = 0;
2532 	value.it_interval.tv_usec = 0;
2533 	setitimer(ITIMER_REAL, &value, NULL);
2534 
2535 	rtk_send_pure_ack_down(fd);
2536 	RS_DBG("H5 init finished\n");
2537 
2538 	rtk_hw_cfg.rom_version_cmd_state = cmd_not_send;
2539 	rtk_hw_cfg.hci_version_cmd_state = cmd_not_send;
2540 	return 0;
2541 }
2542 
2543 /**
2544 * Download realtek firmware and config file from uart with the proto.
2545 * Parse the content to serval packets follow the proto and then write the packets from uart
2546 *
2547 * @param fd uart file descriptor
2548 * @param buf addr where stor the content of firmware and config file
2549 * @param filesize length of buf
2550 * @param is_sent_changerate if baudrate need to be changed
2551 * @param proto realtek Bluetooth protocol, shall be either HCI_UART_H4 or HCI_UART_3WIRE
2552 *
2553 */
rtk_download_fw_config(int fd,RT_U8 * buf,size_t filesize,int is_sent_changerate,int proto,struct termios * ti)2554 static int rtk_download_fw_config(int fd, RT_U8 * buf, size_t filesize,
2555 				  int is_sent_changerate, int proto,
2556 				  struct termios *ti)
2557 {
2558 	uint8_t iCurIndex = 0;
2559 	uint8_t iCurLen = 0;
2560 	uint8_t iEndIndex = 0;
2561 	uint8_t iLastPacketLen = 0;
2562 	uint8_t iAdditionPkt = 0;
2563 	uint8_t iTotalIndex = 0;
2564 	uint8_t iCmdSentNum = 0;
2565 	unsigned char *bufpatch;
2566 	uint8_t i, j;
2567 
2568 	iEndIndex = (uint8_t) ((filesize - 1) / PATCH_DATA_FIELD_MAX_SIZE);
2569 	iLastPacketLen = (filesize) % PATCH_DATA_FIELD_MAX_SIZE;
2570 
2571 	/* if (is_sent_changerate)
2572 	 * 	iCmdSentNum++;
2573 	 * if (rtk_hw_cfg.rom_version_cmd_state >= cmd_has_sent)
2574 	 * 	iCmdSentNum++;
2575 	 * if (rtk_hw_cfg.hci_version_cmd_state >= cmd_has_sent)
2576 	 * 	iCmdSentNum++; */
2577 	iCmdSentNum += rtk_hw_cfg.num_of_cmd_sent;
2578 
2579 	iAdditionPkt =
2580 	    (iEndIndex + 1 + iCmdSentNum) % 8 ? (8 -
2581 						 (iEndIndex + 1 +
2582 						  iCmdSentNum) % 8) : 0;
2583 	iTotalIndex = iAdditionPkt + iEndIndex;
2584 	rtk_hw_cfg.total_num = iTotalIndex;	//init TotalIndex
2585 
2586 	RS_DBG("iEndIndex:%d  iLastPacketLen:%d iAdditionpkt:%d\n", iEndIndex,
2587 	       iLastPacketLen, iAdditionPkt);
2588 
2589 	if (iLastPacketLen == 0)
2590 		iLastPacketLen = PATCH_DATA_FIELD_MAX_SIZE;
2591 
2592 	bufpatch = buf;
2593 
2594 	for (i = 0; i <= iTotalIndex; i++) {
2595 		/* Index will roll over when it reaches 0x80. */
2596 		if (i > 0x7f)
2597 			j = (i & 0x7f) + 1;
2598 		else
2599 			j = i;
2600 
2601 		if (i < iEndIndex) {
2602 			iCurIndex = j;
2603 			iCurLen = PATCH_DATA_FIELD_MAX_SIZE;
2604 		} else if (i == iEndIndex) {
2605 			/* Send last data packets */
2606 			if (i == iTotalIndex)
2607 				iCurIndex = j | 0x80;
2608 			else
2609 				iCurIndex = j;
2610 			iCurLen = iLastPacketLen;
2611 		} else if (i < iTotalIndex) {
2612 			/* Send additional packets */
2613 			iCurIndex = j;
2614 			bufpatch = NULL;
2615 			iCurLen = 0;
2616 			RS_DBG("Send additional packet %u", iCurIndex);
2617 		} else {
2618 			/* Send end packet */
2619 			iCurIndex = j | 0x80;
2620 			bufpatch = NULL;
2621 			iCurLen = 0;
2622 			RS_DBG("Send end packet %u", iCurIndex);
2623 		}
2624 
2625 		if (iCurIndex & 0x80)
2626 			RS_DBG("Send FW last command");
2627 
2628 		if (proto == HCI_UART_H4) {
2629 			iCurIndex = hci_download_patch_h4(fd, iCurIndex,
2630 							  bufpatch, iCurLen);
2631 			if ((iCurIndex != j) && (i != rtk_hw_cfg.total_num)) {
2632 				RS_DBG(
2633 				  "index mismatch j %d, iCurIndex:%d, fail\n",
2634 				  j, iCurIndex);
2635 				return -1;
2636 			}
2637 		} else if (proto == HCI_UART_3WIRE) {
2638 			if (hci_download_patch(fd, iCurIndex, bufpatch, iCurLen,
2639 					       ti) < 0)
2640 				return -1;
2641 		}
2642 
2643 		if (iCurIndex < iEndIndex) {
2644 			bufpatch += PATCH_DATA_FIELD_MAX_SIZE;
2645 		}
2646 	}
2647 
2648 	/* Set last ack packet down */
2649 	if (proto == HCI_UART_3WIRE) {
2650 		rtk_send_pure_ack_down(fd);
2651 	}
2652 
2653 	return 0;
2654 }
2655 
2656 /**
2657 * Get realtek Bluetooth firmaware file. The content will be saved in *fw_buf which is malloc here.
2658 * The length malloc here will be lager than length of firmware file if there is a config file.
2659 * The content of config file will copy to the tail of *fw_buf in rtk_config.
2660 *
2661 * @param fw_buf point to the addr where stored the content of firmware.
2662 * @param addi_len length of config file.
2663 * @return length of *fw_buf.
2664 *
2665 */
rtk_get_bt_firmware(struct btrtl_info * btrtl,RT_U8 ** fw_buf)2666 int rtk_get_bt_firmware(struct btrtl_info *btrtl, RT_U8 **fw_buf)
2667 {
2668 	const char *filename;
2669 	struct stat st;
2670 	int fd = -1;
2671 	size_t fwsize;
2672 	static char firmware_file_name[PATH_MAX] = { 0 };
2673 	int ret = 0;
2674 
2675 	sprintf(firmware_file_name, "%s", FIRMWARE_DIRECTORY);
2676 	strcat(firmware_file_name, btrtl->patch_ent->patch_file);
2677 	filename = firmware_file_name;
2678 
2679 	if (stat(filename, &st) < 0) {
2680 		RS_ERR("Can't access firmware %s, %s", filename,
2681 		       strerror(errno));
2682 		return -1;
2683 	}
2684 
2685 	fwsize = st.st_size;
2686 
2687 	if ((fd = open(filename, O_RDONLY)) < 0) {
2688 		RS_ERR("Can't open firmware, errno:%d", errno);
2689 		return -1;
2690 	}
2691 
2692 	if (!(*fw_buf = malloc(fwsize))) {
2693 		RS_ERR("Can't alloc memory for fw&config, errno:%d", errno);
2694 		close(fd);
2695 		return -1;
2696 	}
2697 
2698 	if (read(fd, *fw_buf, fwsize) < (ssize_t) fwsize) {
2699 		free(*fw_buf);
2700 		*fw_buf = NULL;
2701 		close(fd);
2702 		return -1;
2703 	}
2704 	RS_DBG("Load FW OK");
2705 	close(fd);
2706 	return fwsize;
2707 }
2708 
2709 //These two function(rtk<-->uart speed transfer) need check Host uart speed at first!!!! IMPORTANT
2710 //add more speed if neccessary
2711 typedef struct _baudrate_ex {
2712 	RT_U32 rtk_speed;
2713 	int uart_speed;
2714 } baudrate_ex;
2715 
2716 #ifdef BAUDRATE_4BYTES
2717 baudrate_ex baudrates[] = {
2718 #ifdef RTL_8703A_SUPPORT
2719 	{0x00004003, 1500000}, /* for rtl8703as */
2720 #endif
2721 	{0x0252C014, 115200},
2722 	{0x0252C00A, 230400},
2723 	{0x05F75004, 921600},
2724 	{0x00005004, 1000000},
2725 	{0x04928002, 1500000},
2726 	{0x01128002, 1500000},	//8761AT
2727 	{0x00005002, 2000000},
2728 	{0x0000B001, 2500000},
2729 	{0x04928001, 3000000},
2730 	{0x052A6001, 3500000},
2731 	{0x00005001, 4000000},
2732 };
2733 #else
2734 baudrate_ex baudrates[] = {
2735 	{0x701d, 115200}
2736 	{0x6004, 921600},
2737 	{0x4003, 1500000},
2738 	{0x5002, 2000000},
2739 	{0x8001, 3000000},
2740 	{0x9001, 3000000},
2741 	{0x7001, 3500000},
2742 	{0x5001, 4000000},
2743 };
2744 #endif
2745 
2746 /**
2747 * Change realtek Bluetooth speed to uart speed. It is matching in the struct baudrates:
2748 *
2749 * @code
2750 * baudrate_ex baudrates[] =
2751 * {
2752 *  	{0x7001, 3500000},
2753 *	{0x6004, 921600},
2754 *	{0x4003, 1500000},
2755 *	{0x5001, 4000000},
2756 *	{0x5002, 2000000},
2757 *	{0x8001, 3000000},
2758 *	{0x701d, 115200}
2759 * };
2760 * @endcode
2761 *
2762 * If there is no match in baudrates, uart speed will be set as #115200.
2763 *
2764 * @param rtk_speed realtek Bluetooth speed
2765 * @param uart_speed uart speed
2766 *
2767 */
rtk_speed_to_uart_speed(RT_U32 rtk_speed,RT_U32 * uart_speed)2768 static void rtk_speed_to_uart_speed(RT_U32 rtk_speed, RT_U32 * uart_speed)
2769 {
2770 	*uart_speed = 115200;
2771 
2772 	unsigned int i;
2773 	for (i = 0; i < sizeof(baudrates) / sizeof(baudrate_ex); i++) {
2774 		if (baudrates[i].rtk_speed == rtk_speed) {
2775 			*uart_speed = baudrates[i].uart_speed;
2776 			return;
2777 		}
2778 	}
2779 	return;
2780 }
2781 
2782 /**
2783 * Change uart speed to realtek Bluetooth speed. It is matching in the struct baudrates:
2784 *
2785 * @code
2786 * baudrate_ex baudrates[] =
2787 * {
2788 *  	{0x7001, 3500000},
2789 *	{0x6004, 921600},
2790 *	{0x4003, 1500000},
2791 *	{0x5001, 4000000},
2792 *	{0x5002, 2000000},
2793 *	{0x8001, 3000000},
2794 *	{0x701d, 115200}
2795 * };
2796 * @endcode
2797 *
2798 * If there is no match in baudrates, realtek Bluetooth speed will be set as #0x701D.
2799 *
2800 * @param uart_speed uart speed
2801 * @param rtk_speed realtek Bluetooth speed
2802 *
2803 */
uart_speed_to_rtk_speed(int uart_speed,RT_U32 * rtk_speed)2804 static inline void uart_speed_to_rtk_speed(int uart_speed, RT_U32 * rtk_speed)
2805 {
2806 	*rtk_speed = 0x701D;
2807 
2808 	unsigned int i;
2809 	for (i = 0; i < sizeof(baudrates) / sizeof(baudrate_ex); i++) {
2810 		if (baudrates[i].uart_speed == uart_speed) {
2811 			*rtk_speed = baudrates[i].rtk_speed;
2812 			return;
2813 		}
2814 	}
2815 
2816 	return;
2817 }
2818 
rtk_get_chip_type_timeout(int sig)2819 static void rtk_get_chip_type_timeout(int sig)
2820 {
2821 	static int retries = 0;
2822 	int len = 0;
2823 	struct btrtl_info *btrtl = &rtk_hw_cfg;
2824 
2825 	RS_INFO("RTK get HCI_VENDOR_READ_RTK_CHIP_TYPE_Command\n");
2826 	if (retries < btrtl->h5_max_retries) {
2827 		RS_DBG("rtk get chip type timerout, retry:%d\n", retries);
2828 		if (btrtl->host_last_cmd) {
2829 			len = write(btrtl->serial_fd,
2830 				    btrtl->host_last_cmd->data,
2831 				    btrtl->host_last_cmd->data_len);
2832 		}
2833 		retries++;
2834 		alarm(3);
2835 		return;
2836 	}
2837 	tcflush(btrtl->serial_fd, TCIOFLUSH);
2838 	RS_ERR("rtk get chip type cmd complete event timed out\n");
2839 	exit(1);
2840 }
2841 
rtk_get_chip_type(int dd)2842 void rtk_get_chip_type(int dd)
2843 {
2844 	unsigned char bytes[READ_DATA_SIZE];
2845 	int retlen;
2846 	struct sigaction sa;
2847 	/* 0xB000A094 */
2848 	unsigned char cmd_buff[] = {0x61, 0xfc,
2849 		0x05, 0x00, 0x94, 0xa0, 0x00, 0xb0};
2850 	struct sk_buff *nskb;
2851 	struct btrtl_info *btrtl = &rtk_hw_cfg;
2852 
2853 	nskb = h5_prepare_pkt(btrtl, cmd_buff, sizeof(cmd_buff),
2854 			HCI_COMMAND_PKT);
2855 	if (btrtl->host_last_cmd){
2856 		skb_free(btrtl->host_last_cmd);
2857 		btrtl->host_last_cmd = NULL;
2858 	}
2859 
2860 	btrtl->host_last_cmd = nskb;
2861 
2862 	write(dd, nskb->data, nskb->data_len);
2863 	RS_INFO("RTK send HCI_VENDOR_READ_CHIP_TYPE_Command\n");
2864 
2865 	alarm(0);
2866 	memset(&sa, 0, sizeof(sa));
2867 	sa.sa_flags = SA_NOCLDSTOP;
2868 	sa.sa_handler = rtk_get_chip_type_timeout;
2869 	sigaction(SIGALRM, &sa, NULL);
2870 
2871 	alarm(3);
2872 	while (btrtl->chip_type_cmd_state != event_received) {
2873 		if ((retlen = read_check_rtk(dd, &bytes, READ_DATA_SIZE)) == -1) {
2874 			perror("rtk get chip type: read fail");
2875 			return;
2876 		}
2877 		h5_recv(btrtl, &bytes, retlen);
2878 	}
2879 	alarm(0);
2880 	return;
2881 }
2882 
rtk_get_eversion_timeout(int sig)2883 static void rtk_get_eversion_timeout(int sig)
2884 {
2885 	static int retries = 0;
2886 	int len = 0;
2887 
2888 	RS_DBG("RTK get HCI_VENDOR_READ_RTK_ROM_VERISION_Command\n");
2889 	if (retries < rtk_hw_cfg.h5_max_retries) {
2890 		RS_DBG("rtk get eversion timerout, retry:%d\n", retries);
2891 		if (rtk_hw_cfg.host_last_cmd) {
2892 			len = write(rtk_hw_cfg.serial_fd,
2893 				    rtk_hw_cfg.host_last_cmd->data,
2894 				    rtk_hw_cfg.host_last_cmd->data_len);
2895 		}
2896 		retries++;
2897 		alarm(3);
2898 		return;
2899 	}
2900 	tcflush(rtk_hw_cfg.serial_fd, TCIOFLUSH);
2901 	RS_ERR("rtk get eversion cmd complete event timed out\n");
2902 	exit(1);
2903 }
2904 
2905 /**
2906 * Send vendor cmd to get eversion: 0xfc6d
2907 * If Rom code does not support this cmd, use default.
2908 */
rtk_get_eversion(int dd)2909 void rtk_get_eversion(int dd)
2910 {
2911 	unsigned char bytes[READ_DATA_SIZE];
2912 	int retlen;
2913 	struct sigaction sa;
2914 	unsigned char read_rom_patch_cmd[3] = { 0x6d, 0xfc, 00 };
2915 	struct sk_buff *nskb =
2916 	    h5_prepare_pkt(&rtk_hw_cfg, read_rom_patch_cmd, 3, HCI_COMMAND_PKT);
2917 
2918 	if (rtk_hw_cfg.host_last_cmd) {
2919 		skb_free(rtk_hw_cfg.host_last_cmd);
2920 		rtk_hw_cfg.host_last_cmd = NULL;
2921 	}
2922 
2923 	rtk_hw_cfg.host_last_cmd = nskb;
2924 
2925 	write(dd, nskb->data, nskb->data_len);
2926 	rtk_hw_cfg.rom_version_cmd_state = cmd_has_sent;
2927 	RS_DBG("RTK send HCI_VENDOR_READ_RTK_ROM_VERISION_Command\n");
2928 
2929 	alarm(0);
2930 	memset(&sa, 0, sizeof(sa));
2931 	sa.sa_flags = SA_NOCLDSTOP;
2932 	sa.sa_handler = rtk_get_eversion_timeout;
2933 	sigaction(SIGALRM, &sa, NULL);
2934 
2935 	alarm(3);
2936 	while (rtk_hw_cfg.rom_version_cmd_state != event_received) {
2937 		if ((retlen = read_check_rtk(dd, &bytes, READ_DATA_SIZE)) == -1) {
2938 			perror("rtk get eversion: read fail");
2939 			return;
2940 		}
2941 		h5_recv(&rtk_hw_cfg, &bytes, retlen);
2942 	}
2943 	alarm(0);
2944 	return;
2945 }
2946 
rtk_get_lmp_version_timeout(int sig)2947 static void rtk_get_lmp_version_timeout(int sig)
2948 {
2949 	static int retries = 0;
2950 	RS_DBG("RTK get HCI_VENDOR_READ_RTK_LMP_VERISION_Command\n");
2951 	if (retries < rtk_hw_cfg.h5_max_retries) {
2952 		RS_DBG("rtk get lmp version timeout, retry: %d\n", retries);
2953 		if (rtk_hw_cfg.host_last_cmd) {
2954 			int len = write(rtk_hw_cfg.serial_fd,
2955 					rtk_hw_cfg.host_last_cmd->data,
2956 					rtk_hw_cfg.host_last_cmd->data_len);
2957 		}
2958 		retries++;
2959 		alarm(3);
2960 		return;
2961 	}
2962 	tcflush(rtk_hw_cfg.serial_fd, TCIOFLUSH);
2963 	RS_ERR("rtk get lmp version cmd complete event timed out\n");
2964 	exit(1);
2965 }
2966 
rtk_get_lmp_version(int dd)2967 void rtk_get_lmp_version(int dd)
2968 {
2969 	unsigned char bytes[READ_DATA_SIZE];
2970 	int retlen;
2971 	struct sigaction sa;
2972 	unsigned char read_rom_patch_cmd[3] = { 0x01, 0x10, 00 };
2973 	struct sk_buff *nskb = h5_prepare_pkt(&rtk_hw_cfg, read_rom_patch_cmd, 3, HCI_COMMAND_PKT);	//data:len+head:4
2974 
2975 	if (rtk_hw_cfg.host_last_cmd) {
2976 		skb_free(rtk_hw_cfg.host_last_cmd);
2977 		rtk_hw_cfg.host_last_cmd = NULL;
2978 	}
2979 
2980 	rtk_hw_cfg.host_last_cmd = nskb;
2981 
2982 	write(dd, nskb->data, nskb->data_len);
2983 	rtk_hw_cfg.hci_version_cmd_state = cmd_has_sent;
2984 	RS_DBG("RTK send HCI_VENDOR_READ_RTK_ROM_VERISION_Command\n");
2985 
2986 	alarm(0);
2987 	memset(&sa, 0, sizeof(sa));
2988 	sa.sa_flags = SA_NOCLDSTOP;
2989 	sa.sa_handler = rtk_get_lmp_version_timeout;
2990 	sigaction(SIGALRM, &sa, NULL);
2991 
2992 	alarm(3);
2993 	while (rtk_hw_cfg.hci_version_cmd_state != event_received) {
2994 		if ((retlen = read_check_rtk(dd, &bytes, READ_DATA_SIZE)) == -1) {
2995 			perror("read fail");
2996 			return;
2997 		}
2998 		h5_recv(&rtk_hw_cfg, &bytes, retlen);
2999 	}
3000 	alarm(0);
3001 	return;
3002 }
3003 
3004 static int rtk_max_retries = 5;
3005 
rtk_local_ver_sig_alarm(int sig)3006 static void rtk_local_ver_sig_alarm(int sig)
3007 {
3008 	uint8_t cmd[4] = { 0x01, 0x01, 0x10, 0x00 };
3009 	static int retries;
3010 
3011 	if (retries < rtk_max_retries) {
3012 		retries++;
3013 		if (write(rtk_hw_cfg.serial_fd, cmd, sizeof(cmd)) < 0)
3014 			return;
3015 		alarm(1);
3016 		return;
3017 	}
3018 
3019 	tcflush(rtk_hw_cfg.serial_fd, TCIOFLUSH);
3020 	RS_ERR("init timed out, read local ver fails");
3021 	exit(1);
3022 }
3023 
rtk_hci_local_ver(int fd)3024 static void rtk_hci_local_ver(int fd)
3025 {
3026 	struct sigaction sa;
3027 	uint8_t result[258];
3028 	int ret;
3029 
3030 	alarm(0);
3031 
3032 	memset(&sa, 0, sizeof(sa));
3033 	sa.sa_flags = SA_NOCLDSTOP;
3034 	sa.sa_handler = rtk_local_ver_sig_alarm;
3035 	sigaction(SIGALRM, &sa, NULL);
3036 
3037 	rtk_local_ver_sig_alarm(0);
3038 
3039 	while (1) {
3040 		ret = read_hci_evt(fd, result, 0x0e);
3041 		/* break down is not needed if read fails, because the program
3042 		 * will exit when alarm timeout
3043 		 */
3044 		if (ret < 0)
3045 			RS_ERR("%s: Read HCI event error.", __func__);
3046 		else
3047 			break;
3048 	}
3049 
3050 	/* Cancel pending alarm */
3051 	alarm(0);
3052 
3053 	if (ret != 15) {
3054 		RS_ERR("%s: incorrect complete event, len %u", __func__, ret);
3055 		exit(1);
3056 	}
3057 
3058 	if (result[6]) {
3059 		RS_ERR("%s: status is %u", __func__, result[6]);
3060 		exit(1);
3061 	}
3062 
3063 	rtk_hw_cfg.hci_rev = (uint32_t)result[9] << 8 | result[8];
3064 	rtk_hw_cfg.lmp_subver = (uint32_t)result[14] << 8 | result[13];
3065 }
3066 
rtk_rom_ver_sig_alarm(int sig)3067 static void rtk_rom_ver_sig_alarm(int sig)
3068 {
3069 	uint8_t cmd[4] = { 0x01, 0x6d, 0xfc, 0x00 };
3070 	static int retries;
3071 
3072 	if (retries < rtk_max_retries) {
3073 		retries++;
3074 		if (write(rtk_hw_cfg.serial_fd, cmd, sizeof(cmd)) < 0)
3075 			return;
3076 		alarm(1);
3077 		return;
3078 	}
3079 
3080 	tcflush(rtk_hw_cfg.serial_fd, TCIOFLUSH);
3081 	RS_ERR("init timed out, read rom ver fails");
3082 	exit(1);
3083 }
3084 
rtk_hci_rom_ver(int fd)3085 static void rtk_hci_rom_ver(int fd)
3086 {
3087 	struct sigaction sa;
3088 	uint8_t result[256];
3089 	int ret;
3090 
3091 	alarm(0);
3092 
3093 	memset(&sa, 0, sizeof(sa));
3094 	sa.sa_flags = SA_NOCLDSTOP;
3095 	sa.sa_handler = rtk_rom_ver_sig_alarm;
3096 	sigaction(SIGALRM, &sa, NULL);
3097 
3098 	rtk_rom_ver_sig_alarm(0);
3099 
3100 	while (1) {
3101 		ret = read_hci_evt(fd, result, 0x0e);
3102 		/* break down is not needed if read fails, because the program
3103 		 * will exit when alarm timeout
3104 		 */
3105 		if (ret < 0)
3106 			RS_ERR("%s: Read HCI event error.", __func__);
3107 		else
3108 			break;
3109 	}
3110 
3111 	/* Cancel pending alarm */
3112 	alarm(0);
3113 
3114 	if (ret != 8) {
3115 		RS_ERR("%s: incorrect complete event, len %u", __func__, ret);
3116 		exit(1);
3117 	}
3118 
3119 	if (result[6]) {
3120 		RS_ERR("%s: status is %u", __func__, result[6]);
3121 		rtk_hw_cfg.eversion = 0;
3122 	} else
3123 		rtk_hw_cfg.eversion = result[7];
3124 }
3125 
rtk_get_fw_project_id(uint8_t * p_buf)3126 uint8_t rtk_get_fw_project_id(uint8_t * p_buf)
3127 {
3128 	uint8_t opcode;
3129 	uint8_t len;
3130 	uint8_t data = 0;
3131 
3132 	do {
3133 		opcode = *p_buf;
3134 		len = *(p_buf - 1);
3135 		if (opcode == 0x00) {
3136 			if (len == 1) {
3137 				data = *(p_buf - 2);
3138 				RS_DBG
3139 				    ("rtk_get_fw_project_id: opcode %d, len %d, data %d",
3140 				     opcode, len, data);
3141 				break;
3142 			} else {
3143 				RS_ERR("rtk_get_fw_project_id: invalid len %d",
3144 				       len);
3145 			}
3146 		}
3147 		p_buf -= len + 2;
3148 	} while (*p_buf != 0xFF);
3149 
3150 	return data;
3151 }
3152 
rtk_get_patch_entry(void)3153 struct rtk_epatch_entry *rtk_get_patch_entry(void)
3154 {
3155 	uint16_t i;
3156 	struct rtk_epatch *patch;
3157 	struct rtk_epatch_entry *entry;
3158 	uint8_t *p;
3159 	uint16_t chip_id;
3160 	uint32_t tmp;
3161 
3162 	patch = (struct rtk_epatch *)rtk_hw_cfg.fw_buf;
3163 	entry = (struct rtk_epatch_entry *)malloc(sizeof(*entry));
3164 	if (!entry) {
3165 		RS_ERR("failed to allocate mem for patch entry");
3166 		return NULL;
3167 	}
3168 
3169 	patch->number_of_patch = le16_to_cpu(patch->number_of_patch);
3170 
3171 	RS_DBG("fw_ver 0x%08x, patch_num %d",
3172 	       le32_to_cpu(patch->fw_version), patch->number_of_patch);
3173 
3174 	for (i = 0; i < patch->number_of_patch; i++) {
3175 		RS_DBG("chip id 0x%04x",
3176 			get_unaligned_le16(rtk_hw_cfg.fw_buf + 14 + 2 * i));
3177 		if (get_unaligned_le16(rtk_hw_cfg.fw_buf + 14 + 2 * i) ==
3178 		    rtk_hw_cfg.eversion + 1) {
3179 			entry->chipID = rtk_hw_cfg.eversion + 1;
3180 			entry->patch_length =
3181 			    get_unaligned_le16(rtk_hw_cfg.fw_buf + 14 +
3182 					       2 * patch->number_of_patch +
3183 					       2 * i);
3184 			entry->start_offset =
3185 			    get_unaligned_le32(rtk_hw_cfg.fw_buf + 14 +
3186 					       4 * patch->number_of_patch +
3187 					       4 * i);
3188 			RS_DBG("patch length is 0x%x", entry->patch_length);
3189 			RS_DBG("start offset is 0x%x", entry->start_offset);
3190 
3191 			entry->svn_ver = get_unaligned_le32(rtk_hw_cfg.fw_buf +
3192 						entry->start_offset +
3193 						entry->patch_length - 8);
3194 			entry->coex_ver = get_unaligned_le32(rtk_hw_cfg.fw_buf +
3195 						entry->start_offset +
3196 						entry->patch_length - 12);
3197 
3198 			RS_INFO("Svn version: %8d\n", entry->svn_ver);
3199 			tmp = ((entry->coex_ver >> 16) & 0x7ff) +
3200 			      (entry->coex_ver >> 27) * 10000;
3201 			RS_INFO("Coexistence: BTCOEX_20%06d-%04x\n", tmp,
3202 				(entry->coex_ver & 0xffff));
3203 
3204 			break;
3205 		}
3206 
3207 	}
3208 
3209 	if (i == patch->number_of_patch) {
3210 		RS_ERR("failed to get entry");
3211 		free(entry);
3212 		entry = NULL;
3213 	}
3214 
3215 	return entry;
3216 }
3217 
rtk_get_final_patch(int fd,int proto)3218 void rtk_get_final_patch(int fd, int proto)
3219 {
3220 	struct btrtl_info *rtl = &rtk_hw_cfg;
3221 	uint8_t proj_id = 0;
3222 	struct rtk_epatch_entry *entry = NULL;
3223 	struct rtk_epatch *patch = (struct rtk_epatch *)rtl->fw_buf;
3224 	uint32_t svn_ver, coex_ver, tmp;
3225 
3226 	if ((proto == HCI_UART_H4) ||
3227 	    ((proto == HCI_UART_3WIRE) && (rtl->lmp_subver == ROM_LMP_8723a))) {
3228 		if (memcmp(rtl->fw_buf, RTK_EPATCH_SIGNATURE, 8) == 0) {
3229 			RS_ERR("Check signature error!");
3230 			rtl->dl_fw_flag = 0;
3231 			goto free_buf;
3232 		} else {
3233 			rtl->total_len = rtl->config_len + rtl->fw_len;
3234 			if (!(rtl->total_buf = malloc(rtl->total_len))) {
3235 				RS_ERR("Can't alloc mem for fw/config, errno:%d",
3236 				       errno);
3237 				rtl->dl_fw_flag = 0;
3238 				rtl->total_len = 0;
3239 				goto free_buf;
3240 			} else {
3241 				RS_DBG("fw copy directy");
3242 
3243 				svn_ver = get_unaligned_le32(
3244 						rtl->fw_buf + rtl->fw_len - 8);
3245 				coex_ver = get_unaligned_le32(
3246 						rtl->fw_buf + rtl->fw_len - 12);
3247 
3248 				RS_INFO("Svn version: %8d\n", svn_ver);
3249 				tmp = ((coex_ver >> 16) & 0x7ff) +
3250 					(coex_ver >> 27) * 10000;
3251 				RS_INFO("Coexistence: BTCOEX_20%06d-%04x\n", tmp,
3252 						(coex_ver & 0xffff));
3253 
3254 				memcpy(rtl->total_buf, rtl->fw_buf,
3255 				       rtl->fw_len);
3256 				if (rtl->config_len)
3257 					memcpy(rtl->total_buf +
3258 					       rtl->fw_len,
3259 					       rtl->config_buf,
3260 					       rtl->config_len);
3261 				rtl->dl_fw_flag = 1;
3262 				goto free_buf;
3263 			}
3264 		}
3265 	}
3266 
3267 	if (memcmp(rtl->fw_buf, RTK_EPATCH_SIGNATURE, 8)) {
3268 		RS_DBG("check signature error!");
3269 		rtl->dl_fw_flag = 0;
3270 		goto free_buf;
3271 	}
3272 
3273 	if (memcmp
3274 	    (rtl->fw_buf + rtl->fw_len - 4,
3275 	     Extension_Section_SIGNATURE, 4)) {
3276 		RS_ERR("check extension section signature error");
3277 		rtl->dl_fw_flag = 0;
3278 		goto free_buf;
3279 	}
3280 
3281 	proj_id = rtk_get_fw_project_id(rtl->fw_buf + rtl->fw_len - 5);
3282 
3283 #ifdef RTL_8703A_SUPPORT
3284 	if (rtl->hci_ver == 0x4 && rtl->lmp_subver == ROM_LMP_8723b) {
3285 		RS_DBG("HCI version = 0x4, IC is 8703A.");
3286 	} else {
3287 		RS_ERR("error: lmp_version %x, hci_version %x, project_id %x",
3288 		       rtl->lmp_subver, rtl->hci_ver, project_id[proj_id]);
3289 		rtk_hw_cfg.dl_fw_flag = 0;
3290 		goto free_buf;
3291 	}
3292 #else
3293 	if (rtl->lmp_subver != ROM_LMP_8703b) {
3294 		if (rtl->lmp_subver != project_id[proj_id]) {
3295 			RS_ERR("lmp_subver %04x, project id %04x, mismatch\n",
3296 			       rtl->lmp_subver, project_id[proj_id]);
3297 			rtl->dl_fw_flag = 0;
3298 			goto free_buf;
3299 		}
3300 	} else {
3301 		/* if (rtk_hw_cfg.patch_ent->proj_id != project_id[proj_id]) {
3302 		 * 	RS_ERR("proj_id %04x, version %04x from firmware "
3303 		 * 	       "project_id[%u], mismatch\n",
3304 		 * 	       rtk_hw_cfg.patch_ent->proj_id,
3305 		 * 	       project_id[proj_id], proj_id);
3306 		 * 	rtk_hw_cfg.dl_fw_flag = 0;
3307 		 * 	goto free_buf;
3308 		 * } */
3309 	}
3310 #endif
3311 
3312 	entry = rtk_get_patch_entry();
3313 
3314 	if (entry)
3315 		rtl->total_len =
3316 		    entry->patch_length + rtl->config_len;
3317 	else {
3318 		rtl->dl_fw_flag = 0;
3319 		goto free_buf;
3320 	}
3321 
3322 	if (!(rtl->total_buf = malloc(rtl->total_len))) {
3323 		RS_ERR("Can't alloc memory for multi fw&config, errno:%d",
3324 		       errno);
3325 		rtl->dl_fw_flag = 0;
3326 		rtl->total_len = 0;
3327 		goto free_buf;
3328 	} else {
3329 		memcpy(rtl->total_buf,
3330 		       rtl->fw_buf + entry->start_offset,
3331 		       entry->patch_length);
3332 		memcpy(rtl->total_buf + entry->patch_length - 4,
3333 		       &patch->fw_version, 4);
3334 
3335 		if (rtl->config_len)
3336 			memcpy(rtl->total_buf + entry->patch_length,
3337 			       rtl->config_buf, rtl->config_len);
3338 		rtl->dl_fw_flag = 1;
3339 	}
3340 
3341 	RS_DBG("fw:%s exists, config file:%s exists",
3342 	       (rtl->fw_len > 0) ? "" : "not",
3343 	       (rtl->config_len > 0) ? "" : "not");
3344 
3345 free_buf:
3346 	if (rtl->fw_len > 0) {
3347 		free(rtl->fw_buf);
3348 		rtl->fw_len = 0;
3349 	}
3350 
3351 	if (rtl->config_len > 0) {
3352 		free(rtl->config_buf);
3353 		rtl->config_len = 0;
3354 	}
3355 
3356 	if (entry)
3357 		free(entry);
3358 }
3359 
3360 /**
3361 * Config realtek Bluetooth. The configuration parameter is get from config file and fw.
3362 * Config file is rtk8723_bt_config. which is set in rtk_get_bt_config.
3363 * fw file is "rlt8723a_chip_b_cut_bt40_fw", which is set in get_firmware_name.
3364 *
3365 * @warning maybe only one of config file and fw file exists. The bt_addr arg is stored in "/data/btmac.txt"
3366 * or "/data/misc/bluetoothd/bt_mac/btmac.txt",
3367 *
3368 * @param fd uart file descriptor
3369 * @param proto realtek Bluetooth protocol, shall be either HCI_UART_H4 or HCI_UART_3WIRE
3370 * @param speed init_speed in uart struct
3371 * @param ti termios struct
3372 * @returns #0 on success
3373 */
rtk_config(int fd,int proto,int speed,struct termios * ti)3374 static int rtk_config(int fd, int proto, int speed, struct termios *ti)
3375 {
3376 	int final_speed = 0;
3377 	int ret = 0;
3378 	struct btrtl_info *btrtl = &rtk_hw_cfg;
3379 
3380 	btrtl->proto = proto;
3381 
3382 	/* Get Local Version Information and RTK ROM version */
3383 	if (proto == HCI_UART_3WIRE) {
3384 		RS_INFO("H5 IC");
3385 		rtk_get_lmp_version(fd);
3386 		rtk_get_eversion(fd);
3387 	} else {
3388 		RS_INFO("H4 IC");
3389 		rtk_hci_local_ver(fd);
3390 		rtk_hci_rom_ver(fd);
3391 		if (rtk_hw_cfg.lmp_subver == ROM_LMP_8761btc) {
3392 			rtk_hw_cfg.chip_type = CHIP_8761BTC;
3393 			rtk_hw_cfg.hw_flow_control = 1;
3394 			/* TODO: Change to different uart baud */
3395 			uart_speed_to_rtk_speed(1500000, &rtk_hw_cfg.baudrate);
3396 			goto change_baud;
3397 		}
3398 
3399 		if (rtk_hw_cfg.lmp_subver == ROM_LMP_8761a) {
3400 			if (rtk_hw_cfg.hci_rev == 0x000b) {
3401 				rtk_hw_cfg.chip_type = CHIP_8761B;
3402 				rtk_hw_cfg.hw_flow_control = 1;
3403 				/* TODO: Change to different uart baud */
3404 				uart_speed_to_rtk_speed(1500000, &rtk_hw_cfg.baudrate);
3405 				goto change_baud;
3406 			} else if (rtk_hw_cfg.hci_rev == 0x000a) {
3407 				if (rtk_hw_cfg.eversion == 3)
3408 					rtk_hw_cfg.chip_type = CHIP_8761ATF;
3409 				else if (rtk_hw_cfg.eversion == 2)
3410 					rtk_hw_cfg.chip_type = CHIP_8761AT;
3411 				else
3412 					rtk_hw_cfg.chip_type = CHIP_UNKNOWN;
3413 			}
3414 		}
3415 	}
3416 
3417 	RS_INFO("LMP Subversion 0x%04x", btrtl->lmp_subver);
3418 	RS_INFO("EVersion %d", btrtl->eversion);
3419 
3420 	switch (rtk_hw_cfg.lmp_subver) {
3421 	case ROM_LMP_8723a:
3422 		break;
3423 	case ROM_LMP_8723b:
3424 #ifdef RTL_8703A_SUPPORT
3425 		/* Set chip type for matching fw/config entry */
3426 		rtl->chip_type = CHIP_8703AS;
3427 #endif
3428 		break;
3429 	case ROM_LMP_8821a:
3430 		break;
3431 	case ROM_LMP_8761a:
3432 		break;
3433 	case ROM_LMP_8703b:
3434 		rtk_get_chip_type(fd);
3435 		break;
3436 	}
3437 
3438 	btrtl->patch_ent = get_patch_entry(btrtl);
3439 	if (btrtl->patch_ent) {
3440 		RS_INFO("IC: %s\n", btrtl->patch_ent->ic_name);
3441 		RS_INFO("Firmware/config: %s, %s\n",
3442 			btrtl->patch_ent->patch_file,
3443 			btrtl->patch_ent->config_file);
3444 	} else {
3445 		RS_ERR("Can not find firmware/config entry\n");
3446 		return -1;
3447 	}
3448 
3449 	rtk_hw_cfg.config_len =
3450 	    rtk_get_bt_config(btrtl, &btrtl->config_buf, &btrtl->baudrate);
3451 	if (rtk_hw_cfg.config_len < 0) {
3452 		RS_ERR("Get Config file error, just use efuse settings");
3453 		rtk_hw_cfg.config_len = 0;
3454 	}
3455 
3456 	rtk_hw_cfg.fw_len = rtk_get_bt_firmware(btrtl, &btrtl->fw_buf);
3457 	if (rtk_hw_cfg.fw_len < 0) {
3458 		RS_ERR("Get BT firmware error");
3459 		rtk_hw_cfg.fw_len = 0;
3460 		return -1;
3461 	} else {
3462 		rtk_get_final_patch(fd, proto);
3463 	}
3464 
3465 	if (rtk_hw_cfg.total_len > RTK_PATCH_LENGTH_MAX) {
3466 		RS_ERR("total length of fw&config larger than allowed");
3467 		return -1;
3468 	}
3469 
3470 	RS_INFO("Total len %d for fw/config", rtk_hw_cfg.total_len);
3471 
3472 change_baud:
3473 	/* change baudrate if needed
3474 	 * rtk_hw_cfg.baudrate is a __u32/__u16 vendor-specific variable
3475 	 * parsed from config file
3476 	 * */
3477 	if (rtk_hw_cfg.baudrate == 0) {
3478 		uart_speed_to_rtk_speed(speed, &rtk_hw_cfg.baudrate);
3479 		RS_DBG("No cfg file, set baudrate, : %u, 0x%08x",
3480 		       (unsigned int)speed, (unsigned int)rtk_hw_cfg.baudrate);
3481 		goto SET_FLOW_CONTRL;
3482 	} else
3483 		rtk_speed_to_uart_speed(rtk_hw_cfg.baudrate,
3484 					(RT_U32 *) & (rtk_hw_cfg.final_speed));
3485 
3486 	if (proto == HCI_UART_3WIRE)
3487 		rtk_vendor_change_speed_h5(fd, rtk_hw_cfg.baudrate);
3488 	else
3489 		rtk_vendor_change_speed_h4(fd, rtk_hw_cfg.baudrate);
3490 
3491 	usleep(50000);
3492 	final_speed = rtk_hw_cfg.final_speed ? rtk_hw_cfg.final_speed : speed;
3493 	RS_DBG("final_speed %d\n", final_speed);
3494 	if (set_speed(fd, ti, final_speed) < 0) {
3495 		RS_ERR("Can't set baud rate:%x, %x, %x", final_speed,
3496 		       rtk_hw_cfg.final_speed, speed);
3497 		return -1;
3498 	}
3499 
3500 SET_FLOW_CONTRL:
3501 	if (rtk_hw_cfg.hw_flow_control) {
3502 		RS_DBG("hw flow control enable");
3503 		ti->c_cflag |= CRTSCTS;
3504 
3505 		if (tcsetattr(fd, TCSANOW, ti) < 0) {
3506 			RS_ERR("Can't set port settings");
3507 			return -1;
3508 		}
3509 	} else {
3510 		RS_DBG("hw flow control disable");
3511 		ti->c_cflag &= ~CRTSCTS;
3512 	}
3513 
3514 	/* wait for while for controller to setup */
3515 	usleep(10000);
3516 
3517 	/* For 8761B Test chip, no patch to download */
3518 	if (rtk_hw_cfg.chip_type == CHIP_8761BTC ||
3519 	    rtk_hw_cfg.chip_type == CHIP_8761B)
3520 		goto done;
3521 
3522 	if ((rtk_hw_cfg.total_len > 0) && (rtk_hw_cfg.dl_fw_flag)) {
3523 		rtk_hw_cfg.link_estab_state = H5_PATCH;
3524 		rtk_hw_cfg.rx_index = -1;
3525 
3526 		ret =
3527 		    rtk_download_fw_config(fd, rtk_hw_cfg.total_buf,
3528 					   rtk_hw_cfg.total_len,
3529 					   rtk_hw_cfg.baudrate, proto, ti);
3530 		free(rtk_hw_cfg.total_buf);
3531 
3532 		if (ret < 0)
3533 			return ret;
3534 	}
3535 
3536 done:
3537 	RS_DBG("Init Process finished");
3538 	return 0;
3539 }
3540 
3541 /**
3542 * Init uart by realtek Bluetooth.
3543 *
3544 * @param fd uart file descriptor
3545 * @param proto realtek Bluetooth protocol, shall be either HCI_UART_H4 or HCI_UART_3WIRE
3546 * @param speed init_speed in uart struct
3547 * @param ti termios struct
3548 * @returns #0 on success, depend on rtk_config
3549 */
rtk_init(int fd,int proto,int speed,struct termios * ti)3550 int rtk_init(int fd, int proto, int speed, struct termios *ti)
3551 {
3552 	struct sigaction sa;
3553 	int retlen;
3554 	RS_DBG("Realtek hciattach version %s \n", RTK_VERSION);
3555 
3556 	memset(&rtk_hw_cfg, 0, sizeof(rtk_hw_cfg));
3557 	rtk_hw_cfg.serial_fd = fd;
3558 	rtk_hw_cfg.dl_fw_flag = 1;
3559 
3560 	/* h4 will do nothing for init */
3561 	if (proto == HCI_UART_3WIRE) {
3562 		if (rtk_init_h5(fd, ti) < 0)
3563 			return -1;;
3564 	}
3565 
3566 	return rtk_config(fd, proto, speed, ti);
3567 }
3568 
3569 /**
3570 * Post uart by realtek Bluetooth. If gFinalSpeed is set, set uart speed with it.
3571 *
3572 * @param fd uart file descriptor
3573 * @param proto realtek Bluetooth protocol, shall be either HCI_UART_H4 or HCI_UART_3WIRE
3574 * @param ti termios struct
3575 * @returns #0 on success.
3576 */
rtk_post(int fd,int proto,struct termios * ti)3577 int rtk_post(int fd, int proto, struct termios *ti)
3578 {
3579 	if (rtk_hw_cfg.final_speed)
3580 		return set_speed(fd, ti, rtk_hw_cfg.final_speed);
3581 
3582 	return 0;
3583 }
3584