bt.c 34 KB

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