bt.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stddef.h>
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include "esp_random.h"
  11. #include "esp_heap_caps.h"
  12. #include "esp_heap_caps_init.h"
  13. #include <esp_mac.h>
  14. #include "sdkconfig.h"
  15. #include "nimble/nimble_port.h"
  16. #include "nimble/nimble_port_freertos.h"
  17. #ifdef ESP_PLATFORM
  18. #include "esp_log.h"
  19. #endif
  20. #if CONFIG_SW_COEXIST_ENABLE
  21. #include "private/esp_coexist_internal.h"
  22. #endif
  23. #include "nimble/nimble_npl_os.h"
  24. #include "nimble/ble_hci_trans.h"
  25. #include "os/endian.h"
  26. #include "esp_bt.h"
  27. #include "esp_intr_alloc.h"
  28. #include "esp_sleep.h"
  29. #include "esp_pm.h"
  30. #include "esp_phy_init.h"
  31. #include "soc/syscon_reg.h"
  32. #include "soc/modem_clkrst_reg.h"
  33. #include "esp_private/periph_ctrl.h"
  34. #include "hci_uart.h"
  35. #include "bt_osi_mem.h"
  36. #ifdef CONFIG_BT_BLUEDROID_ENABLED
  37. #include "hci/hci_hal.h"
  38. #endif
  39. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  40. #include "esp_private/sleep_modem.h"
  41. #endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
  42. #include "freertos/FreeRTOS.h"
  43. #include "freertos/task.h"
  44. #include "esp_private/periph_ctrl.h"
  45. #include "esp_sleep.h"
  46. #include "soc/syscon_reg.h"
  47. #include "soc/dport_access.h"
  48. #include "hal/efuse_ll.h"
  49. /* Macro definition
  50. ************************************************************************
  51. */
  52. #define NIMBLE_PORT_LOG_TAG "BLE_INIT"
  53. #define OSI_COEX_VERSION 0x00010006
  54. #define OSI_COEX_MAGIC_VALUE 0xFADEBEAD
  55. #define EXT_FUNC_VERSION 0x20221122
  56. #define EXT_FUNC_MAGIC_VALUE 0xA5A5A5A5
  57. #define BT_ASSERT_PRINT ets_printf
  58. #ifdef CONFIG_BT_BLUEDROID_ENABLED
  59. /* ACL_DATA_MBUF_LEADINGSPCAE: The leadingspace in user info header for ACL data */
  60. #define ACL_DATA_MBUF_LEADINGSPCAE 4
  61. #endif // CONFIG_BT_BLUEDROID_ENABLED
  62. /* Types definition
  63. ************************************************************************
  64. */
  65. struct osi_coex_funcs_t {
  66. uint32_t _magic;
  67. uint32_t _version;
  68. void (* _coex_wifi_sleep_set)(bool sleep);
  69. int (* _coex_core_ble_conn_dyn_prio_get)(bool *low, bool *high);
  70. void (* _coex_schm_status_bit_set)(uint32_t type, uint32_t status);
  71. void (* _coex_schm_status_bit_clear)(uint32_t type, uint32_t status);
  72. };
  73. struct ext_funcs_t {
  74. uint32_t ext_version;
  75. int (*_esp_intr_alloc)(int source, int flags, intr_handler_t handler, void *arg, void **ret_handle);
  76. int (*_esp_intr_free)(void **ret_handle);
  77. void *(* _malloc)(size_t size);
  78. void (*_free)(void *p);
  79. void (*_hal_uart_start_tx)(int);
  80. int (*_hal_uart_init_cbs)(int, hci_uart_tx_char, hci_uart_tx_done, hci_uart_rx_char, void *);
  81. int (*_hal_uart_config)(int, int32_t, uint8_t, uint8_t, uart_parity_t, uart_hw_flowcontrol_t);
  82. int (*_hal_uart_close)(int);
  83. void (*_hal_uart_blocking_tx)(int, uint8_t);
  84. int (*_hal_uart_init)(int, void *);
  85. int (* _task_create)(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle, uint32_t core_id);
  86. void (* _task_delete)(void *task_handle);
  87. void (*_osi_assert)(const uint32_t ln, const char *fn, uint32_t param1, uint32_t param2);
  88. uint32_t (* _os_random)(void);
  89. int (* _ecc_gen_key_pair)(uint8_t *public, uint8_t *priv);
  90. int (* _ecc_gen_dh_key)(const uint8_t *remote_pub_key_x, const uint8_t *remote_pub_key_y, const uint8_t *local_priv_key, uint8_t *dhkey);
  91. void (* _esp_reset_rpa_moudle)(void);
  92. void (* _esp_bt_track_pll_cap)(void);
  93. uint32_t magic;
  94. };
  95. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  96. typedef void (*interface_func_t) (uint32_t len, const uint8_t*addr, bool end);
  97. #endif // CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  98. /* External functions or variables
  99. ************************************************************************
  100. */
  101. extern int ble_osi_coex_funcs_register(struct osi_coex_funcs_t *coex_funcs);
  102. extern int ble_controller_init(esp_bt_controller_config_t *cfg);
  103. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  104. extern int ble_log_init_async(interface_func_t bt_controller_log_interface, bool task_create, uint8_t buffers, uint32_t *bufs_size);
  105. extern int ble_log_deinit_async(void);
  106. extern void ble_log_async_output_dump_all(bool output);
  107. #endif // CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  108. extern int ble_controller_deinit(void);
  109. extern int ble_controller_enable(uint8_t mode);
  110. extern int ble_controller_disable(void);
  111. extern int esp_register_ext_funcs (struct ext_funcs_t *);
  112. extern void esp_unregister_ext_funcs (void);
  113. extern int esp_ble_ll_set_public_addr(const uint8_t *addr);
  114. extern int esp_register_npl_funcs (struct npl_funcs_t *p_npl_func);
  115. extern void esp_unregister_npl_funcs (void);
  116. extern void npl_freertos_mempool_deinit(void);
  117. extern void bt_bb_v2_init_cmplx(uint8_t i);
  118. extern int os_msys_buf_alloc(void);
  119. extern uint32_t r_os_cputime_get32(void);
  120. extern uint32_t r_os_cputime_ticks_to_usecs(uint32_t ticks);
  121. extern void r_ble_lll_rfmgmt_set_sleep_cb(void *s_cb, void *w_cb, void *s_arg, void *w_arg, uint32_t us_to_enabled);
  122. extern void r_ble_rtc_wake_up_state_clr(void);
  123. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  124. extern void esp_ble_set_wakeup_overhead(uint32_t overhead);
  125. #endif /* CONFIG_FREERTOS_USE_TICKLESS_IDLE */
  126. extern int os_msys_init(void);
  127. extern void os_msys_buf_free(void);
  128. extern int ble_sm_alg_gen_dhkey(const uint8_t *peer_pub_key_x,
  129. const uint8_t *peer_pub_key_y,
  130. const uint8_t *our_priv_key, uint8_t *out_dhkey);
  131. extern int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv);
  132. extern int ble_txpwr_set(esp_ble_enhanced_power_type_t power_type, uint16_t handle, int power_level);
  133. extern int ble_txpwr_get(esp_ble_enhanced_power_type_t power_type, uint16_t handle);
  134. extern int ble_get_npl_element_info(esp_bt_controller_config_t *cfg, ble_npl_count_info_t * npl_info);
  135. extern void bt_track_pll_cap(void);
  136. #if CONFIG_BT_RELEASE_IRAM
  137. extern uint32_t _iram_bt_text_start;
  138. extern uint32_t _bss_bt_end;
  139. #else
  140. extern uint32_t _bt_bss_end;
  141. extern uint32_t _bt_controller_data_start;
  142. #endif
  143. /* Local Function Declaration
  144. *********************************************************************
  145. */
  146. static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status);
  147. static void coex_schm_status_bit_clear_wrapper(uint32_t type, uint32_t status);
  148. static int task_create_wrapper(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle, uint32_t core_id);
  149. static void task_delete_wrapper(void *task_handle);
  150. #if CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  151. static void hci_uart_start_tx_wrapper(int uart_no);
  152. static int hci_uart_init_cbs_wrapper(int uart_no, hci_uart_tx_char tx_func,
  153. hci_uart_tx_done tx_done, hci_uart_rx_char rx_func, void *arg);
  154. static int hci_uart_config_wrapper(int uart_no, int32_t speed, uint8_t databits, uint8_t stopbits,
  155. uart_parity_t parity, uart_hw_flowcontrol_t flow_ctl);
  156. static int hci_uart_close_wrapper(int uart_no);
  157. static void hci_uart_blocking_tx_wrapper(int port, uint8_t data);
  158. static int hci_uart_init_wrapper(int uart_no, void *cfg);
  159. #endif // CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  160. static int esp_intr_alloc_wrapper(int source, int flags, intr_handler_t handler,
  161. void *arg, void **ret_handle_in);
  162. static int esp_intr_free_wrapper(void **ret_handle);
  163. static void osi_assert_wrapper(const uint32_t ln, const char *fn, uint32_t param1, uint32_t param2);
  164. static uint32_t osi_random_wrapper(void);
  165. static void esp_reset_rpa_moudle(void);
  166. static int esp_ecc_gen_key_pair(uint8_t *pub, uint8_t *priv);
  167. static int esp_ecc_gen_dh_key(const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_key_y,
  168. const uint8_t *our_priv_key, uint8_t *out_dhkey);
  169. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  170. static void esp_bt_controller_log_interface(uint32_t len, const uint8_t *addr, bool end);
  171. #endif // CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  172. /* Local variable definition
  173. ***************************************************************************
  174. */
  175. /* Static variable declare */
  176. static DRAM_ATTR esp_bt_controller_status_t ble_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;
  177. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  178. const static uint32_t log_bufs_size[] = {2048, 1024, 1024};
  179. #endif // CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  180. /* This variable tells if BLE is running */
  181. static bool s_ble_active = false;
  182. #ifdef CONFIG_PM_ENABLE
  183. static DRAM_ATTR esp_pm_lock_handle_t s_pm_lock = NULL;
  184. #define BTDM_MIN_TIMER_UNCERTAINTY_US (200)
  185. #endif // CONFIG_PM_ENABLE
  186. #define BLE_RTC_DELAY_US (1800)
  187. static const struct osi_coex_funcs_t s_osi_coex_funcs_ro = {
  188. ._magic = OSI_COEX_MAGIC_VALUE,
  189. ._version = OSI_COEX_VERSION,
  190. ._coex_wifi_sleep_set = NULL,
  191. ._coex_core_ble_conn_dyn_prio_get = NULL,
  192. ._coex_schm_status_bit_set = coex_schm_status_bit_set_wrapper,
  193. ._coex_schm_status_bit_clear = coex_schm_status_bit_clear_wrapper,
  194. };
  195. struct ext_funcs_t ext_funcs_ro = {
  196. .ext_version = EXT_FUNC_VERSION,
  197. ._esp_intr_alloc = esp_intr_alloc_wrapper,
  198. ._esp_intr_free = esp_intr_free_wrapper,
  199. ._malloc = bt_osi_mem_malloc_internal,
  200. ._free = bt_osi_mem_free,
  201. #if CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  202. ._hal_uart_start_tx = hci_uart_start_tx_wrapper,
  203. ._hal_uart_init_cbs = hci_uart_init_cbs_wrapper,
  204. ._hal_uart_config = hci_uart_config_wrapper,
  205. ._hal_uart_close = hci_uart_close_wrapper,
  206. ._hal_uart_blocking_tx = hci_uart_blocking_tx_wrapper,
  207. ._hal_uart_init = hci_uart_init_wrapper,
  208. #endif //CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  209. ._task_create = task_create_wrapper,
  210. ._task_delete = task_delete_wrapper,
  211. ._osi_assert = osi_assert_wrapper,
  212. ._os_random = osi_random_wrapper,
  213. ._ecc_gen_key_pair = esp_ecc_gen_key_pair,
  214. ._ecc_gen_dh_key = esp_ecc_gen_dh_key,
  215. ._esp_reset_rpa_moudle = esp_reset_rpa_moudle,
  216. ._esp_bt_track_pll_cap = NULL,
  217. .magic = EXT_FUNC_MAGIC_VALUE,
  218. };
  219. static void IRAM_ATTR esp_reset_rpa_moudle(void)
  220. {
  221. DPORT_SET_PERI_REG_MASK(SYSTEM_CORE_RST_EN_REG, BLE_RPA_REST_BIT);
  222. DPORT_CLEAR_PERI_REG_MASK(SYSTEM_CORE_RST_EN_REG, BLE_RPA_REST_BIT);
  223. }
  224. static void IRAM_ATTR osi_assert_wrapper(const uint32_t ln, const char *fn,
  225. uint32_t param1, uint32_t param2)
  226. {
  227. BT_ASSERT_PRINT("BLE assert: line %d in function %s, param: 0x%x, 0x%x", ln, fn, param1, param2);
  228. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  229. esp_ble_controller_log_dump_all(true);
  230. #endif // CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  231. assert(0);
  232. }
  233. static uint32_t IRAM_ATTR osi_random_wrapper(void)
  234. {
  235. return esp_random();
  236. }
  237. static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status)
  238. {
  239. #if CONFIG_SW_COEXIST_ENABLE
  240. coex_schm_status_bit_set(type, status);
  241. #endif // CONFIG_SW_COEXIST_ENABLE
  242. }
  243. static void coex_schm_status_bit_clear_wrapper(uint32_t type, uint32_t status)
  244. {
  245. #if CONFIG_SW_COEXIST_ENABLE
  246. coex_schm_status_bit_clear(type, status);
  247. #endif // CONFIG_SW_COEXIST_ENABLE
  248. }
  249. #ifdef CONFIG_BT_BLUEDROID_ENABLED
  250. bool esp_vhci_host_check_send_available(void)
  251. {
  252. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
  253. return false;
  254. }
  255. return true;
  256. }
  257. /**
  258. * Allocates an mbuf for use by the nimble host.
  259. */
  260. static struct os_mbuf *ble_hs_mbuf_gen_pkt(uint16_t leading_space)
  261. {
  262. struct os_mbuf *om;
  263. int rc;
  264. om = os_msys_get_pkthdr(0, 0);
  265. if (om == NULL) {
  266. return NULL;
  267. }
  268. if (om->om_omp->omp_databuf_len < leading_space) {
  269. rc = os_mbuf_free_chain(om);
  270. assert(rc == 0);
  271. return NULL;
  272. }
  273. om->om_data += leading_space;
  274. return om;
  275. }
  276. /**
  277. * Allocates an mbuf suitable for an HCI ACL data packet.
  278. *
  279. * @return An empty mbuf on success; null on memory
  280. * exhaustion.
  281. */
  282. struct os_mbuf *ble_hs_mbuf_acl_pkt(void)
  283. {
  284. return ble_hs_mbuf_gen_pkt(4 + 1);
  285. }
  286. void esp_vhci_host_send_packet(uint8_t *data, uint16_t len)
  287. {
  288. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
  289. return;
  290. }
  291. if (*(data) == DATA_TYPE_COMMAND) {
  292. struct ble_hci_cmd *cmd = NULL;
  293. cmd = (struct ble_hci_cmd *) ble_hci_trans_buf_alloc(BLE_HCI_TRANS_BUF_CMD);
  294. assert(cmd);
  295. memcpy((uint8_t *)cmd, data + 1, len - 1);
  296. ble_hci_trans_hs_cmd_tx((uint8_t *)cmd);
  297. }
  298. if (*(data) == DATA_TYPE_ACL) {
  299. struct os_mbuf *om = os_msys_get_pkthdr(len, ACL_DATA_MBUF_LEADINGSPCAE);
  300. assert(om);
  301. assert(os_mbuf_append(om, &data[1], len - 1) == 0);
  302. ble_hci_trans_hs_acl_tx(om);
  303. }
  304. }
  305. esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback)
  306. {
  307. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
  308. return ESP_FAIL;
  309. }
  310. ble_hci_trans_cfg_hs(ble_hs_hci_rx_evt, NULL, ble_hs_rx_data, NULL);
  311. return ESP_OK;
  312. }
  313. #endif // CONFIG_BT_BLUEDROID_ENABLED
  314. static int task_create_wrapper(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle, uint32_t core_id)
  315. {
  316. return (uint32_t)xTaskCreatePinnedToCore(task_func, name, stack_depth, param, prio, task_handle, (core_id < portNUM_PROCESSORS ? core_id : tskNO_AFFINITY));
  317. }
  318. static void task_delete_wrapper(void *task_handle)
  319. {
  320. vTaskDelete(task_handle);
  321. }
  322. static int esp_ecc_gen_key_pair(uint8_t *pub, uint8_t *priv)
  323. {
  324. int rc = -1;
  325. #if CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC
  326. rc = ble_sm_alg_gen_key_pair(pub, priv);
  327. #endif // CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC
  328. return rc;
  329. }
  330. static int esp_ecc_gen_dh_key(const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_key_y,
  331. const uint8_t *our_priv_key, uint8_t *out_dhkey)
  332. {
  333. int rc = -1;
  334. #if CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC
  335. rc = ble_sm_alg_gen_dhkey(peer_pub_key_x, peer_pub_key_y, our_priv_key, out_dhkey);
  336. #endif // CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC
  337. return rc;
  338. }
  339. #ifdef CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  340. static void hci_uart_start_tx_wrapper(int uart_no)
  341. {
  342. hci_uart_start_tx(uart_no);
  343. }
  344. static int hci_uart_init_cbs_wrapper(int uart_no, hci_uart_tx_char tx_func,
  345. hci_uart_tx_done tx_done, hci_uart_rx_char rx_func, void *arg)
  346. {
  347. int rc = -1;
  348. rc = hci_uart_init_cbs(uart_no, tx_func, tx_done, rx_func, arg);
  349. return rc;
  350. }
  351. static int hci_uart_config_wrapper(int port_num, int32_t baud_rate, uint8_t data_bits,
  352. uint8_t stop_bits,uart_parity_t parity,
  353. uart_hw_flowcontrol_t flow_ctl)
  354. {
  355. int rc = -1;
  356. rc = hci_uart_config(port_num, baud_rate, data_bits, stop_bits, parity, flow_ctl);
  357. return rc;
  358. }
  359. static int hci_uart_close_wrapper(int uart_no)
  360. {
  361. int rc = -1;
  362. rc = hci_uart_close(uart_no);
  363. return rc;
  364. }
  365. static void hci_uart_blocking_tx_wrapper(int port, uint8_t data)
  366. {
  367. //This function is nowhere to use.
  368. }
  369. static int hci_uart_init_wrapper(int uart_no, void *cfg)
  370. {
  371. //This function is nowhere to use.
  372. return 0;
  373. }
  374. #endif //CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  375. static int ble_hci_unregistered_hook(void*, void*)
  376. {
  377. ESP_LOGD(NIMBLE_PORT_LOG_TAG,"%s ble hci rx_evt is not registered.",__func__);
  378. return 0;
  379. }
  380. static int esp_intr_alloc_wrapper(int source, int flags, intr_handler_t handler, void *arg, void **ret_handle_in)
  381. {
  382. int rc = esp_intr_alloc(source, flags | ESP_INTR_FLAG_IRAM, handler, arg, (intr_handle_t *)ret_handle_in);
  383. return rc;
  384. }
  385. static int esp_intr_free_wrapper(void **ret_handle)
  386. {
  387. int rc = 0;
  388. rc = esp_intr_free((intr_handle_t) * ret_handle);
  389. *ret_handle = NULL;
  390. return rc;
  391. }
  392. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  393. void sleep_modem_light_sleep_overhead_set(uint32_t overhead)
  394. {
  395. esp_ble_set_wakeup_overhead(overhead);
  396. }
  397. #endif /* CONFIG_FREERTOS_USE_TICKLESS_IDLE */
  398. IRAM_ATTR void controller_sleep_cb(uint32_t enable_tick, void *arg)
  399. {
  400. if (!s_ble_active) {
  401. return;
  402. }
  403. #ifdef CONFIG_PM_ENABLE
  404. r_ble_rtc_wake_up_state_clr();
  405. esp_pm_lock_release(s_pm_lock);
  406. #endif // CONFIG_PM_ENABLE
  407. esp_phy_disable(PHY_MODEM_BT);
  408. s_ble_active = false;
  409. }
  410. IRAM_ATTR void controller_wakeup_cb(void *arg)
  411. {
  412. if (s_ble_active) {
  413. return;
  414. }
  415. esp_phy_enable(PHY_MODEM_BT);
  416. // need to check if need to call pm lock here
  417. #ifdef CONFIG_PM_ENABLE
  418. esp_pm_lock_acquire(s_pm_lock);
  419. #endif //CONFIG_PM_ENABLE
  420. s_ble_active = true;
  421. }
  422. esp_err_t controller_sleep_init(void)
  423. {
  424. esp_err_t rc = 0;
  425. #ifdef CONFIG_BT_LE_SLEEP_ENABLE
  426. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "BLE modem sleep is enabled\n");
  427. r_ble_lll_rfmgmt_set_sleep_cb(controller_sleep_cb, controller_wakeup_cb, 0, 0, 500 + BLE_RTC_DELAY_US);
  428. #ifdef CONFIG_PM_ENABLE
  429. esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_ON);
  430. #endif // CONFIG_PM_ENABLE
  431. #endif // CONFIG_BT_LE_SLEEP_ENABLE
  432. // enable light sleep
  433. #ifdef CONFIG_PM_ENABLE
  434. rc = esp_pm_lock_create(ESP_PM_CPU_FREQ_MAX, 0, "bt", &s_pm_lock);
  435. if (rc != ESP_OK) {
  436. goto error;
  437. }
  438. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  439. esp_sleep_enable_bt_wakeup();
  440. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "Enable light sleep, the wake up source is BLE timer");
  441. rc = esp_pm_register_inform_out_light_sleep_overhead_callback(sleep_modem_light_sleep_overhead_set);
  442. if (rc != ESP_OK) {
  443. goto error;
  444. }
  445. #endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
  446. return rc;
  447. error:
  448. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  449. esp_sleep_disable_bt_wakeup();
  450. esp_pm_unregister_inform_out_light_sleep_overhead_callback(sleep_modem_light_sleep_overhead_set);
  451. #endif /* CONFIG_FREERTOS_USE_TICKLESS_IDLE */
  452. /*lock should release first and then delete*/
  453. if (s_pm_lock != NULL) {
  454. esp_pm_lock_delete(s_pm_lock);
  455. s_pm_lock = NULL;
  456. }
  457. #endif //CONFIG_PM_ENABLE
  458. return rc;
  459. }
  460. void controller_sleep_deinit(void)
  461. {
  462. #ifdef CONFIG_FREERTOS_USE_TICKLESS_IDLE
  463. r_ble_rtc_wake_up_state_clr();
  464. esp_sleep_disable_bt_wakeup();
  465. esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_AUTO);
  466. esp_pm_unregister_inform_out_light_sleep_overhead_callback(sleep_modem_light_sleep_overhead_set);
  467. #endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
  468. #ifdef CONFIG_PM_ENABLE
  469. /*lock should release first and then delete*/
  470. esp_pm_lock_delete(s_pm_lock);
  471. s_pm_lock = NULL;
  472. #endif //CONFIG_PM_ENABLE
  473. }
  474. void ble_rtc_clk_init(void)
  475. {
  476. // modem_clkrst_reg
  477. // LP_TIMER_SEL_XTAL32K -> 0
  478. // LP_TIMER_SEL_XTAL -> 1
  479. // LP_TIMER_SEL_8M -> 0
  480. // LP_TIMER_SEL_RTC_SLOW -> 0
  481. SET_PERI_REG_BITS(MODEM_CLKRST_MODEM_LP_TIMER_CONF_REG, 1, 0, MODEM_CLKRST_LP_TIMER_SEL_XTAL32K_S);
  482. SET_PERI_REG_BITS(MODEM_CLKRST_MODEM_LP_TIMER_CONF_REG, 1, 1, MODEM_CLKRST_LP_TIMER_SEL_XTAL_S);
  483. SET_PERI_REG_BITS(MODEM_CLKRST_MODEM_LP_TIMER_CONF_REG, 1, 0, MODEM_CLKRST_LP_TIMER_SEL_8M_S);
  484. SET_PERI_REG_BITS(MODEM_CLKRST_MODEM_LP_TIMER_CONF_REG, 1, 0, MODEM_CLKRST_LP_TIMER_SEL_RTC_SLOW_S);
  485. #ifdef CONFIG_XTAL_FREQ_26
  486. // LP_TIMER_CLK_DIV_NUM -> 130
  487. SET_PERI_REG_BITS(MODEM_CLKRST_MODEM_LP_TIMER_CONF_REG, MODEM_CLKRST_LP_TIMER_CLK_DIV_NUM, 129, MODEM_CLKRST_LP_TIMER_CLK_DIV_NUM_S);
  488. #else
  489. // LP_TIMER_CLK_DIV_NUM -> 250
  490. SET_PERI_REG_BITS(MODEM_CLKRST_MODEM_LP_TIMER_CONF_REG, MODEM_CLKRST_LP_TIMER_CLK_DIV_NUM, 249, MODEM_CLKRST_LP_TIMER_CLK_DIV_NUM_S);
  491. #endif // CONFIG_XTAL_FREQ_26
  492. // MODEM_CLKRST_ETM_CLK_ACTIVE -> 1
  493. // MODEM_CLKRST_ETM_CLK_SEL -> 0
  494. SET_PERI_REG_BITS(MODEM_CLKRST_ETM_CLK_CONF_REG, 1, 1, MODEM_CLKRST_ETM_CLK_ACTIVE_S);
  495. SET_PERI_REG_BITS(MODEM_CLKRST_ETM_CLK_CONF_REG, 1, 0, MODEM_CLKRST_ETM_CLK_SEL_S);
  496. }
  497. esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg)
  498. {
  499. esp_err_t ret = ESP_OK;
  500. ble_npl_count_info_t npl_info;
  501. memset(&npl_info, 0, sizeof(ble_npl_count_info_t));
  502. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
  503. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller state");
  504. return ESP_ERR_INVALID_STATE;
  505. }
  506. if (!cfg) {
  507. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "cfg is NULL");
  508. return ESP_ERR_INVALID_ARG;
  509. }
  510. ble_rtc_clk_init();
  511. ret = esp_register_ext_funcs(&ext_funcs_ro);
  512. if (ret != ESP_OK) {
  513. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "register extend functions failed");
  514. return ret;
  515. }
  516. /* Initialize the function pointers for OS porting */
  517. npl_freertos_funcs_init();
  518. struct npl_funcs_t *p_npl_funcs = npl_freertos_funcs_get();
  519. if (!p_npl_funcs) {
  520. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "npl functions get failed");
  521. return ESP_ERR_INVALID_ARG;
  522. }
  523. ret = esp_register_npl_funcs(p_npl_funcs);
  524. if (ret != ESP_OK) {
  525. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "npl functions register failed");
  526. goto free_mem;
  527. }
  528. ble_get_npl_element_info(cfg, &npl_info);
  529. npl_freertos_set_controller_npl_info(&npl_info);
  530. if (npl_freertos_mempool_init() != 0) {
  531. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "npl mempool init failed");
  532. ret = ESP_ERR_INVALID_ARG;
  533. goto free_mem;
  534. }
  535. /* Initialize the global memory pool */
  536. ret = os_msys_buf_alloc();
  537. if (ret != ESP_OK) {
  538. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "os msys alloc failed");
  539. goto free_mem;
  540. }
  541. os_msys_init();
  542. #if CONFIG_BT_NIMBLE_ENABLED
  543. // ble_npl_eventq_init() need to use npl function in rom and must be called after esp_bt_controller_init()
  544. /* Initialize default event queue */
  545. ble_npl_eventq_init(nimble_port_get_dflt_eventq());
  546. #endif
  547. esp_phy_modem_init();
  548. periph_module_enable(PERIPH_BT_MODULE);
  549. periph_module_reset(PERIPH_BT_MODULE);
  550. if (ble_osi_coex_funcs_register((struct osi_coex_funcs_t *)&s_osi_coex_funcs_ro) != 0) {
  551. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "osi coex funcs reg failed");
  552. ret = ESP_ERR_INVALID_ARG;
  553. goto modem_deint;
  554. }
  555. #if CONFIG_SW_COEXIST_ENABLE
  556. coex_init();
  557. #endif
  558. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  559. interface_func_t bt_controller_log_interface;
  560. bt_controller_log_interface = esp_bt_controller_log_interface;
  561. uint8_t buffers = 0;
  562. #if CONFIG_BT_LE_CONTROLLER_LOG_CTRL_ENABLED
  563. buffers |= ESP_BLE_LOG_BUF_CONTROLLER;
  564. #endif // CONFIG_BT_LE_CONTROLLER_LOG_CTRL_ENABLED
  565. #if CONFIG_BT_LE_CONTROLLER_LOG_HCI_ENABLED
  566. buffers |= ESP_BLE_LOG_BUF_HCI;
  567. #endif // CONFIG_BT_LE_CONTROLLER_LOG_HCI_ENABLED
  568. #if CONFIG_BT_LE_CONTROLLER_LOG_DUMP_ONLY
  569. ret = ble_log_init_async(bt_controller_log_interface, false, buffers, (uint32_t *)log_bufs_size);
  570. #else
  571. ret = ble_log_init_async(bt_controller_log_interface, true, buffers, (uint32_t *)log_bufs_size);
  572. #endif // CONFIG_BT_CONTROLLER_LOG_DUMP
  573. if (ret != ESP_OK) {
  574. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "ble_controller_log_init failed %d", ret);
  575. goto modem_deint;
  576. }
  577. #endif // CONFIG_BT_CONTROLLER_LOG_ENABLED
  578. ret = ble_controller_init(cfg);
  579. if (ret != ESP_OK) {
  580. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "ble_controller_init failed %d", ret);
  581. goto modem_deint;
  582. }
  583. ret = controller_sleep_init();
  584. if (ret != ESP_OK) {
  585. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "controller_sleep_init failed %d", ret);
  586. goto free_controller;
  587. }
  588. uint8_t mac[6];
  589. ESP_ERROR_CHECK(esp_read_mac((uint8_t *)mac, ESP_MAC_BT));
  590. swap_in_place(mac, 6);
  591. esp_ble_ll_set_public_addr(mac);
  592. ble_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;
  593. ble_hci_trans_cfg_hs((ble_hci_trans_rx_cmd_fn *)ble_hci_unregistered_hook,NULL,
  594. (ble_hci_trans_rx_acl_fn *)ble_hci_unregistered_hook,NULL);
  595. return ESP_OK;
  596. free_controller:
  597. controller_sleep_deinit();
  598. ble_controller_deinit();
  599. modem_deint:
  600. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  601. ble_log_deinit_async();
  602. #endif // CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  603. esp_phy_modem_deinit();
  604. periph_module_disable(PERIPH_BT_MODULE);
  605. #if CONFIG_BT_NIMBLE_ENABLED
  606. ble_npl_eventq_deinit(nimble_port_get_dflt_eventq());
  607. #endif // CONFIG_BT_NIMBLE_ENABLED
  608. free_mem:
  609. os_msys_buf_free();
  610. npl_freertos_mempool_deinit();
  611. esp_unregister_npl_funcs();
  612. npl_freertos_funcs_deinit();
  613. esp_unregister_ext_funcs();
  614. return ret;
  615. }
  616. esp_err_t esp_bt_controller_deinit(void)
  617. {
  618. if ((ble_controller_status < ESP_BT_CONTROLLER_STATUS_INITED) || (ble_controller_status >= ESP_BT_CONTROLLER_STATUS_ENABLED)) {
  619. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller state");
  620. return ESP_FAIL;
  621. }
  622. controller_sleep_deinit();
  623. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  624. ble_log_deinit_async();
  625. #endif // CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  626. ble_controller_deinit();
  627. periph_module_disable(PERIPH_BT_MODULE);
  628. #if CONFIG_BT_NIMBLE_ENABLED
  629. /* De-initialize default event queue */
  630. ble_npl_eventq_deinit(nimble_port_get_dflt_eventq());
  631. #endif
  632. os_msys_buf_free();
  633. esp_unregister_npl_funcs();
  634. esp_unregister_ext_funcs();
  635. /* De-initialize npl functions */
  636. npl_freertos_funcs_deinit();
  637. npl_freertos_mempool_deinit();
  638. esp_phy_modem_deinit();
  639. ble_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;
  640. return ESP_OK;
  641. }
  642. esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode)
  643. {
  644. esp_err_t ret = ESP_OK;
  645. if (mode != ESP_BT_MODE_BLE) {
  646. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller mode");
  647. return ESP_FAIL;
  648. }
  649. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_INITED) {
  650. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller state");
  651. return ESP_FAIL;
  652. }
  653. if (!s_ble_active) {
  654. #if CONFIG_PM_ENABLE
  655. esp_pm_lock_acquire(s_pm_lock);
  656. #endif // CONFIG_PM_ENABLE
  657. // init phy
  658. esp_phy_enable(PHY_MODEM_BT);
  659. s_ble_active = true;
  660. }
  661. // init bb
  662. bt_bb_v2_init_cmplx(1);
  663. #if CONFIG_SW_COEXIST_ENABLE
  664. coex_enable();
  665. #endif
  666. if (ble_controller_enable(mode) != 0) {
  667. ret = ESP_FAIL;
  668. goto error;
  669. }
  670. ble_controller_status = ESP_BT_CONTROLLER_STATUS_ENABLED;
  671. return ESP_OK;
  672. error:
  673. #if CONFIG_SW_COEXIST_ENABLE
  674. coex_disable();
  675. #endif
  676. if (s_ble_active) {
  677. esp_phy_disable(PHY_MODEM_BT);
  678. #if CONFIG_PM_ENABLE
  679. esp_pm_lock_release(s_pm_lock);
  680. #endif // CONFIG_PM_ENABLE
  681. s_ble_active = false;
  682. }
  683. return ret;
  684. }
  685. esp_err_t esp_bt_controller_disable(void)
  686. {
  687. if (ble_controller_status < ESP_BT_CONTROLLER_STATUS_ENABLED) {
  688. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller state");
  689. return ESP_FAIL;
  690. }
  691. if (ble_controller_disable() != 0) {
  692. return ESP_FAIL;
  693. }
  694. if (s_ble_active) {
  695. esp_phy_disable(PHY_MODEM_BT);
  696. #if CONFIG_PM_ENABLE
  697. esp_pm_lock_release(s_pm_lock);
  698. #endif // CONFIG_PM_ENABLE
  699. s_ble_active = false;
  700. }
  701. #if CONFIG_SW_COEXIST_ENABLE
  702. coex_disable();
  703. #endif
  704. ble_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;
  705. return ESP_OK;
  706. }
  707. esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode)
  708. {
  709. ESP_LOGD(NIMBLE_PORT_LOG_TAG, "%s not implemented, return OK", __func__);
  710. return ESP_OK;
  711. }
  712. static esp_err_t try_heap_caps_add_region(intptr_t start, intptr_t end)
  713. {
  714. int ret = heap_caps_add_region(start, end);
  715. /* heap_caps_add_region() returns ESP_ERR_INVALID_SIZE if the memory region is
  716. * is too small to fit a heap. This cannot be termed as a fatal error and hence
  717. * we replace it by ESP_OK
  718. */
  719. if (ret == ESP_ERR_INVALID_SIZE) {
  720. return ESP_OK;
  721. }
  722. return ret;
  723. }
  724. esp_err_t esp_bt_mem_release(esp_bt_mode_t mode)
  725. {
  726. intptr_t mem_start, mem_end;
  727. #if CONFIG_BT_RELEASE_IRAM && CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT
  728. /* Release Bluetooth text section and merge Bluetooth data, bss & text into a large free heap
  729. * region when esp_bt_mem_release is called, total saving ~21kB or more of IRAM. ESP32-C2 has
  730. * only 3 configurable PMP entries available, rest of them are hard-coded. We cannot split the
  731. * memory into 3 different regions (IRAM, BLE-IRAM, DRAM). So `ESP_SYSTEM_PMP_IDRAM_SPLIT` needs
  732. * to be disabled.
  733. */
  734. ESP_LOGE(NIMBLE_PORT_LOG_TAG, "`ESP_SYSTEM_PMP_IDRAM_SPLIT` should be disabled!");
  735. assert(0);
  736. #endif // CONFIG_BT_RELEASE_IRAM && CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT
  737. if (mode & ESP_BT_MODE_BLE) {
  738. #if CONFIG_BT_RELEASE_IRAM
  739. mem_start = (intptr_t)MAP_IRAM_TO_DRAM((intptr_t)&_iram_bt_text_start);
  740. mem_end = (intptr_t)&_bss_bt_end;
  741. #else
  742. mem_start = (intptr_t)&_bt_controller_data_start;
  743. mem_end = (intptr_t)&_bt_bss_end;
  744. #endif // CONFIG_BT_RELEASE_IRAM
  745. if (mem_start != mem_end) {
  746. ESP_LOGI(NIMBLE_PORT_LOG_TAG, "Release BLE [0x%08x] - [0x%08x], len %d", mem_start,
  747. mem_end, mem_end - mem_start);
  748. ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
  749. }
  750. }
  751. return ESP_OK;
  752. }
  753. esp_bt_controller_status_t esp_bt_controller_get_status(void)
  754. {
  755. return ble_controller_status;
  756. }
  757. /* extra functions */
  758. esp_err_t esp_ble_tx_power_set(esp_ble_power_type_t power_type, esp_power_level_t power_level)
  759. {
  760. esp_err_t stat = ESP_FAIL;
  761. switch (power_type) {
  762. case ESP_BLE_PWR_TYPE_DEFAULT:
  763. case ESP_BLE_PWR_TYPE_ADV:
  764. case ESP_BLE_PWR_TYPE_SCAN:
  765. if (ble_txpwr_set(ESP_BLE_ENHANCED_PWR_TYPE_DEFAULT, 0, power_level) == 0) {
  766. stat = ESP_OK;
  767. }
  768. break;
  769. case ESP_BLE_PWR_TYPE_CONN_HDL0:
  770. case ESP_BLE_PWR_TYPE_CONN_HDL1:
  771. case ESP_BLE_PWR_TYPE_CONN_HDL2:
  772. case ESP_BLE_PWR_TYPE_CONN_HDL3:
  773. case ESP_BLE_PWR_TYPE_CONN_HDL4:
  774. case ESP_BLE_PWR_TYPE_CONN_HDL5:
  775. case ESP_BLE_PWR_TYPE_CONN_HDL6:
  776. case ESP_BLE_PWR_TYPE_CONN_HDL7:
  777. case ESP_BLE_PWR_TYPE_CONN_HDL8:
  778. if (ble_txpwr_set(ESP_BLE_ENHANCED_PWR_TYPE_CONN, power_type, power_level) == 0) {
  779. stat = ESP_OK;
  780. }
  781. break;
  782. default:
  783. stat = ESP_ERR_NOT_SUPPORTED;
  784. break;
  785. }
  786. return stat;
  787. }
  788. esp_err_t esp_ble_tx_power_set_enhanced(esp_ble_enhanced_power_type_t power_type, uint16_t handle, esp_power_level_t power_level)
  789. {
  790. esp_err_t stat = ESP_FAIL;
  791. switch (power_type) {
  792. case ESP_BLE_ENHANCED_PWR_TYPE_DEFAULT:
  793. case ESP_BLE_ENHANCED_PWR_TYPE_SCAN:
  794. case ESP_BLE_ENHANCED_PWR_TYPE_INIT:
  795. if (ble_txpwr_set(ESP_BLE_ENHANCED_PWR_TYPE_DEFAULT, 0, power_level) == 0) {
  796. stat = ESP_OK;
  797. }
  798. break;
  799. case ESP_BLE_ENHANCED_PWR_TYPE_ADV:
  800. case ESP_BLE_ENHANCED_PWR_TYPE_CONN:
  801. if (ble_txpwr_set(power_type, handle, power_level) == 0) {
  802. stat = ESP_OK;
  803. }
  804. break;
  805. default:
  806. stat = ESP_ERR_NOT_SUPPORTED;
  807. break;
  808. }
  809. return stat;
  810. }
  811. esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type)
  812. {
  813. int tx_level = 0;
  814. switch (power_type) {
  815. case ESP_BLE_PWR_TYPE_ADV:
  816. case ESP_BLE_PWR_TYPE_SCAN:
  817. case ESP_BLE_PWR_TYPE_DEFAULT:
  818. tx_level = ble_txpwr_get(ESP_BLE_ENHANCED_PWR_TYPE_DEFAULT, 0);
  819. break;
  820. case ESP_BLE_PWR_TYPE_CONN_HDL0:
  821. case ESP_BLE_PWR_TYPE_CONN_HDL1:
  822. case ESP_BLE_PWR_TYPE_CONN_HDL2:
  823. case ESP_BLE_PWR_TYPE_CONN_HDL3:
  824. case ESP_BLE_PWR_TYPE_CONN_HDL4:
  825. case ESP_BLE_PWR_TYPE_CONN_HDL5:
  826. case ESP_BLE_PWR_TYPE_CONN_HDL6:
  827. case ESP_BLE_PWR_TYPE_CONN_HDL7:
  828. case ESP_BLE_PWR_TYPE_CONN_HDL8:
  829. tx_level = ble_txpwr_get(ESP_BLE_ENHANCED_PWR_TYPE_CONN, power_type);
  830. break;
  831. default:
  832. return ESP_PWR_LVL_INVALID;
  833. }
  834. if (tx_level < 0) {
  835. return ESP_PWR_LVL_INVALID;
  836. }
  837. return (esp_power_level_t)tx_level;
  838. }
  839. esp_power_level_t esp_ble_tx_power_get_enhanced(esp_ble_enhanced_power_type_t power_type, uint16_t handle)
  840. {
  841. int tx_level = 0;
  842. switch (power_type) {
  843. case ESP_BLE_ENHANCED_PWR_TYPE_DEFAULT:
  844. case ESP_BLE_ENHANCED_PWR_TYPE_SCAN:
  845. case ESP_BLE_ENHANCED_PWR_TYPE_INIT:
  846. tx_level = ble_txpwr_get(ESP_BLE_ENHANCED_PWR_TYPE_DEFAULT, 0);
  847. break;
  848. case ESP_BLE_ENHANCED_PWR_TYPE_ADV:
  849. case ESP_BLE_ENHANCED_PWR_TYPE_CONN:
  850. tx_level = ble_txpwr_get(power_type, handle);
  851. break;
  852. default:
  853. return ESP_PWR_LVL_INVALID;
  854. }
  855. if (tx_level < 0) {
  856. return ESP_PWR_LVL_INVALID;
  857. }
  858. return (esp_power_level_t)tx_level;
  859. }
  860. uint8_t esp_ble_get_chip_rev_version(void)
  861. {
  862. return efuse_ll_get_chip_wafer_version_minor();
  863. }
  864. #if CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  865. static void esp_bt_controller_log_interface(uint32_t len, const uint8_t *addr, bool end)
  866. {
  867. for (int i = 0; i < len; i++) {
  868. esp_rom_printf("%02x ", addr[i]);
  869. }
  870. if (end) {
  871. esp_rom_printf("\n");
  872. }
  873. }
  874. void esp_ble_controller_log_dump_all(bool output)
  875. {
  876. portMUX_TYPE spinlock;
  877. portENTER_CRITICAL_SAFE(&spinlock);
  878. BT_ASSERT_PRINT("\r\n[DUMP_START:");
  879. ble_log_async_output_dump_all(output);
  880. BT_ASSERT_PRINT("]\r\n");
  881. portEXIT_CRITICAL_SAFE(&spinlock);
  882. }
  883. #endif // CONFIG_BT_LE_CONTROLLER_LOG_ENABLED
  884. #if (!CONFIG_BT_NIMBLE_ENABLED) && (CONFIG_BT_CONTROLLER_ENABLED == true)
  885. #define BLE_SM_KEY_ERR 0x17
  886. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  887. #include "mbedtls/aes.h"
  888. #if CONFIG_BT_LE_SM_SC
  889. #include "mbedtls/cipher.h"
  890. #include "mbedtls/entropy.h"
  891. #include "mbedtls/ctr_drbg.h"
  892. #include "mbedtls/cmac.h"
  893. #include "mbedtls/ecdh.h"
  894. #include "mbedtls/ecp.h"
  895. #endif
  896. #else
  897. #include "tinycrypt/aes.h"
  898. #include "tinycrypt/constants.h"
  899. #include "tinycrypt/utils.h"
  900. #if CONFIG_BT_LE_SM_SC
  901. #include "tinycrypt/cmac_mode.h"
  902. #include "tinycrypt/ecc_dh.h"
  903. #endif
  904. #endif
  905. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  906. #if CONFIG_BT_LE_SM_SC
  907. static mbedtls_ecp_keypair keypair;
  908. #endif
  909. #endif
  910. int ble_sm_alg_gen_dhkey(const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_key_y,
  911. const uint8_t *our_priv_key, uint8_t *out_dhkey)
  912. {
  913. uint8_t dh[32];
  914. uint8_t pk[64];
  915. uint8_t priv[32];
  916. int rc = BLE_SM_KEY_ERR;
  917. swap_buf(pk, peer_pub_key_x, 32);
  918. swap_buf(&pk[32], peer_pub_key_y, 32);
  919. swap_buf(priv, our_priv_key, 32);
  920. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  921. struct mbedtls_ecp_point pt = {0}, Q = {0};
  922. mbedtls_mpi z = {0}, d = {0};
  923. mbedtls_ctr_drbg_context ctr_drbg = {0};
  924. mbedtls_entropy_context entropy = {0};
  925. uint8_t pub[65] = {0};
  926. /* Hardcoded first byte of pub key for MBEDTLS_ECP_PF_UNCOMPRESSED */
  927. pub[0] = 0x04;
  928. memcpy(&pub[1], pk, 64);
  929. /* Initialize the required structures here */
  930. mbedtls_ecp_point_init(&pt);
  931. mbedtls_ecp_point_init(&Q);
  932. mbedtls_ctr_drbg_init(&ctr_drbg);
  933. mbedtls_entropy_init(&entropy);
  934. mbedtls_mpi_init(&d);
  935. mbedtls_mpi_init(&z);
  936. /* Below 3 steps are to validate public key on curve secp256r1 */
  937. if (mbedtls_ecp_group_load(&keypair.MBEDTLS_PRIVATE(grp), MBEDTLS_ECP_DP_SECP256R1) != 0) {
  938. goto exit;
  939. }
  940. if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &pt, pub, 65) != 0) {
  941. goto exit;
  942. }
  943. if (mbedtls_ecp_check_pubkey(&keypair.MBEDTLS_PRIVATE(grp), &pt) != 0) {
  944. goto exit;
  945. }
  946. /* Set PRNG */
  947. if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  948. NULL, 0)) != 0) {
  949. goto exit;
  950. }
  951. /* Prepare point Q from pub key */
  952. if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &Q, pub, 65) != 0) {
  953. goto exit;
  954. }
  955. if (mbedtls_mpi_read_binary(&d, priv, 32) != 0) {
  956. goto exit;
  957. }
  958. rc = mbedtls_ecdh_compute_shared(&keypair.MBEDTLS_PRIVATE(grp), &z, &Q, &d,
  959. mbedtls_ctr_drbg_random, &ctr_drbg);
  960. if (rc != 0) {
  961. goto exit;
  962. }
  963. rc = mbedtls_mpi_write_binary(&z, dh, 32);
  964. if (rc != 0) {
  965. goto exit;
  966. }
  967. exit:
  968. mbedtls_ecp_point_free(&pt);
  969. mbedtls_mpi_free(&z);
  970. mbedtls_mpi_free(&d);
  971. mbedtls_ecp_point_free(&Q);
  972. mbedtls_entropy_free(&entropy);
  973. mbedtls_ctr_drbg_free(&ctr_drbg);
  974. if (rc != 0) {
  975. return BLE_SM_KEY_ERR;
  976. }
  977. #else
  978. if (uECC_valid_public_key(pk, &curve_secp256r1) < 0) {
  979. return BLE_SM_KEY_ERR;
  980. }
  981. rc = uECC_shared_secret(pk, priv, dh, &curve_secp256r1);
  982. if (rc == TC_CRYPTO_FAIL) {
  983. return BLE_SM_KEY_ERR;
  984. }
  985. #endif
  986. swap_buf(out_dhkey, dh, 32);
  987. return 0;
  988. }
  989. /* based on Core Specification 4.2 Vol 3. Part H 2.3.5.6.1 */
  990. static const uint8_t ble_sm_alg_dbg_priv_key[32] = {
  991. 0x3f, 0x49, 0xf6, 0xd4, 0xa3, 0xc5, 0x5f, 0x38, 0x74, 0xc9, 0xb3, 0xe3,
  992. 0xd2, 0x10, 0x3f, 0x50, 0x4a, 0xff, 0x60, 0x7b, 0xeb, 0x40, 0xb7, 0x99,
  993. 0x58, 0x99, 0xb8, 0xa6, 0xcd, 0x3c, 0x1a, 0xbd
  994. };
  995. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  996. static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key)
  997. {
  998. int rc = BLE_SM_KEY_ERR;
  999. mbedtls_entropy_context entropy = {0};
  1000. mbedtls_ctr_drbg_context ctr_drbg = {0};
  1001. mbedtls_entropy_init(&entropy);
  1002. mbedtls_ctr_drbg_init(&ctr_drbg);
  1003. mbedtls_ecp_keypair_init(&keypair);
  1004. if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  1005. NULL, 0)) != 0) {
  1006. goto exit;
  1007. }
  1008. if ((rc = mbedtls_ecp_gen_key(MBEDTLS_ECP_DP_SECP256R1, &keypair,
  1009. mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
  1010. goto exit;
  1011. }
  1012. if ((rc = mbedtls_mpi_write_binary(&keypair.MBEDTLS_PRIVATE(d), private_key, 32)) != 0) {
  1013. goto exit;
  1014. }
  1015. size_t olen = 0;
  1016. uint8_t pub[65] = {0};
  1017. if ((rc = mbedtls_ecp_point_write_binary(&keypair.MBEDTLS_PRIVATE(grp), &keypair.MBEDTLS_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED,
  1018. &olen, pub, 65)) != 0) {
  1019. goto exit;
  1020. }
  1021. memcpy(public_key, &pub[1], 64);
  1022. exit:
  1023. mbedtls_ctr_drbg_free(&ctr_drbg);
  1024. mbedtls_entropy_free(&entropy);
  1025. if (rc != 0) {
  1026. mbedtls_ecp_keypair_free(&keypair);
  1027. return BLE_SM_KEY_ERR;
  1028. }
  1029. return 0;
  1030. }
  1031. #endif
  1032. /**
  1033. * pub: 64 bytes
  1034. * priv: 32 bytes
  1035. */
  1036. int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv)
  1037. {
  1038. #if CONFIG_BT_LE_SM_SC_DEBUG_KEYS
  1039. swap_buf(pub, ble_sm_alg_dbg_pub_key, 32);
  1040. swap_buf(&pub[32], &ble_sm_alg_dbg_pub_key[32], 32);
  1041. swap_buf(priv, ble_sm_alg_dbg_priv_key, 32);
  1042. #else
  1043. uint8_t pk[64];
  1044. do {
  1045. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  1046. if (mbedtls_gen_keypair(pk, priv) != 0) {
  1047. return BLE_SM_KEY_ERR;
  1048. }
  1049. #else
  1050. if (uECC_make_key(pk, priv, &curve_secp256r1) != TC_CRYPTO_SUCCESS) {
  1051. return BLE_SM_KEY_ERR;
  1052. }
  1053. #endif
  1054. /* Make sure generated key isn't debug key. */
  1055. } while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0);
  1056. swap_buf(pub, pk, 32);
  1057. swap_buf(&pub[32], &pk[32], 32);
  1058. swap_in_place(priv, 32);
  1059. #endif
  1060. return 0;
  1061. }
  1062. #endif