bt.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2022 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_mac.h>
  12. #include "sdkconfig.h"
  13. #include "nimble/nimble_port.h"
  14. #include "nimble/nimble_port_freertos.h"
  15. #ifdef ESP_PLATFORM
  16. #include "esp_log.h"
  17. #endif
  18. #if CONFIG_SW_COEXIST_ENABLE
  19. #include "esp_coexist_internal.h"
  20. #endif
  21. #include "nimble/nimble_npl_os.h"
  22. #include "nimble/ble_hci_trans.h"
  23. #include "os/endian.h"
  24. #include "esp_bt.h"
  25. #include "esp_intr_alloc.h"
  26. #include "esp_sleep.h"
  27. #include "esp_pm.h"
  28. #include "esp_phy_init.h"
  29. #include "soc/system_reg.h"
  30. #include "soc/clkrst_reg.h"
  31. #include "hci_uart.h"
  32. #include "bt_osi_mem.h"
  33. #ifdef CONFIG_BT_BLUEDROID_ENABLED
  34. #include "hci/hci_hal.h"
  35. #endif
  36. #include "freertos/FreeRTOS.h"
  37. #include "freertos/task.h"
  38. #include "esp_private/periph_ctrl.h"
  39. #include "esp_sleep.h"
  40. /* Macro definition
  41. ************************************************************************
  42. */
  43. #define NIMBLE_PORT_LOG_TAG "BLE_INIT"
  44. #define OSI_COEX_VERSION 0x00010006
  45. #define OSI_COEX_MAGIC_VALUE 0xFADEBEAD
  46. #define EXT_FUNC_VERSION 0x20220125
  47. #define EXT_FUNC_MAGIC_VALUE 0xA5A5A5A5
  48. /* Types definition
  49. ************************************************************************
  50. */
  51. struct osi_coex_funcs_t {
  52. uint32_t _magic;
  53. uint32_t _version;
  54. void (* _coex_wifi_sleep_set)(bool sleep);
  55. int (* _coex_core_ble_conn_dyn_prio_get)(bool *low, bool *high);
  56. void (* _coex_schm_status_bit_set)(uint32_t type, uint32_t status);
  57. void (* _coex_schm_status_bit_clear)(uint32_t type, uint32_t status);
  58. };
  59. struct ext_funcs_t {
  60. uint32_t ext_version;
  61. int (*_esp_intr_alloc)(int source, int flags, intr_handler_t handler, void *arg, void **ret_handle);
  62. int (*_esp_intr_free)(void **ret_handle);
  63. void *(* _malloc)(size_t size);
  64. void (*_free)(void *p);
  65. void (*_hal_uart_start_tx)(int);
  66. int (*_hal_uart_init_cbs)(int, hci_uart_tx_char, hci_uart_tx_done, hci_uart_rx_char, void *);
  67. int (*_hal_uart_config)(int, int32_t, uint8_t, uint8_t, uart_parity_t, uart_hw_flowcontrol_t);
  68. int (*_hal_uart_close)(int);
  69. void (*_hal_uart_blocking_tx)(int, uint8_t);
  70. int (*_hal_uart_init)(int, void *);
  71. 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);
  72. void (* _task_delete)(void *task_handle);
  73. void (*_osi_assert)(const uint32_t ln, const char *fn, uint32_t param1, uint32_t param2);
  74. uint32_t (* _os_random)(void);
  75. int (* _ecc_gen_key_pair)(uint8_t *pub, uint8_t *priv);
  76. 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);
  77. int (* _esp_reset_rpa_moudle)(void);
  78. uint32_t magic;
  79. };
  80. /* External functions or variables
  81. ************************************************************************
  82. */
  83. extern int ble_plf_set_log_level(int level);
  84. extern int ble_osi_coex_funcs_register(struct osi_coex_funcs_t *coex_funcs);
  85. extern int coex_core_ble_conn_dyn_prio_get(bool *low, bool *high);
  86. extern int ble_controller_init(esp_bt_controller_config_t *cfg);
  87. extern int ble_controller_deinit(void);
  88. extern int ble_controller_enable(uint8_t mode);
  89. extern int ble_controller_disable(void);
  90. extern int esp_register_ext_funcs (struct ext_funcs_t *);
  91. extern void esp_unregister_ext_funcs (void);
  92. extern int esp_ble_ll_set_public_addr(const uint8_t *addr);
  93. extern int esp_register_npl_funcs (struct npl_funcs_t *p_npl_func);
  94. extern void esp_unregister_npl_funcs (void);
  95. extern void npl_freertos_mempool_deinit(void);
  96. /* TX power */
  97. int ble_txpwr_set(int power_type, int power_level);
  98. int ble_txpwr_get(int power_type);
  99. extern void bt_bb_v2_init_cmplx(uint8_t i);
  100. extern int os_msys_buf_alloc(void);
  101. extern uint32_t r_os_cputime_get32(void);
  102. extern uint32_t r_os_cputime_ticks_to_usecs(uint32_t ticks);
  103. extern void r_ble_ll_rfmgmt_set_sleep_cb(void *s_cb, void *w_cb, void *s_arg, void *w_arg, uint32_t us_to_enabled);
  104. extern int os_msys_init(void);
  105. extern void os_msys_buf_free(void);
  106. extern void bt_bb_set_le_tx_on_delay(uint32_t delay_us);
  107. extern int ble_sm_alg_gen_dhkey(const uint8_t *peer_pub_key_x,
  108. const uint8_t *peer_pub_key_y,
  109. const uint8_t *our_priv_key, uint8_t *out_dhkey);
  110. extern int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv);
  111. /* Local Function Declaration
  112. *********************************************************************
  113. */
  114. static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status);
  115. static void coex_schm_status_bit_clear_wrapper(uint32_t type, uint32_t status);
  116. 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);
  117. static void task_delete_wrapper(void *task_handle);
  118. #if CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  119. static void hci_uart_start_tx_wrapper(int uart_no);
  120. static int hci_uart_init_cbs_wrapper(int uart_no, hci_uart_tx_char tx_func,
  121. hci_uart_tx_done tx_done, hci_uart_rx_char rx_func, void *arg);
  122. static int hci_uart_config_wrapper(int uart_no, int32_t speed, uint8_t databits, uint8_t stopbits,
  123. uart_parity_t parity, uart_hw_flowcontrol_t flow_ctl);
  124. static int hci_uart_close_wrapper(int uart_no);
  125. static void hci_uart_blocking_tx_wrapper(int port, uint8_t data);
  126. static int hci_uart_init_wrapper(int uart_no, void *cfg);
  127. #endif
  128. static int esp_intr_alloc_wrapper(int source, int flags, intr_handler_t handler, void *arg, void **ret_handle_in);
  129. static int esp_intr_free_wrapper(void **ret_handle);
  130. static void osi_assert_wrapper(const uint32_t ln, const char *fn, uint32_t param1, uint32_t param2);
  131. static uint32_t osi_random_wrapper(void);
  132. static int esp_reset_rpa_moudle(void);
  133. /* Local variable definition
  134. ***************************************************************************
  135. */
  136. /* Static variable declare */
  137. static DRAM_ATTR esp_bt_controller_status_t ble_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;
  138. #ifdef CONFIG_PM_ENABLE
  139. static DRAM_ATTR esp_pm_lock_handle_t s_pm_lock = NULL;
  140. static bool s_pm_lock_acquired = true;
  141. static DRAM_ATTR bool s_btdm_allow_light_sleep;
  142. // pm_lock to prevent light sleep when using main crystal as Bluetooth low power clock
  143. static DRAM_ATTR esp_pm_lock_handle_t s_light_sleep_pm_lock;
  144. #define BTDM_MIN_TIMER_UNCERTAINTY_US (200)
  145. #endif /* #ifdef CONFIG_PM_ENABLE */
  146. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_BLE_RTC_TIMER
  147. #define BLE_RTC_DELAY_US (1100)
  148. #endif
  149. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  150. #define BLE_RTC_DELAY_US (0)
  151. static void btdm_slp_tmr_callback(void *arg);
  152. static DRAM_ATTR esp_timer_handle_t s_btdm_slp_tmr = NULL;
  153. #endif
  154. static const struct osi_coex_funcs_t s_osi_coex_funcs_ro = {
  155. ._magic = OSI_COEX_MAGIC_VALUE,
  156. ._version = OSI_COEX_VERSION,
  157. ._coex_wifi_sleep_set = NULL,
  158. ._coex_core_ble_conn_dyn_prio_get = NULL,
  159. ._coex_schm_status_bit_set = coex_schm_status_bit_set_wrapper,
  160. ._coex_schm_status_bit_clear = coex_schm_status_bit_clear_wrapper,
  161. };
  162. struct ext_funcs_t ext_funcs_ro = {
  163. .ext_version = EXT_FUNC_VERSION,
  164. ._esp_intr_alloc = esp_intr_alloc_wrapper,
  165. ._esp_intr_free = esp_intr_free_wrapper,
  166. ._malloc = bt_osi_mem_malloc_internal,
  167. ._free = bt_osi_mem_free,
  168. #if CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  169. ._hal_uart_start_tx = hci_uart_start_tx_wrapper,
  170. ._hal_uart_init_cbs = hci_uart_init_cbs_wrapper,
  171. ._hal_uart_config = hci_uart_config_wrapper,
  172. ._hal_uart_close = hci_uart_close_wrapper,
  173. ._hal_uart_blocking_tx = hci_uart_blocking_tx_wrapper,
  174. ._hal_uart_init = hci_uart_init_wrapper,
  175. #endif //CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  176. ._task_create = task_create_wrapper,
  177. ._task_delete = task_delete_wrapper,
  178. ._osi_assert = osi_assert_wrapper,
  179. ._os_random = osi_random_wrapper,
  180. ._ecc_gen_key_pair = ble_sm_alg_gen_key_pair,
  181. ._ecc_gen_dh_key = ble_sm_alg_gen_dhkey,
  182. ._esp_reset_rpa_moudle = esp_reset_rpa_moudle,
  183. .magic = EXT_FUNC_MAGIC_VALUE,
  184. };
  185. static int IRAM_ATTR esp_reset_rpa_moudle(void)
  186. {
  187. periph_module_reset(PERIPH_MODEM_RPA_MODULE);
  188. return 0;
  189. }
  190. static void IRAM_ATTR osi_assert_wrapper(const uint32_t ln, const char *fn, uint32_t param1, uint32_t param2)
  191. {
  192. ESP_LOGE(NIMBLE_PORT_LOG_TAG, "BLE assert: line %d in function %s, param: 0x%x, 0x%x", ln, fn, param1, param2);
  193. assert(0);
  194. }
  195. static uint32_t IRAM_ATTR osi_random_wrapper(void)
  196. {
  197. return esp_random();
  198. }
  199. static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status)
  200. {
  201. #if CONFIG_SW_COEXIST_ENABLE
  202. coex_schm_status_bit_set(type, status);
  203. #endif
  204. }
  205. static void coex_schm_status_bit_clear_wrapper(uint32_t type, uint32_t status)
  206. {
  207. #if CONFIG_SW_COEXIST_ENABLE
  208. coex_schm_status_bit_clear(type, status);
  209. #endif
  210. }
  211. #ifdef CONFIG_BT_BLUEDROID_ENABLED
  212. bool esp_vhci_host_check_send_available(void)
  213. {
  214. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
  215. return false;
  216. }
  217. return true;
  218. }
  219. /**
  220. * Allocates an mbuf for use by the nimble host.
  221. */
  222. static struct os_mbuf *ble_hs_mbuf_gen_pkt(uint16_t leading_space)
  223. {
  224. struct os_mbuf *om;
  225. int rc;
  226. om = os_msys_get_pkthdr(0, 0);
  227. if (om == NULL) {
  228. return NULL;
  229. }
  230. if (om->om_omp->omp_databuf_len < leading_space) {
  231. rc = os_mbuf_free_chain(om);
  232. assert(rc == 0);
  233. return NULL;
  234. }
  235. om->om_data += leading_space;
  236. return om;
  237. }
  238. /**
  239. * Allocates an mbuf suitable for an HCI ACL data packet.
  240. *
  241. * @return An empty mbuf on success; null on memory
  242. * exhaustion.
  243. */
  244. struct os_mbuf *ble_hs_mbuf_acl_pkt(void)
  245. {
  246. return ble_hs_mbuf_gen_pkt(4 + 1);
  247. }
  248. void esp_vhci_host_send_packet(uint8_t *data, uint16_t len)
  249. {
  250. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
  251. return;
  252. }
  253. if (*(data) == DATA_TYPE_COMMAND) {
  254. struct ble_hci_cmd *cmd = NULL;
  255. cmd = (struct ble_hci_cmd *) ble_hci_trans_buf_alloc(BLE_HCI_TRANS_BUF_CMD);
  256. memcpy((uint8_t *)cmd, data + 1, len - 1);
  257. ble_hci_trans_hs_cmd_tx((uint8_t *)cmd);
  258. }
  259. if (*(data) == DATA_TYPE_ACL) {
  260. struct os_mbuf *om = os_msys_get_pkthdr(0, 0);
  261. assert(om);
  262. memcpy(om->om_data, &data[1], len - 1);
  263. om->om_len = len - 1;
  264. OS_MBUF_PKTHDR(om)->omp_len = len - 1;
  265. ble_hci_trans_hs_acl_tx(om);
  266. }
  267. }
  268. esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback)
  269. {
  270. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
  271. return ESP_FAIL;
  272. }
  273. ble_hci_trans_cfg_hs(ble_hs_hci_rx_evt, NULL, ble_hs_rx_data, NULL);
  274. return ESP_OK;
  275. }
  276. #endif
  277. 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)
  278. {
  279. return (uint32_t)xTaskCreatePinnedToCore(task_func, name, stack_depth, param, prio, task_handle, (core_id < portNUM_PROCESSORS ? core_id : tskNO_AFFINITY));
  280. }
  281. static void task_delete_wrapper(void *task_handle)
  282. {
  283. vTaskDelete(task_handle);
  284. }
  285. #ifdef CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  286. static void hci_uart_start_tx_wrapper(int uart_no)
  287. {
  288. hci_uart_start_tx(uart_no);
  289. }
  290. static int hci_uart_init_cbs_wrapper(int uart_no, hci_uart_tx_char tx_func,
  291. hci_uart_tx_done tx_done, hci_uart_rx_char rx_func, void *arg)
  292. {
  293. int rc = -1;
  294. rc = hci_uart_init_cbs(uart_no, tx_func, tx_done, rx_func, arg);
  295. return rc;
  296. }
  297. static int hci_uart_config_wrapper(int port_num, int32_t baud_rate, uint8_t data_bits, uint8_t stop_bits,
  298. uart_parity_t parity, uart_hw_flowcontrol_t flow_ctl)
  299. {
  300. int rc = -1;
  301. rc = hci_uart_config(port_num, baud_rate, data_bits, stop_bits, parity, flow_ctl);
  302. return rc;
  303. }
  304. static int hci_uart_close_wrapper(int uart_no)
  305. {
  306. int rc = -1;
  307. rc = hci_uart_close(uart_no);
  308. return rc;
  309. }
  310. static void hci_uart_blocking_tx_wrapper(int port, uint8_t data)
  311. {
  312. //This function is nowhere to use.
  313. }
  314. static int hci_uart_init_wrapper(int uart_no, void *cfg)
  315. {
  316. //This function is nowhere to use.
  317. return 0;
  318. }
  319. #endif //CONFIG_BT_LE_HCI_INTERFACE_USE_UART
  320. static int ble_hci_unregistered_hook(void*, void*)
  321. {
  322. ESP_LOGD(NIMBLE_PORT_LOG_TAG,"%s ble hci rx_evt is not registered.",__func__);
  323. return 0;
  324. }
  325. static int esp_intr_alloc_wrapper(int source, int flags, intr_handler_t handler, void *arg, void **ret_handle_in)
  326. {
  327. int rc = esp_intr_alloc(source, flags, handler, arg, (intr_handle_t *)ret_handle_in);
  328. return rc;
  329. }
  330. static int esp_intr_free_wrapper(void **ret_handle)
  331. {
  332. int rc = 0;
  333. rc = esp_intr_free((intr_handle_t) * ret_handle);
  334. *ret_handle = NULL;
  335. return rc;
  336. }
  337. IRAM_ATTR void controller_sleep_cb(uint32_t enable_tick, void *arg)
  338. {
  339. esp_phy_disable();
  340. #ifdef CONFIG_PM_ENABLE
  341. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  342. uint32_t tick_invalid = *(uint32_t*)(arg);
  343. assert(arg != NULL);
  344. if(!tick_invalid) {
  345. uint32_t sleep_tick = r_os_cputime_get32();
  346. if(enable_tick <= sleep_tick) {
  347. return;
  348. }
  349. // start a timer to wake up and acquire the pm_lock before modem_sleep awakes
  350. uint32_t us_to_sleep = r_os_cputime_ticks_to_usecs(enable_tick - sleep_tick);
  351. assert(us_to_sleep > BTDM_MIN_TIMER_UNCERTAINTY_US);
  352. esp_err_t err = esp_timer_start_once(s_btdm_slp_tmr, us_to_sleep - BTDM_MIN_TIMER_UNCERTAINTY_US);
  353. if (err != ESP_OK) {
  354. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "ESP timer start failed\n");
  355. return;
  356. }
  357. }
  358. #endif // CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  359. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_BLE_RTC_TIMER
  360. r_ble_rtc_wake_up_state_clr();
  361. #endif
  362. if (s_pm_lock_acquired) {
  363. assert(s_pm_lock != NULL);
  364. esp_pm_lock_release(s_pm_lock);
  365. s_pm_lock_acquired = false;
  366. }
  367. #endif // CONFIG_PM_ENABLE
  368. }
  369. IRAM_ATTR void controller_wakeup_cb(void *arg)
  370. {
  371. esp_phy_enable();
  372. // need to check if need to call pm lock here
  373. #ifdef CONFIG_PM_ENABLE
  374. assert(s_pm_lock != NULL);
  375. if (!s_pm_lock_acquired) {
  376. s_pm_lock_acquired = true;
  377. esp_pm_lock_acquire(s_pm_lock);
  378. }
  379. #endif //CONFIG_PM_ENABLE
  380. }
  381. #ifdef CONFIG_PM_ENABLE
  382. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  383. static void btdm_slp_tmr_callback(void * arg)
  384. {
  385. (void)(arg);
  386. if (!s_pm_lock_acquired) {
  387. assert(s_pm_lock != NULL);
  388. s_pm_lock_acquired = true;
  389. esp_pm_lock_acquire(s_pm_lock);
  390. }
  391. }
  392. #endif // CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  393. #endif // CONFIG_PM_ENABLE
  394. void controller_sleep_init(void)
  395. {
  396. #ifdef CONFIG_PM_ENABLE
  397. s_btdm_allow_light_sleep = false;
  398. #endif // CONFIG_PM_ENABLE
  399. #ifdef CONFIG_BT_LE_SLEEP_ENABLE
  400. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "BLE modem sleep is enabled\n");
  401. r_ble_lll_rfmgmt_set_sleep_cb(controller_sleep_cb, controller_wakeup_cb, 0, 0, 500 + BLE_RTC_DELAY_US);
  402. #ifdef CONFIG_PM_ENABLE
  403. s_btdm_allow_light_sleep = true;
  404. esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_ON);
  405. #endif // CONFIG_PM_ENABLE
  406. #endif // CONFIG_BT_LE_SLEEP_ENABLE
  407. // enable light sleep
  408. #ifdef CONFIG_PM_ENABLE
  409. if (!s_btdm_allow_light_sleep) {
  410. if (esp_pm_lock_create(ESP_PM_NO_LIGHT_SLEEP, 0, "btnosleep", &s_light_sleep_pm_lock) != ESP_OK) {
  411. goto error;
  412. }
  413. }
  414. if (esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "bt", &s_pm_lock) != ESP_OK) {
  415. goto error;
  416. }
  417. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  418. esp_timer_create_args_t create_args = {
  419. .callback = btdm_slp_tmr_callback,
  420. .arg = NULL,
  421. .name = "btSlp"
  422. };
  423. if (esp_timer_create(&create_args, &s_btdm_slp_tmr) != ESP_OK) {
  424. goto error;
  425. }
  426. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "Enable light sleep, the wake up source is ESP timer");
  427. #endif //CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  428. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_BLE_RTC_TIMER
  429. esp_sleep_enable_bt_wakeup();
  430. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "Enable light sleep, the wake up source is BLE timer");
  431. #endif // CONFIG_BT_LE_WAKEUP_SOURCE_BLE_RTC_TIMER
  432. s_pm_lock_acquired = true;
  433. if (!s_btdm_allow_light_sleep) {
  434. esp_pm_lock_acquire(s_light_sleep_pm_lock);
  435. }
  436. if (s_pm_lock) {
  437. esp_pm_lock_acquire(s_pm_lock);
  438. }
  439. return;
  440. error:
  441. if (!s_btdm_allow_light_sleep) {
  442. if (s_light_sleep_pm_lock != NULL) {
  443. esp_pm_lock_delete(s_light_sleep_pm_lock);
  444. s_light_sleep_pm_lock = NULL;
  445. }
  446. }
  447. if (s_pm_lock != NULL) {
  448. esp_pm_lock_delete(s_pm_lock);
  449. s_pm_lock = NULL;
  450. }
  451. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  452. if (s_btdm_slp_tmr != NULL) {
  453. esp_timer_delete(s_btdm_slp_tmr);
  454. s_btdm_slp_tmr = NULL;
  455. }
  456. #endif // CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  457. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_BLE_RTC_TIMER
  458. esp_sleep_disable_bt_wakeup();
  459. #endif // CONFIG_BT_LE_WAKEUP_SOURCE_BLE_RTC_TIMER
  460. #endif //CONFIG_PM_ENABLE
  461. }
  462. void controller_sleep_deinit(void)
  463. {
  464. #ifdef CONFIG_PM_ENABLE
  465. if (!s_btdm_allow_light_sleep) {
  466. if (s_light_sleep_pm_lock != NULL) {
  467. esp_pm_lock_delete(s_light_sleep_pm_lock);
  468. s_light_sleep_pm_lock = NULL;
  469. }
  470. }
  471. if (s_pm_lock != NULL) {
  472. esp_pm_lock_delete(s_pm_lock);
  473. s_pm_lock = NULL;
  474. }
  475. #ifdef CONFIG_BT_LE_WAKEUP_SOURCE_CPU_RTC_TIMER
  476. if(s_btdm_slp_tmr != NULL) {
  477. esp_timer_stop(s_btdm_slp_tmr);
  478. esp_timer_delete(s_btdm_slp_tmr);
  479. s_btdm_slp_tmr = NULL;
  480. }
  481. #endif
  482. s_pm_lock_acquired = false;
  483. #endif
  484. }
  485. #if CONFIG_IDF_TARGET_ESP32H2_BETA_VERSION_2
  486. void periph_module_etm_active()
  487. {
  488. /*This part for esp32h2 beta2*/
  489. REG_SET_BIT(SYSTEM_MODCLK_CONF_REG, SYSTEM_ETM_CLK_SEL | SYSTEM_ETM_CLK_ACTIVE ); //Active ETM clock
  490. }
  491. #endif
  492. esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg)
  493. {
  494. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
  495. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller state");
  496. return ESP_FAIL;
  497. }
  498. if (cfg == NULL) {
  499. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "cfg is NULL");
  500. return ESP_ERR_INVALID_ARG;
  501. }
  502. if (esp_register_ext_funcs(&ext_funcs_ro) != 0) {
  503. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "register extend functions failed");
  504. return ESP_ERR_INVALID_ARG;
  505. }
  506. /* Initialize the function pointers for OS porting */
  507. npl_freertos_funcs_init();
  508. struct npl_funcs_t *p_npl_funcs = npl_freertos_funcs_get();
  509. if (!p_npl_funcs) {
  510. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "npl functions get failed");
  511. return ESP_ERR_INVALID_ARG;
  512. }
  513. if (esp_register_npl_funcs(p_npl_funcs) != 0) {
  514. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "npl functions register failed");
  515. return ESP_ERR_INVALID_ARG;
  516. }
  517. if (npl_freertos_mempool_init() != 0) {
  518. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "npl mempool init failed");
  519. return ESP_ERR_INVALID_ARG;
  520. }
  521. /* Initialize the global memory pool */
  522. if (os_msys_buf_alloc() != 0) {
  523. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "os msys alloc failed");
  524. return ESP_ERR_INVALID_ARG;
  525. }
  526. os_msys_init();
  527. #if CONFIG_BT_NIMBLE_ENABLED
  528. // ble_npl_eventq_init() need to use npl function in rom and must be called after esp_bt_controller_init()
  529. /* Initialize default event queue */
  530. ble_npl_eventq_init(nimble_port_get_dflt_eventq());
  531. #endif
  532. periph_module_enable(PERIPH_BT_MODULE);
  533. #if CONFIG_IDF_TARGET_ESP32H2_BETA_VERSION_2
  534. // only use for esp32h2 beta2
  535. periph_module_etm_active();
  536. #endif
  537. // init phy
  538. esp_phy_enable();
  539. // set bb delay
  540. bt_bb_set_le_tx_on_delay(50);
  541. if (ble_osi_coex_funcs_register((struct osi_coex_funcs_t *)&s_osi_coex_funcs_ro) != 0) {
  542. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "osi coex funcs reg failed");
  543. return ESP_ERR_INVALID_ARG;
  544. }
  545. #if CONFIG_SW_COEXIST_ENABLE
  546. coex_init();
  547. #endif
  548. int rc = ble_controller_init(cfg);
  549. if (rc != 0) {
  550. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "ble_controller_init failed %d", rc);
  551. return ESP_ERR_NO_MEM;
  552. }
  553. controller_sleep_init();
  554. uint8_t mac[6];
  555. ESP_ERROR_CHECK(esp_read_mac((uint8_t *)mac, ESP_MAC_BT));
  556. swap_in_place(mac, 6);
  557. esp_ble_ll_set_public_addr(mac);
  558. ble_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;
  559. ble_hci_trans_cfg_hs((ble_hci_trans_rx_cmd_fn *)ble_hci_unregistered_hook,NULL,
  560. (ble_hci_trans_rx_acl_fn *)ble_hci_unregistered_hook,NULL);
  561. return ESP_OK;
  562. }
  563. esp_err_t esp_bt_controller_deinit(void)
  564. {
  565. if ((ble_controller_status < ESP_BT_CONTROLLER_STATUS_INITED) || (ble_controller_status >= ESP_BT_CONTROLLER_STATUS_ENABLED)) {
  566. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller state");
  567. return ESP_FAIL;
  568. }
  569. controller_sleep_deinit();
  570. if (ble_controller_deinit() != 0) {
  571. return ESP_FAIL;
  572. }
  573. #if CONFIG_BT_NIMBLE_ENABLED
  574. /* De-initialize default event queue */
  575. ble_npl_eventq_deinit(nimble_port_get_dflt_eventq());
  576. #endif
  577. os_msys_buf_free();
  578. esp_unregister_npl_funcs();
  579. esp_unregister_ext_funcs();
  580. /* De-initialize npl functions */
  581. npl_freertos_funcs_deinit();
  582. npl_freertos_mempool_deinit();
  583. esp_phy_disable();
  584. ble_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;
  585. return ESP_OK;
  586. }
  587. esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode)
  588. {
  589. if (mode != ESP_BT_MODE_BLE) {
  590. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller mode");
  591. return ESP_FAIL;
  592. }
  593. if (ble_controller_status != ESP_BT_CONTROLLER_STATUS_INITED) {
  594. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller state");
  595. return ESP_FAIL;
  596. }
  597. #if CONFIG_SW_COEXIST_ENABLE
  598. coex_enable();
  599. #endif
  600. if (ble_controller_enable(mode) != 0) {
  601. return ESP_FAIL;
  602. }
  603. ble_controller_status = ESP_BT_CONTROLLER_STATUS_ENABLED;
  604. return ESP_OK;
  605. }
  606. esp_err_t esp_bt_controller_disable(void)
  607. {
  608. if (ble_controller_status < ESP_BT_CONTROLLER_STATUS_ENABLED) {
  609. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "invalid controller state");
  610. return ESP_FAIL;
  611. }
  612. if (ble_controller_disable() != 0) {
  613. return ESP_FAIL;
  614. }
  615. ble_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;
  616. return ESP_OK;
  617. }
  618. esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode)
  619. {
  620. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "%s not implemented, return OK", __func__);
  621. return ESP_OK;
  622. }
  623. esp_err_t esp_bt_mem_release(esp_bt_mode_t mode)
  624. {
  625. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "%s not implemented, return OK", __func__);
  626. return ESP_OK;
  627. }
  628. esp_bt_controller_status_t esp_bt_controller_get_status(void)
  629. {
  630. return ble_controller_status;
  631. }
  632. /* extra functions */
  633. esp_err_t esp_ble_tx_power_set(esp_ble_power_type_t power_type, esp_power_level_t power_level)
  634. {
  635. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "%s not implemented, return OK", __func__);
  636. return ESP_OK;
  637. }
  638. esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type)
  639. {
  640. ESP_LOGW(NIMBLE_PORT_LOG_TAG, "%s not implemented, return OK", __func__);
  641. return ESP_PWR_LVL_N0;
  642. }
  643. #if (!CONFIG_BT_NIMBLE_ENABLED) && (CONFIG_BT_CONTROLLER_ENABLED == true)
  644. #define BLE_SM_KEY_ERR 0x17
  645. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  646. #include "mbedtls/aes.h"
  647. #if CONFIG_BT_LE_SM_SC
  648. #include "mbedtls/cipher.h"
  649. #include "mbedtls/entropy.h"
  650. #include "mbedtls/ctr_drbg.h"
  651. #include "mbedtls/cmac.h"
  652. #include "mbedtls/ecdh.h"
  653. #include "mbedtls/ecp.h"
  654. #endif
  655. #else
  656. #include "tinycrypt/aes.h"
  657. #include "tinycrypt/constants.h"
  658. #include "tinycrypt/utils.h"
  659. #if CONFIG_BT_LE_SM_SC
  660. #include "tinycrypt/cmac_mode.h"
  661. #include "tinycrypt/ecc_dh.h"
  662. #endif
  663. #endif
  664. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  665. #if CONFIG_BT_LE_SM_SC
  666. static mbedtls_ecp_keypair keypair;
  667. #endif
  668. #endif
  669. int ble_sm_alg_gen_dhkey(const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_key_y,
  670. const uint8_t *our_priv_key, uint8_t *out_dhkey)
  671. {
  672. uint8_t dh[32];
  673. uint8_t pk[64];
  674. uint8_t priv[32];
  675. int rc = BLE_SM_KEY_ERR;
  676. swap_buf(pk, peer_pub_key_x, 32);
  677. swap_buf(&pk[32], peer_pub_key_y, 32);
  678. swap_buf(priv, our_priv_key, 32);
  679. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  680. struct mbedtls_ecp_point pt = {0}, Q = {0};
  681. mbedtls_mpi z = {0}, d = {0};
  682. mbedtls_ctr_drbg_context ctr_drbg = {0};
  683. mbedtls_entropy_context entropy = {0};
  684. uint8_t pub[65] = {0};
  685. /* Hardcoded first byte of pub key for MBEDTLS_ECP_PF_UNCOMPRESSED */
  686. pub[0] = 0x04;
  687. memcpy(&pub[1], pk, 64);
  688. /* Initialize the required structures here */
  689. mbedtls_ecp_point_init(&pt);
  690. mbedtls_ecp_point_init(&Q);
  691. mbedtls_ctr_drbg_init(&ctr_drbg);
  692. mbedtls_entropy_init(&entropy);
  693. mbedtls_mpi_init(&d);
  694. mbedtls_mpi_init(&z);
  695. /* Below 3 steps are to validate public key on curve secp256r1 */
  696. if (mbedtls_ecp_group_load(&keypair.MBEDTLS_PRIVATE(grp), MBEDTLS_ECP_DP_SECP256R1) != 0) {
  697. goto exit;
  698. }
  699. if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &pt, pub, 65) != 0) {
  700. goto exit;
  701. }
  702. if (mbedtls_ecp_check_pubkey(&keypair.MBEDTLS_PRIVATE(grp), &pt) != 0) {
  703. goto exit;
  704. }
  705. /* Set PRNG */
  706. if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  707. NULL, 0)) != 0) {
  708. goto exit;
  709. }
  710. /* Prepare point Q from pub key */
  711. if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &Q, pub, 65) != 0) {
  712. goto exit;
  713. }
  714. if (mbedtls_mpi_read_binary(&d, priv, 32) != 0) {
  715. goto exit;
  716. }
  717. rc = mbedtls_ecdh_compute_shared(&keypair.MBEDTLS_PRIVATE(grp), &z, &Q, &d,
  718. mbedtls_ctr_drbg_random, &ctr_drbg);
  719. if (rc != 0) {
  720. goto exit;
  721. }
  722. rc = mbedtls_mpi_write_binary(&z, dh, 32);
  723. if (rc != 0) {
  724. goto exit;
  725. }
  726. exit:
  727. mbedtls_ecp_point_free(&pt);
  728. mbedtls_mpi_free(&z);
  729. mbedtls_mpi_free(&d);
  730. mbedtls_ecp_point_free(&Q);
  731. mbedtls_entropy_free(&entropy);
  732. mbedtls_ctr_drbg_free(&ctr_drbg);
  733. if (rc != 0) {
  734. return BLE_SM_KEY_ERR;
  735. }
  736. #else
  737. if (uECC_valid_public_key(pk, &curve_secp256r1) < 0) {
  738. return BLE_SM_KEY_ERR;
  739. }
  740. rc = uECC_shared_secret(pk, priv, dh, &curve_secp256r1);
  741. if (rc == TC_CRYPTO_FAIL) {
  742. return BLE_SM_KEY_ERR;
  743. }
  744. #endif
  745. swap_buf(out_dhkey, dh, 32);
  746. return 0;
  747. }
  748. /* based on Core Specification 4.2 Vol 3. Part H 2.3.5.6.1 */
  749. static const uint8_t ble_sm_alg_dbg_priv_key[32] = {
  750. 0x3f, 0x49, 0xf6, 0xd4, 0xa3, 0xc5, 0x5f, 0x38, 0x74, 0xc9, 0xb3, 0xe3,
  751. 0xd2, 0x10, 0x3f, 0x50, 0x4a, 0xff, 0x60, 0x7b, 0xeb, 0x40, 0xb7, 0x99,
  752. 0x58, 0x99, 0xb8, 0xa6, 0xcd, 0x3c, 0x1a, 0xbd
  753. };
  754. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  755. static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key)
  756. {
  757. int rc = BLE_SM_KEY_ERR;
  758. mbedtls_entropy_context entropy = {0};
  759. mbedtls_ctr_drbg_context ctr_drbg = {0};
  760. mbedtls_entropy_init(&entropy);
  761. mbedtls_ctr_drbg_init(&ctr_drbg);
  762. mbedtls_ecp_keypair_init(&keypair);
  763. if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  764. NULL, 0)) != 0) {
  765. goto exit;
  766. }
  767. if ((rc = mbedtls_ecp_gen_key(MBEDTLS_ECP_DP_SECP256R1, &keypair,
  768. mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
  769. goto exit;
  770. }
  771. if ((rc = mbedtls_mpi_write_binary(&keypair.MBEDTLS_PRIVATE(d), private_key, 32)) != 0) {
  772. goto exit;
  773. }
  774. size_t olen = 0;
  775. uint8_t pub[65] = {0};
  776. if ((rc = mbedtls_ecp_point_write_binary(&keypair.MBEDTLS_PRIVATE(grp), &keypair.MBEDTLS_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED,
  777. &olen, pub, 65)) != 0) {
  778. goto exit;
  779. }
  780. memcpy(public_key, &pub[1], 64);
  781. exit:
  782. mbedtls_ctr_drbg_free(&ctr_drbg);
  783. mbedtls_entropy_free(&entropy);
  784. if (rc != 0) {
  785. mbedtls_ecp_keypair_free(&keypair);
  786. return BLE_SM_KEY_ERR;
  787. }
  788. return 0;
  789. }
  790. #endif
  791. /**
  792. * pub: 64 bytes
  793. * priv: 32 bytes
  794. */
  795. int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv)
  796. {
  797. #if CONFIG_BT_LE_SM_SC_DEBUG_KEYS
  798. swap_buf(pub, ble_sm_alg_dbg_pub_key, 32);
  799. swap_buf(&pub[32], &ble_sm_alg_dbg_pub_key[32], 32);
  800. swap_buf(priv, ble_sm_alg_dbg_priv_key, 32);
  801. #else
  802. uint8_t pk[64];
  803. do {
  804. #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
  805. if (mbedtls_gen_keypair(pk, priv) != 0) {
  806. return BLE_SM_KEY_ERR;
  807. }
  808. #else
  809. if (uECC_make_key(pk, priv, &curve_secp256r1) != TC_CRYPTO_SUCCESS) {
  810. return BLE_SM_KEY_ERR;
  811. }
  812. #endif
  813. /* Make sure generated key isn't debug key. */
  814. } while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0);
  815. swap_buf(pub, pk, 32);
  816. swap_buf(&pub[32], &pk[32], 32);
  817. swap_in_place(priv, 32);
  818. #endif
  819. return 0;
  820. }
  821. #endif