bt.c 30 KB

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