bt.c 30 KB

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