• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <stddef.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 
20 #include "sdkconfig.h"
21 #include "esp_heap_caps.h"
22 #include "esp_heap_caps_init.h"
23 #include "esp_osal/esp_osal.h"
24 #include "esp_osal/task.h"
25 #include "esp_osal/queue.h"
26 #include "esp_osal/semphr.h"
27 #include "esp_osal/xtensa_api.h"
28 #include "esp_osal/portmacro.h"
29 #include "xtensa/core-macros.h"
30 #include "esp_types.h"
31 #include "esp_system.h"
32 #include "esp_task.h"
33 #include "esp_intr_alloc.h"
34 #include "esp_attr.h"
35 #include "esp_phy_init.h"
36 #include "esp_bt.h"
37 #include "esp_err.h"
38 #include "esp_log.h"
39 #include "driver/periph_ctrl.h"
40 #include "soc/rtc.h"
41 #include "soc/soc_memory_layout.h"
42 #include "esp32/clk.h"
43 #include "esp_coexist_internal.h"
44 #if !CONFIG_FREERTOS_UNICORE
45 #include "esp_ipc.h"
46 #endif
47 
48 #include "esp_rom_sys.h"
49 
50 #if CONFIG_BT_ENABLED
51 
52 /* Macro definition
53  ************************************************************************
54  */
55 
56 #define BTDM_LOG_TAG                        "BTDM_INIT"
57 
58 #define BTDM_INIT_PERIOD                    (5000)    /* ms */
59 
60 /* Bluetooth system and controller config */
61 #define BTDM_CFG_BT_DATA_RELEASE            (1<<0)
62 #define BTDM_CFG_HCI_UART                   (1<<1)
63 #define BTDM_CFG_CONTROLLER_RUN_APP_CPU     (1<<2)
64 #define BTDM_CFG_SCAN_DUPLICATE_OPTIONS     (1<<3)
65 #define BTDM_CFG_SEND_ADV_RESERVED_SIZE     (1<<4)
66 #define BTDM_CFG_BLE_FULL_SCAN_SUPPORTED    (1<<5)
67 
68 /* Sleep mode */
69 #define BTDM_MODEM_SLEEP_MODE_NONE          (0)
70 #define BTDM_MODEM_SLEEP_MODE_ORIG          (1)
71 #define BTDM_MODEM_SLEEP_MODE_EVED          (2)  // sleep mode for BLE controller, used only for internal test.
72 
73 /* Low Power Clock Selection */
74 #define BTDM_LPCLK_SEL_XTAL      (0)
75 #define BTDM_LPCLK_SEL_XTAL32K   (1)
76 #define BTDM_LPCLK_SEL_RTC_SLOW  (2)
77 #define BTDM_LPCLK_SEL_8M        (3)
78 
79 /* Sleep and wakeup interval control */
80 #define BTDM_MIN_SLEEP_DURATION          (12) // threshold of interval in slots to allow to fall into modem sleep
81 #define BTDM_MODEM_WAKE_UP_DELAY         (4)  // delay in slots of modem wake up procedure, including re-enable PHY/RF
82 
83 #define BT_DEBUG(...)
84 #define BT_API_CALL_CHECK(info, api_call, ret) \
85 do{\
86     esp_err_t __err = (api_call);\
87     if ((ret) != __err) {\
88         BT_DEBUG("%s %d %s ret=0x%X\n", __FUNCTION__, __LINE__, (info), __err);\
89         return __err;\
90     }\
91 } while(0)
92 
93 #define OSI_FUNCS_TIME_BLOCKING  0xffffffff
94 #define OSI_VERSION              0x00010002
95 #define OSI_MAGIC_VALUE          0xFADEBEAD
96 
97 /* SPIRAM Configuration */
98 #if CONFIG_SPIRAM_USE_MALLOC
99 #define BTDM_MAX_QUEUE_NUM       (5)
100 #endif
101 
102 /* Types definition
103  ************************************************************************
104  */
105 
106 /* VHCI function interface */
107 typedef struct vhci_host_callback {
108     void (*notify_host_send_available)(void);               /*!< callback used to notify that the host can send packet to controller */
109     int (*notify_host_recv)(uint8_t *data, uint16_t len);   /*!< callback used to notify that the controller has a packet to send to the host*/
110 } vhci_host_callback_t;
111 
112 /* Dram region */
113 typedef struct {
114     esp_bt_mode_t mode;
115     intptr_t start;
116     intptr_t end;
117 } btdm_dram_available_region_t;
118 
119 /* PSRAM configuration */
120 #if CONFIG_SPIRAM_USE_MALLOC
121 typedef struct {
122     QueueHandle_t handle;
123     void *storage;
124     void *buffer;
125 } btdm_queue_item_t;
126 #endif
127 
128 /* OSI function */
129 struct osi_funcs_t {
130     uint32_t _version;
131     xt_handler (*_set_isr)(int n, xt_handler f, void *arg);
132     void (*_ints_on)(unsigned int mask);
133     void (*_interrupt_disable)(void);
134     void (*_interrupt_restore)(void);
135     void (*_task_yield)(void);
136     void (*_task_yield_from_isr)(void);
137     void *(*_semphr_create)(uint32_t max, uint32_t init);
138     void (*_semphr_delete)(void *semphr);
139     int32_t (*_semphr_take_from_isr)(void *semphr, void *hptw);
140     int32_t (*_semphr_give_from_isr)(void *semphr, void *hptw);
141     int32_t (*_semphr_take)(void *semphr, uint32_t block_time_ms);
142     int32_t (*_semphr_give)(void *semphr);
143     void *(*_mutex_create)(void);
144     void (*_mutex_delete)(void *mutex);
145     int32_t (*_mutex_lock)(void *mutex);
146     int32_t (*_mutex_unlock)(void *mutex);
147     void *(* _queue_create)(uint32_t queue_len, uint32_t item_size);
148     void (* _queue_delete)(void *queue);
149     int32_t (* _queue_send)(void *queue, void *item, uint32_t block_time_ms);
150     int32_t (* _queue_send_from_isr)(void *queue, void *item, void *hptw);
151     int32_t (* _queue_recv)(void *queue, void *item, uint32_t block_time_ms);
152     int32_t (* _queue_recv_from_isr)(void *queue, void *item, void *hptw);
153     int32_t (* _task_create)(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle, uint32_t core_id);
154     void (* _task_delete)(void *task_handle);
155     bool (* _is_in_isr)(void);
156     int (* _cause_sw_intr_to_core)(int core_id, int intr_no);
157     void *(* _malloc)(uint32_t size);
158     void *(* _malloc_internal)(uint32_t size);
159     void (* _free)(void *p);
160     int32_t (* _read_efuse_mac)(uint8_t mac[6]);
161     void (* _srand)(unsigned int seed);
162     int (* _rand)(void);
163     uint32_t (* _btdm_lpcycles_2_us)(uint32_t cycles);
164     uint32_t (* _btdm_us_2_lpcycles)(uint32_t us);
165     bool (* _btdm_sleep_check_duration)(uint32_t *slot_cnt);
166     void (* _btdm_sleep_enter_phase1)(uint32_t lpcycles);  /* called when interrupt is disabled */
167     void (* _btdm_sleep_enter_phase2)(void);
168     void (* _btdm_sleep_exit_phase1)(void);  /* called from ISR */
169     void (* _btdm_sleep_exit_phase2)(void);  /* called from ISR */
170     void (* _btdm_sleep_exit_phase3)(void);  /* called from task */
171     bool (* _coex_bt_wakeup_request)(void);
172     void (* _coex_bt_wakeup_request_end)(void);
173     int (* _coex_bt_request)(uint32_t event, uint32_t latency, uint32_t duration);
174     int (* _coex_bt_release)(uint32_t event);
175     int (* _coex_register_bt_cb)(coex_func_cb_t cb);
176     uint32_t (* _coex_bb_reset_lock)(void);
177     void (* _coex_bb_reset_unlock)(uint32_t restore);
178     int (* _coex_schm_register_btdm_callback)(void *callback);
179     void (* _coex_schm_status_bit_clear)(uint32_t type, uint32_t status);
180     void (* _coex_schm_status_bit_set)(uint32_t type, uint32_t status);
181     uint32_t (* _coex_schm_interval_get)(void);
182     uint8_t (* _coex_schm_curr_period_get)(void);
183     void *(* _coex_schm_curr_phase_get)(void);
184     int (* _coex_wifi_channel_get)(uint8_t *primary, uint8_t *secondary);
185     int (* _coex_register_wifi_channel_change_callback)(void *cb);
186     uint32_t _magic;
187 };
188 
189 typedef void (*workitem_handler_t)(void* arg);
190 
191 /* External functions or values
192  ************************************************************************
193  */
194 
195 /* not for user call, so don't put to include file */
196 /* OSI */
197 extern int btdm_osi_funcs_register(void *osi_funcs);
198 /* Initialise and De-initialise */
199 extern int btdm_controller_init(uint32_t config_mask, esp_bt_controller_config_t *config_opts);
200 extern void btdm_controller_deinit(void);
201 extern int btdm_controller_enable(esp_bt_mode_t mode);
202 extern void btdm_controller_disable(void);
203 extern uint8_t btdm_controller_get_mode(void);
204 extern const char *btdm_controller_get_compile_version(void);
205 extern void btdm_rf_bb_init_phase2(void); // shall be called after PHY/RF is enabled
206 extern int btdm_dispatch_work_to_controller(workitem_handler_t callback, void *arg, bool blocking);
207 /* Sleep */
208 extern void btdm_controller_enable_sleep(bool enable);
209 extern void btdm_controller_set_sleep_mode(uint8_t mode);
210 extern uint8_t btdm_controller_get_sleep_mode(void);
211 extern bool btdm_power_state_active(void);
212 extern void btdm_wakeup_request(void);
213 extern void btdm_in_wakeup_requesting_set(bool in_wakeup_requesting);
214 /* Low Power Clock */
215 extern bool btdm_lpclk_select_src(uint32_t sel);
216 extern bool btdm_lpclk_set_div(uint32_t div);
217 /* VHCI */
218 extern bool API_vhci_host_check_send_available(void);
219 extern void API_vhci_host_send_packet(uint8_t *data, uint16_t len);
220 extern int API_vhci_host_register_callback(const vhci_host_callback_t *callback);
221 /* TX power */
222 extern int ble_txpwr_set(int power_type, int power_level);
223 extern int ble_txpwr_get(int power_type);
224 extern int bredr_txpwr_set(int min_power_level, int max_power_level);
225 extern int bredr_txpwr_get(int *min_power_level, int *max_power_level);
226 extern void bredr_sco_datapath_set(uint8_t data_path);
227 extern void btdm_controller_scan_duplicate_list_clear(void);
228 /* Coexistence */
229 extern int coex_bt_request(uint32_t event, uint32_t latency, uint32_t duration);
230 extern int coex_bt_release(uint32_t event);
231 extern int coex_register_bt_cb(coex_func_cb_t cb);
232 extern uint32_t coex_bb_reset_lock(void);
233 extern void coex_bb_reset_unlock(uint32_t restore);
234 extern int coex_schm_register_btdm_callback(void *callback);
235 extern void coex_schm_status_bit_clear(uint32_t type, uint32_t status);
236 extern void coex_schm_status_bit_set(uint32_t type, uint32_t status);
237 extern uint32_t coex_schm_interval_get(void);
238 extern uint8_t coex_schm_curr_period_get(void);
239 extern void * coex_schm_curr_phase_get(void);
240 extern int coex_wifi_channel_get(uint8_t *primary, uint8_t *secondary);
241 extern int coex_register_wifi_channel_change_callback(void *cb);
242 
243 extern char _bss_start_btdm;
244 extern char _bss_end_btdm;
245 extern char _data_start_btdm;
246 extern char _data_end_btdm;
247 extern uint32_t _data_start_btdm_rom;
248 extern uint32_t _data_end_btdm_rom;
249 
250 extern uint32_t _bt_bss_start;
251 extern uint32_t _bt_bss_end;
252 extern uint32_t _nimble_bss_start;
253 extern uint32_t _nimble_bss_end;
254 extern uint32_t _btdm_bss_start;
255 extern uint32_t _btdm_bss_end;
256 extern uint32_t _bt_data_start;
257 extern uint32_t _bt_data_end;
258 extern uint32_t _nimble_data_start;
259 extern uint32_t _nimble_data_end;
260 extern uint32_t _btdm_data_start;
261 extern uint32_t _btdm_data_end;
262 
263 /* Local Function Declare
264  *********************************************************************
265  */
266 #if CONFIG_SPIRAM_USE_MALLOC
267 static bool btdm_queue_generic_register(const btdm_queue_item_t *queue);
268 static bool btdm_queue_generic_deregister(btdm_queue_item_t *queue);
269 #endif /* CONFIG_SPIRAM_USE_MALLOC */
270 static void IRAM_ATTR interrupt_disable(void);
271 static void IRAM_ATTR interrupt_restore(void);
272 static void IRAM_ATTR task_yield_from_isr(void);
273 static void *semphr_create_wrapper(uint32_t max, uint32_t init);
274 static void semphr_delete_wrapper(void *semphr);
275 static int32_t IRAM_ATTR semphr_take_from_isr_wrapper(void *semphr, void *hptw);
276 static int32_t IRAM_ATTR semphr_give_from_isr_wrapper(void *semphr, void *hptw);
277 static int32_t  semphr_take_wrapper(void *semphr, uint32_t block_time_ms);
278 static int32_t  semphr_give_wrapper(void *semphr);
279 static void *mutex_create_wrapper(void);
280 static void mutex_delete_wrapper(void *mutex);
281 static int32_t mutex_lock_wrapper(void *mutex);
282 static int32_t mutex_unlock_wrapper(void *mutex);
283 static void *queue_create_wrapper(uint32_t queue_len, uint32_t item_size);
284 static void queue_delete_wrapper(void *queue);
285 static int32_t queue_send_wrapper(void *queue, void *item, uint32_t block_time_ms);
286 static int32_t IRAM_ATTR queue_send_from_isr_wrapper(void *queue, void *item, void *hptw);
287 static int32_t queue_recv_wrapper(void *queue, void *item, uint32_t block_time_ms);
288 static int32_t IRAM_ATTR queue_recv_from_isr_wrapper(void *queue, void *item, void *hptw);
289 static int32_t 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 static void task_delete_wrapper(void *task_handle);
291 static bool IRAM_ATTR is_in_isr_wrapper(void);
292 static void IRAM_ATTR cause_sw_intr(void *arg);
293 static int IRAM_ATTR cause_sw_intr_to_core_wrapper(int core_id, int intr_no);
294 static void *malloc_internal_wrapper(size_t size);
295 static int32_t IRAM_ATTR read_mac_wrapper(uint8_t mac[6]);
296 static void IRAM_ATTR srand_wrapper(unsigned int seed);
297 static int IRAM_ATTR rand_wrapper(void);
298 static uint32_t IRAM_ATTR btdm_lpcycles_2_us(uint32_t cycles);
299 static uint32_t IRAM_ATTR btdm_us_2_lpcycles(uint32_t us);
300 static bool IRAM_ATTR btdm_sleep_check_duration(uint32_t *slot_cnt);
301 static void btdm_sleep_enter_phase1_wrapper(uint32_t lpcycles);
302 static void btdm_sleep_enter_phase2_wrapper(void);
303 static void btdm_sleep_exit_phase3_wrapper(void);
304 static bool coex_bt_wakeup_request(void);
305 static void coex_bt_wakeup_request_end(void);
306 static int coex_bt_request_wrapper(uint32_t event, uint32_t latency, uint32_t duration);
307 static int coex_bt_release_wrapper(uint32_t event);
308 static int coex_register_bt_cb_wrapper(coex_func_cb_t cb);
309 static uint32_t coex_bb_reset_lock_wrapper(void);
310 static void coex_bb_reset_unlock_wrapper(uint32_t restore);
311 static int coex_schm_register_btdm_callback_wrapper(void *callback);
312 static void coex_schm_status_bit_clear_wrapper(uint32_t type, uint32_t status);
313 static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status);
314 static uint32_t coex_schm_interval_get_wrapper(void);
315 static uint8_t coex_schm_curr_period_get_wrapper(void);
316 static void * coex_schm_curr_phase_get_wrapper(void);
317 static int coex_wifi_channel_get_wrapper(uint8_t *primary, uint8_t *secondary);
318 static int coex_register_wifi_channel_change_callback_wrapper(void *cb);
319 /* Local variable definition
320  ***************************************************************************
321  */
322 /* OSI funcs */
323 static const struct osi_funcs_t osi_funcs_ro = {
324     ._version = OSI_VERSION,
325     ._set_isr = xt_set_interrupt_handler,
326     ._ints_on = xt_ints_on,
327     ._interrupt_disable = interrupt_disable,
328     ._interrupt_restore = interrupt_restore,
329     ._task_yield = vPortYield,
330     ._task_yield_from_isr = task_yield_from_isr,
331     ._semphr_create = semphr_create_wrapper,
332     ._semphr_delete = semphr_delete_wrapper,
333     ._semphr_take_from_isr = semphr_take_from_isr_wrapper,
334     ._semphr_give_from_isr = semphr_give_from_isr_wrapper,
335     ._semphr_take = semphr_take_wrapper,
336     ._semphr_give = semphr_give_wrapper,
337     ._mutex_create = mutex_create_wrapper,
338     ._mutex_delete = mutex_delete_wrapper,
339     ._mutex_lock = mutex_lock_wrapper,
340     ._mutex_unlock = mutex_unlock_wrapper,
341     ._queue_create = queue_create_wrapper,
342     ._queue_delete = queue_delete_wrapper,
343     ._queue_send = queue_send_wrapper,
344     ._queue_send_from_isr = queue_send_from_isr_wrapper,
345     ._queue_recv = queue_recv_wrapper,
346     ._queue_recv_from_isr = queue_recv_from_isr_wrapper,
347     ._task_create = task_create_wrapper,
348     ._task_delete = task_delete_wrapper,
349     ._is_in_isr = is_in_isr_wrapper,
350     ._cause_sw_intr_to_core = cause_sw_intr_to_core_wrapper,
351     ._malloc = malloc,
352     ._malloc_internal = malloc_internal_wrapper,
353     ._free = free,
354     ._read_efuse_mac = read_mac_wrapper,
355     ._srand = srand_wrapper,
356     ._rand = rand_wrapper,
357     ._btdm_lpcycles_2_us = btdm_lpcycles_2_us,
358     ._btdm_us_2_lpcycles = btdm_us_2_lpcycles,
359     ._btdm_sleep_check_duration = btdm_sleep_check_duration,
360     ._btdm_sleep_enter_phase1 = btdm_sleep_enter_phase1_wrapper,
361     ._btdm_sleep_enter_phase2 = btdm_sleep_enter_phase2_wrapper,
362     ._btdm_sleep_exit_phase1 = NULL,
363     ._btdm_sleep_exit_phase2 = NULL,
364     ._btdm_sleep_exit_phase3 = btdm_sleep_exit_phase3_wrapper,
365     ._coex_bt_wakeup_request = coex_bt_wakeup_request,
366     ._coex_bt_wakeup_request_end = coex_bt_wakeup_request_end,
367     ._coex_bt_request = coex_bt_request_wrapper,
368     ._coex_bt_release = coex_bt_release_wrapper,
369     ._coex_register_bt_cb = coex_register_bt_cb_wrapper,
370     ._coex_bb_reset_lock = coex_bb_reset_lock_wrapper,
371     ._coex_bb_reset_unlock = coex_bb_reset_unlock_wrapper,
372     ._coex_schm_register_btdm_callback = coex_schm_register_btdm_callback_wrapper,
373     ._coex_schm_status_bit_clear = coex_schm_status_bit_clear_wrapper,
374     ._coex_schm_status_bit_set = coex_schm_status_bit_set_wrapper,
375     ._coex_schm_interval_get = coex_schm_interval_get_wrapper,
376     ._coex_schm_curr_period_get = coex_schm_curr_period_get_wrapper,
377     ._coex_schm_curr_phase_get = coex_schm_curr_phase_get_wrapper,
378     ._coex_wifi_channel_get = coex_wifi_channel_get_wrapper,
379     ._coex_register_wifi_channel_change_callback = coex_register_wifi_channel_change_callback_wrapper,
380     ._magic = OSI_MAGIC_VALUE,
381 };
382 
383 /* the mode column will be modified by release function to indicate the available region */
384 static btdm_dram_available_region_t btdm_dram_available_region[] = {
385     //following is .data
386     {ESP_BT_MODE_BTDM,          SOC_MEM_BT_DATA_START,      SOC_MEM_BT_DATA_END         },
387     //following is memory which HW will use
388     {ESP_BT_MODE_BTDM,          SOC_MEM_BT_EM_BTDM0_START,  SOC_MEM_BT_EM_BTDM0_END     },
389     {ESP_BT_MODE_BLE,           SOC_MEM_BT_EM_BLE_START,    SOC_MEM_BT_EM_BLE_END      },
390     {ESP_BT_MODE_BTDM,          SOC_MEM_BT_EM_BTDM1_START,  SOC_MEM_BT_EM_BTDM1_END     },
391     {ESP_BT_MODE_CLASSIC_BT,    SOC_MEM_BT_EM_BREDR_START,  SOC_MEM_BT_EM_BREDR_REAL_END},
392     //following is .bss
393     {ESP_BT_MODE_BTDM,          SOC_MEM_BT_BSS_START,       SOC_MEM_BT_BSS_END          },
394     {ESP_BT_MODE_BTDM,          SOC_MEM_BT_MISC_START,      SOC_MEM_BT_MISC_END         },
395 };
396 
397 /* Reserve the full memory region used by Bluetooth Controller,
398  *    some may be released later at runtime. */
399 SOC_RESERVE_MEMORY_REGION(SOC_MEM_BT_EM_START,   SOC_MEM_BT_EM_BREDR_REAL_END,  rom_bt_em);
400 SOC_RESERVE_MEMORY_REGION(SOC_MEM_BT_BSS_START,  SOC_MEM_BT_BSS_END,            rom_bt_bss);
401 SOC_RESERVE_MEMORY_REGION(SOC_MEM_BT_MISC_START, SOC_MEM_BT_MISC_END,           rom_bt_misc);
402 SOC_RESERVE_MEMORY_REGION(SOC_MEM_BT_DATA_START, SOC_MEM_BT_DATA_END,           rom_bt_data);
403 
404 static DRAM_ATTR struct osi_funcs_t *osi_funcs_p;
405 
406 #if CONFIG_SPIRAM_USE_MALLOC
407 static DRAM_ATTR btdm_queue_item_t btdm_queue_table[BTDM_MAX_QUEUE_NUM];
408 static DRAM_ATTR SemaphoreHandle_t btdm_queue_table_mux = NULL;
409 #endif /* #if CONFIG_SPIRAM_USE_MALLOC */
410 
411 /* Static variable declare */
412 // timestamp when PHY/RF was switched on
413 static DRAM_ATTR int64_t s_time_phy_rf_just_enabled = 0;
414 static DRAM_ATTR esp_bt_controller_status_t btdm_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;
415 
416 static DRAM_ATTR portMUX_TYPE global_int_mux = portMUX_INITIALIZER_UNLOCKED;
417 
418 // measured average low power clock period in micro seconds
419 static DRAM_ATTR uint32_t btdm_lpcycle_us = 0;
420 static DRAM_ATTR uint8_t btdm_lpcycle_us_frac = 0; // number of fractional bit for btdm_lpcycle_us
421 
422 #if CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE_ORIG
423 // used low power clock
424 static DRAM_ATTR uint8_t btdm_lpclk_sel;
425 #endif /* #ifdef CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE_ORIG */
426 
427 static DRAM_ATTR QueueHandle_t s_wakeup_req_sem = NULL;
428 #ifdef CONFIG_PM_ENABLE
429 static DRAM_ATTR esp_timer_handle_t s_btdm_slp_tmr;
430 static DRAM_ATTR esp_pm_lock_handle_t s_pm_lock;
431 static bool s_pm_lock_acquired = true;
432 static DRAM_ATTR bool s_btdm_allow_light_sleep;
433 // pm_lock to prevent light sleep when using main crystal as Bluetooth low power clock
434 static DRAM_ATTR esp_pm_lock_handle_t s_light_sleep_pm_lock;
435 static void btdm_slp_tmr_callback(void *arg);
436 #endif /* #ifdef CONFIG_PM_ENABLE */
437 
438 
btdm_check_and_init_bb(void)439 static inline void btdm_check_and_init_bb(void)
440 {
441     /* init BT-BB if PHY/RF has been switched off since last BT-BB init */
442     int64_t latest_ts = esp_phy_rf_get_on_ts();
443     if (latest_ts != s_time_phy_rf_just_enabled ||
444         s_time_phy_rf_just_enabled == 0) {
445         btdm_rf_bb_init_phase2();
446         s_time_phy_rf_just_enabled = latest_ts;
447     }
448 }
449 
450 #if CONFIG_SPIRAM_USE_MALLOC
btdm_queue_generic_register(const btdm_queue_item_t * queue)451 static bool btdm_queue_generic_register(const btdm_queue_item_t *queue)
452 {
453     if (!btdm_queue_table_mux || !queue) {
454         return NULL;
455     }
456 
457     bool ret = false;
458     btdm_queue_item_t *item;
459     xSemaphoreTake(btdm_queue_table_mux, portMAX_DELAY);
460     for (int i = 0; i < BTDM_MAX_QUEUE_NUM; ++i) {
461         item = &btdm_queue_table[i];
462         if (item->handle == NULL) {
463             memcpy(item, queue, sizeof(btdm_queue_item_t));
464             ret = true;
465             break;
466         }
467     }
468     xSemaphoreGive(btdm_queue_table_mux);
469     return ret;
470 }
471 
btdm_queue_generic_deregister(btdm_queue_item_t * queue)472 static bool btdm_queue_generic_deregister(btdm_queue_item_t *queue)
473 {
474     if (!btdm_queue_table_mux || !queue) {
475         return false;
476     }
477 
478     bool ret = false;
479     btdm_queue_item_t *item;
480     xSemaphoreTake(btdm_queue_table_mux, portMAX_DELAY);
481     for (int i = 0; i < BTDM_MAX_QUEUE_NUM; ++i) {
482         item = &btdm_queue_table[i];
483         if (item->handle == queue->handle) {
484             memcpy(queue, item, sizeof(btdm_queue_item_t));
485             memset(item, 0, sizeof(btdm_queue_item_t));
486             ret = true;
487             break;
488         }
489     }
490     xSemaphoreGive(btdm_queue_table_mux);
491     return ret;
492 }
493 
494 #endif /* CONFIG_SPIRAM_USE_MALLOC */
495 
interrupt_disable(void)496 static void IRAM_ATTR interrupt_disable(void)
497 {
498     if (xPortInIsrContext()) {
499         portENTER_CRITICAL_ISR(&global_int_mux);
500     } else {
501         portENTER_CRITICAL(&global_int_mux);
502     }
503 }
504 
interrupt_restore(void)505 static void IRAM_ATTR interrupt_restore(void)
506 {
507     if (xPortInIsrContext()) {
508         portEXIT_CRITICAL_ISR(&global_int_mux);
509     } else {
510         portEXIT_CRITICAL(&global_int_mux);
511     }
512 }
513 
task_yield_from_isr(void)514 static void IRAM_ATTR task_yield_from_isr(void)
515 {
516     portYIELD_FROM_ISR();
517 }
518 
semphr_create_wrapper(uint32_t max,uint32_t init)519 static void *semphr_create_wrapper(uint32_t max, uint32_t init)
520 {
521 #if !CONFIG_SPIRAM_USE_MALLOC
522     return (void *)xSemaphoreCreateCounting(max, init);
523 #else
524     StaticQueue_t *queue_buffer = NULL;
525     QueueHandle_t handle = NULL;
526 
527     queue_buffer = heap_caps_malloc(sizeof(StaticQueue_t), MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
528     if (!queue_buffer) {
529         goto error;
530     }
531 
532     handle = xSemaphoreCreateCountingStatic(max, init, queue_buffer);
533     if (!handle) {
534         goto error;
535     }
536 
537     btdm_queue_item_t item = {
538         .handle = handle,
539         .storage = NULL,
540         .buffer = queue_buffer,
541     };
542 
543     if (!btdm_queue_generic_register(&item)) {
544         goto error;
545     }
546     return handle;
547 
548  error:
549     if (handle) {
550         vSemaphoreDelete(handle);
551     }
552     if (queue_buffer) {
553         free(queue_buffer);
554     }
555 
556     return NULL;
557 #endif
558 }
559 
semphr_delete_wrapper(void * semphr)560 static void semphr_delete_wrapper(void *semphr)
561 {
562 #if !CONFIG_SPIRAM_USE_MALLOC
563     vSemaphoreDelete(semphr);
564 #else
565     btdm_queue_item_t item = {
566         .handle = semphr,
567         .storage = NULL,
568         .buffer = NULL,
569     };
570 
571     if (btdm_queue_generic_deregister(&item)) {
572         vSemaphoreDelete(item.handle);
573         free(item.buffer);
574     }
575 
576     return;
577 #endif
578 }
579 
semphr_take_from_isr_wrapper(void * semphr,void * hptw)580 static int32_t IRAM_ATTR semphr_take_from_isr_wrapper(void *semphr, void *hptw)
581 {
582     return (int32_t)xSemaphoreTakeFromISR(semphr, hptw);
583 }
584 
semphr_give_from_isr_wrapper(void * semphr,void * hptw)585 static int32_t IRAM_ATTR semphr_give_from_isr_wrapper(void *semphr, void *hptw)
586 {
587     return (int32_t)xSemaphoreGiveFromISR(semphr, hptw);
588 }
589 
semphr_take_wrapper(void * semphr,uint32_t block_time_ms)590 static int32_t semphr_take_wrapper(void *semphr, uint32_t block_time_ms)
591 {
592     if (block_time_ms == OSI_FUNCS_TIME_BLOCKING) {
593         return (int32_t)xSemaphoreTake(semphr, portMAX_DELAY);
594     } else {
595         return (int32_t)xSemaphoreTake(semphr, block_time_ms / portTICK_PERIOD_MS);
596     }
597 }
598 
semphr_give_wrapper(void * semphr)599 static int32_t semphr_give_wrapper(void *semphr)
600 {
601     return (int32_t)xSemaphoreGive(semphr);
602 }
603 
mutex_create_wrapper(void)604 static void *mutex_create_wrapper(void)
605 {
606 #if CONFIG_SPIRAM_USE_MALLOC
607     StaticQueue_t *queue_buffer = NULL;
608     QueueHandle_t handle = NULL;
609 
610     queue_buffer = heap_caps_malloc(sizeof(StaticQueue_t), MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
611     if (!queue_buffer) {
612         goto error;
613     }
614 
615     handle = xSemaphoreCreateMutexStatic(queue_buffer);
616     if (!handle) {
617         goto error;
618     }
619 
620     btdm_queue_item_t item = {
621         .handle = handle,
622         .storage = NULL,
623         .buffer = queue_buffer,
624     };
625 
626     if (!btdm_queue_generic_register(&item)) {
627         goto error;
628     }
629     return handle;
630 
631  error:
632     if (handle) {
633         vSemaphoreDelete(handle);
634     }
635     if (queue_buffer) {
636         free(queue_buffer);
637     }
638 
639     return NULL;
640 #else
641     return (void *)xSemaphoreCreateMutex();
642 #endif
643 }
644 
mutex_delete_wrapper(void * mutex)645 static void mutex_delete_wrapper(void *mutex)
646 {
647 #if !CONFIG_SPIRAM_USE_MALLOC
648     vSemaphoreDelete(mutex);
649 #else
650     btdm_queue_item_t item = {
651         .handle = mutex,
652         .storage = NULL,
653         .buffer = NULL,
654     };
655 
656     if (btdm_queue_generic_deregister(&item)) {
657         vSemaphoreDelete(item.handle);
658         free(item.buffer);
659     }
660 
661     return;
662 #endif
663 }
664 
mutex_lock_wrapper(void * mutex)665 static int32_t mutex_lock_wrapper(void *mutex)
666 {
667     return (int32_t)xSemaphoreTake(mutex, portMAX_DELAY);
668 }
669 
mutex_unlock_wrapper(void * mutex)670 static int32_t mutex_unlock_wrapper(void *mutex)
671 {
672     return (int32_t)xSemaphoreGive(mutex);
673 }
674 
queue_create_wrapper(uint32_t queue_len,uint32_t item_size)675 static void *queue_create_wrapper(uint32_t queue_len, uint32_t item_size)
676 {
677 #if CONFIG_SPIRAM_USE_MALLOC
678     StaticQueue_t *queue_buffer = NULL;
679     uint8_t *queue_storage = NULL;
680     QueueHandle_t handle = NULL;
681 
682     queue_buffer = heap_caps_malloc(sizeof(StaticQueue_t), MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
683     if (!queue_buffer) {
684         goto error;
685     }
686 
687     queue_storage = heap_caps_malloc((queue_len*item_size), MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
688     if (!queue_storage ) {
689         goto error;
690     }
691 
692     handle = xQueueCreateStatic(queue_len, item_size, queue_storage, queue_buffer);
693     if (!handle) {
694         goto error;
695     }
696 
697     btdm_queue_item_t item = {
698         .handle = handle,
699         .storage = queue_storage,
700         .buffer = queue_buffer,
701     };
702 
703     if (!btdm_queue_generic_register(&item)) {
704         goto error;
705     }
706 
707     return handle;
708 
709  error:
710     if (handle) {
711         vQueueDelete(handle);
712     }
713     if (queue_storage) {
714         free(queue_storage);
715     }
716     if (queue_buffer) {
717         free(queue_buffer);
718     }
719 
720     return NULL;
721 #else
722     return (void *)xQueueCreate(queue_len, item_size);
723 #endif
724 }
725 
queue_delete_wrapper(void * queue)726 static void queue_delete_wrapper(void *queue)
727 {
728 #if !CONFIG_SPIRAM_USE_MALLOC
729     vQueueDelete(queue);
730 #else
731     btdm_queue_item_t item = {
732         .handle = queue,
733         .storage = NULL,
734         .buffer = NULL,
735     };
736 
737     if (btdm_queue_generic_deregister(&item)) {
738         vQueueDelete(item.handle);
739         free(item.storage);
740         free(item.buffer);
741     }
742 
743     return;
744 #endif
745 }
746 
queue_send_wrapper(void * queue,void * item,uint32_t block_time_ms)747 static int32_t queue_send_wrapper(void *queue, void *item, uint32_t block_time_ms)
748 {
749     if (block_time_ms == OSI_FUNCS_TIME_BLOCKING) {
750         return (int32_t)xQueueSend(queue, item, portMAX_DELAY);
751     } else {
752         return (int32_t)xQueueSend(queue, item, block_time_ms / portTICK_PERIOD_MS);
753     }
754 }
755 
queue_send_from_isr_wrapper(void * queue,void * item,void * hptw)756 static int32_t IRAM_ATTR queue_send_from_isr_wrapper(void *queue, void *item, void *hptw)
757 {
758     return (int32_t)xQueueSendFromISR(queue, item, hptw);
759 }
760 
queue_recv_wrapper(void * queue,void * item,uint32_t block_time_ms)761 static int32_t queue_recv_wrapper(void *queue, void *item, uint32_t block_time_ms)
762 {
763     if (block_time_ms == OSI_FUNCS_TIME_BLOCKING) {
764         return (int32_t)xQueueReceive(queue, item, portMAX_DELAY);
765     } else {
766         return (int32_t)xQueueReceive(queue, item, block_time_ms / portTICK_PERIOD_MS);
767     }
768 }
769 
queue_recv_from_isr_wrapper(void * queue,void * item,void * hptw)770 static int32_t IRAM_ATTR queue_recv_from_isr_wrapper(void *queue, void *item, void *hptw)
771 {
772     return (int32_t)xQueueReceiveFromISR(queue, item, hptw);
773 }
774 
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)775 static int32_t 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)
776 {
777     return (uint32_t)xTaskCreatePinnedToCore(task_func, name, stack_depth, param, prio, task_handle, (core_id < portNUM_PROCESSORS ? core_id : tskNO_AFFINITY));
778 }
779 
task_delete_wrapper(void * task_handle)780 static void task_delete_wrapper(void *task_handle)
781 {
782     vTaskDelete(task_handle);
783 }
784 
is_in_isr_wrapper(void)785 static bool IRAM_ATTR is_in_isr_wrapper(void)
786 {
787     return !xPortCanYield();
788 }
789 
cause_sw_intr(void * arg)790 static void IRAM_ATTR cause_sw_intr(void *arg)
791 {
792     /* just convert void * to int, because the width is the same */
793     uint32_t intr_no = (uint32_t)arg;
794     XTHAL_SET_INTSET((1<<intr_no));
795 }
796 
cause_sw_intr_to_core_wrapper(int core_id,int intr_no)797 static int IRAM_ATTR cause_sw_intr_to_core_wrapper(int core_id, int intr_no)
798 {
799     esp_err_t err = ESP_OK;
800 
801 #if CONFIG_FREERTOS_UNICORE
802     cause_sw_intr((void *)intr_no);
803 #else /* CONFIG_FREERTOS_UNICORE */
804     if (xPortGetCoreID() == core_id) {
805         cause_sw_intr((void *)intr_no);
806     } else {
807         err = esp_ipc_call(core_id, cause_sw_intr, (void *)intr_no);
808     }
809 #endif /* !CONFIG_FREERTOS_UNICORE */
810     return err;
811 }
812 
malloc_internal_wrapper(size_t size)813 static void *malloc_internal_wrapper(size_t size)
814 {
815     return heap_caps_malloc(size, MALLOC_CAP_8BIT|MALLOC_CAP_DMA|MALLOC_CAP_INTERNAL);
816 }
817 
read_mac_wrapper(uint8_t mac[6])818 static int32_t IRAM_ATTR read_mac_wrapper(uint8_t mac[6])
819 {
820     return esp_read_mac(mac, ESP_MAC_BT);
821 }
822 
srand_wrapper(unsigned int seed)823 static void IRAM_ATTR srand_wrapper(unsigned int seed)
824 {
825     /* empty function */
826 }
827 
rand_wrapper(void)828 static int IRAM_ATTR rand_wrapper(void)
829 {
830     return (int)esp_random();
831 }
832 
btdm_lpcycles_2_us(uint32_t cycles)833 static uint32_t IRAM_ATTR btdm_lpcycles_2_us(uint32_t cycles)
834 {
835     // The number of lp cycles should not lead to overflow. Thrs: 100s
836     // clock measurement is conducted
837     uint64_t us = (uint64_t)btdm_lpcycle_us * cycles;
838     us = (us + (1 << (btdm_lpcycle_us_frac - 1))) >> btdm_lpcycle_us_frac;
839     return (uint32_t)us;
840 }
841 
842 /*
843  * @brief Converts a duration in slots into a number of low power clock cycles.
844  */
btdm_us_2_lpcycles(uint32_t us)845 static uint32_t IRAM_ATTR btdm_us_2_lpcycles(uint32_t us)
846 {
847     // The number of sleep duration(us) should not lead to overflow. Thrs: 100s
848     // Compute the sleep duration in us to low power clock cycles, with calibration result applied
849     // clock measurement is conducted
850     uint64_t cycles = ((uint64_t)(us) << btdm_lpcycle_us_frac) / btdm_lpcycle_us;
851 
852     return (uint32_t)cycles;
853 }
854 
btdm_sleep_check_duration(uint32_t * slot_cnt)855 static bool IRAM_ATTR btdm_sleep_check_duration(uint32_t *slot_cnt)
856 {
857     if (*slot_cnt < BTDM_MIN_SLEEP_DURATION) {
858         return false;
859     }
860     /* wake up in advance considering the delay in enabling PHY/RF */
861     *slot_cnt -= BTDM_MODEM_WAKE_UP_DELAY;
862     return true;
863 }
864 
btdm_sleep_enter_phase1_wrapper(uint32_t lpcycles)865 static void btdm_sleep_enter_phase1_wrapper(uint32_t lpcycles)
866 {
867 #ifdef CONFIG_PM_ENABLE
868     // start a timer to wake up and acquire the pm_lock before modem_sleep awakes
869     uint32_t us_to_sleep = btdm_lpcycles_2_us(lpcycles);
870 
871 #define BTDM_MIN_TIMER_UNCERTAINTY_US      (500)
872     assert(us_to_sleep > BTDM_MIN_TIMER_UNCERTAINTY_US);
873     // allow a maximum time uncertainty to be about 488ppm(1/2048) at least as clock drift
874     // and set the timer in advance
875     uint32_t uncertainty = (us_to_sleep >> 11);
876     if (uncertainty < BTDM_MIN_TIMER_UNCERTAINTY_US) {
877         uncertainty = BTDM_MIN_TIMER_UNCERTAINTY_US;
878     }
879 
880     if (esp_timer_start_once(s_btdm_slp_tmr, us_to_sleep - uncertainty) != ESP_OK) {
881         ESP_LOGW(BTDM_LOG_TAG, "timer start failed");
882     }
883 #endif
884 }
885 
btdm_sleep_enter_phase2_wrapper(void)886 static void btdm_sleep_enter_phase2_wrapper(void)
887 {
888     if (btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_ORIG) {
889         esp_phy_disable();
890 #ifdef CONFIG_PM_ENABLE
891         if (s_pm_lock_acquired) {
892             esp_pm_lock_release(s_pm_lock);
893             s_pm_lock_acquired = false;
894         }
895 #endif
896     } else if (btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_EVED) {
897         esp_phy_disable();
898         // pause bluetooth baseband
899         periph_module_disable(PERIPH_BT_BASEBAND_MODULE);
900     }
901 }
902 
btdm_sleep_exit_phase3_wrapper(void)903 static void btdm_sleep_exit_phase3_wrapper(void)
904 {
905 #ifdef CONFIG_PM_ENABLE
906     if (!s_pm_lock_acquired) {
907         s_pm_lock_acquired = true;
908         esp_pm_lock_acquire(s_pm_lock);
909     }
910 #endif
911 
912     if (btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_ORIG) {
913         esp_phy_enable();
914         btdm_check_and_init_bb();
915 #ifdef CONFIG_PM_ENABLE
916         esp_timer_stop(s_btdm_slp_tmr);
917 #endif
918     } else if (btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_EVED) {
919         // resume bluetooth baseband
920         periph_module_enable(PERIPH_BT_BASEBAND_MODULE);
921         esp_phy_enable();
922     }
923 }
924 
925 #ifdef CONFIG_PM_ENABLE
btdm_slp_tmr_customer_callback(void * arg)926 static void btdm_slp_tmr_customer_callback(void * arg)
927 {
928     (void)(arg);
929 
930     if (!s_pm_lock_acquired) {
931         s_pm_lock_acquired = true;
932         esp_pm_lock_acquire(s_pm_lock);
933     }
934 }
935 
btdm_slp_tmr_callback(void * arg)936 static void IRAM_ATTR btdm_slp_tmr_callback(void *arg)
937 {
938     (void)(arg);
939     btdm_dispatch_work_to_controller(btdm_slp_tmr_customer_callback, NULL, true);
940 }
941 #endif
942 
943 #define BTDM_ASYNC_WAKEUP_REQ_HCI       0
944 #define BTDM_ASYNC_WAKEUP_REQ_COEX      1
945 #define BTDM_ASYNC_WAKEUP_REQ_CTRL_DISA 2
946 #define BTDM_ASYNC_WAKEUP_REQMAX        3
947 
btdm_wakeup_request_callback(void * arg)948 static void btdm_wakeup_request_callback(void * arg)
949 {
950     (void)(arg);
951 
952 #if CONFIG_PM_ENABLE
953     if (!s_pm_lock_acquired) {
954         s_pm_lock_acquired = true;
955         esp_pm_lock_acquire(s_pm_lock);
956     }
957     esp_timer_stop(s_btdm_slp_tmr);
958 #endif
959     btdm_wakeup_request();
960 
961     semphr_give_wrapper(s_wakeup_req_sem);
962 }
963 
async_wakeup_request(int event)964 static bool async_wakeup_request(int event)
965 {
966     bool do_wakeup_request = false;
967 
968     switch (event) {
969         case BTDM_ASYNC_WAKEUP_REQ_HCI:
970             btdm_in_wakeup_requesting_set(true);
971             // NO break
972         case BTDM_ASYNC_WAKEUP_REQ_CTRL_DISA:
973             if (!btdm_power_state_active()) {
974                 do_wakeup_request = true;
975 
976                 btdm_dispatch_work_to_controller(btdm_wakeup_request_callback, NULL, true);
977                 semphr_take_wrapper(s_wakeup_req_sem, OSI_FUNCS_TIME_BLOCKING);
978             }
979             break;
980         case BTDM_ASYNC_WAKEUP_REQ_COEX:
981             if (!btdm_power_state_active()) {
982                 do_wakeup_request = true;
983 #if CONFIG_PM_ENABLE
984                 if (!s_pm_lock_acquired) {
985                     s_pm_lock_acquired = true;
986                     esp_pm_lock_acquire(s_pm_lock);
987                 }
988                 esp_timer_stop(s_btdm_slp_tmr);
989 #endif
990                 btdm_wakeup_request();
991             }
992             break;
993         default:
994             return false;
995     }
996 
997     return do_wakeup_request;
998 }
999 
async_wakeup_request_end(int event)1000 static void async_wakeup_request_end(int event)
1001 {
1002     bool request_lock = false;
1003     switch (event) {
1004         case BTDM_ASYNC_WAKEUP_REQ_HCI:
1005             request_lock = true;
1006             break;
1007         case BTDM_ASYNC_WAKEUP_REQ_COEX:
1008         case BTDM_ASYNC_WAKEUP_REQ_CTRL_DISA:
1009             request_lock = false;
1010             break;
1011         default:
1012             return;
1013     }
1014 
1015     if (request_lock) {
1016         btdm_in_wakeup_requesting_set(false);
1017     }
1018 
1019     return;
1020 }
1021 
coex_bt_wakeup_request(void)1022 static bool coex_bt_wakeup_request(void)
1023 {
1024     return async_wakeup_request(BTDM_ASYNC_WAKEUP_REQ_COEX);
1025 }
1026 
coex_bt_wakeup_request_end(void)1027 static void coex_bt_wakeup_request_end(void)
1028 {
1029     async_wakeup_request_end(BTDM_ASYNC_WAKEUP_REQ_COEX);
1030     return;
1031 }
1032 
coex_bt_request_wrapper(uint32_t event,uint32_t latency,uint32_t duration)1033 static int IRAM_ATTR coex_bt_request_wrapper(uint32_t event, uint32_t latency, uint32_t duration)
1034 {
1035 #if CONFIG_SW_COEXIST_ENABLE
1036     return coex_bt_request(event, latency, duration);
1037 #else
1038     return 0;
1039 #endif
1040 }
1041 
coex_bt_release_wrapper(uint32_t event)1042 static int IRAM_ATTR coex_bt_release_wrapper(uint32_t event)
1043 {
1044 #if CONFIG_SW_COEXIST_ENABLE
1045     return coex_bt_release(event);
1046 #else
1047     return 0;
1048 #endif
1049 }
1050 
coex_register_bt_cb_wrapper(coex_func_cb_t cb)1051 static int coex_register_bt_cb_wrapper(coex_func_cb_t cb)
1052 {
1053 #if CONFIG_SW_COEXIST_ENABLE
1054     return coex_register_bt_cb(cb);
1055 #else
1056     return 0;
1057 #endif
1058 }
1059 
coex_bb_reset_lock_wrapper(void)1060 static uint32_t IRAM_ATTR coex_bb_reset_lock_wrapper(void)
1061 {
1062 #if CONFIG_SW_COEXIST_ENABLE
1063     return coex_bb_reset_lock();
1064 #else
1065     return 0;
1066 #endif
1067 }
1068 
coex_bb_reset_unlock_wrapper(uint32_t restore)1069 static void IRAM_ATTR coex_bb_reset_unlock_wrapper(uint32_t restore)
1070 {
1071 #if CONFIG_SW_COEXIST_ENABLE
1072     coex_bb_reset_unlock(restore);
1073 #endif
1074 }
1075 
coex_schm_register_btdm_callback_wrapper(void * callback)1076 static int coex_schm_register_btdm_callback_wrapper(void *callback)
1077 {
1078 #if CONFIG_SW_COEXIST_ENABLE
1079     return coex_schm_register_btdm_callback(callback);
1080 #else
1081     return 0;
1082 #endif
1083 }
1084 
coex_schm_status_bit_clear_wrapper(uint32_t type,uint32_t status)1085 static void coex_schm_status_bit_clear_wrapper(uint32_t type, uint32_t status)
1086 {
1087 #if CONFIG_SW_COEXIST_ENABLE
1088     coex_schm_status_bit_clear(type, status);
1089 #endif
1090 }
1091 
coex_schm_status_bit_set_wrapper(uint32_t type,uint32_t status)1092 static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status)
1093 {
1094 #if CONFIG_SW_COEXIST_ENABLE
1095     coex_schm_status_bit_set(type, status);
1096 #endif
1097 }
1098 
coex_schm_interval_get_wrapper(void)1099 static uint32_t coex_schm_interval_get_wrapper(void)
1100 {
1101 #if CONFIG_SW_COEXIST_ENABLE
1102     return coex_schm_interval_get();
1103 #else
1104     return 0;
1105 #endif
1106 }
1107 
coex_schm_curr_period_get_wrapper(void)1108 static uint8_t coex_schm_curr_period_get_wrapper(void)
1109 {
1110 #if CONFIG_SW_COEXIST_ENABLE
1111     return coex_schm_curr_period_get();
1112 #else
1113     return 1;
1114 #endif
1115 }
1116 
coex_schm_curr_phase_get_wrapper(void)1117 static void * coex_schm_curr_phase_get_wrapper(void)
1118 {
1119 #if CONFIG_SW_COEXIST_ENABLE
1120     return coex_schm_curr_phase_get();
1121 #else
1122     return NULL;
1123 #endif
1124 }
1125 
coex_wifi_channel_get_wrapper(uint8_t * primary,uint8_t * secondary)1126 static int coex_wifi_channel_get_wrapper(uint8_t *primary, uint8_t *secondary)
1127 {
1128 #if CONFIG_SW_COEXIST_ENABLE
1129     return coex_wifi_channel_get(primary, secondary);
1130 #else
1131     return -1;
1132 #endif
1133 }
1134 
coex_register_wifi_channel_change_callback_wrapper(void * cb)1135 static int coex_register_wifi_channel_change_callback_wrapper(void *cb)
1136 {
1137 #if CONFIG_SW_COEXIST_ENABLE
1138     return coex_register_wifi_channel_change_callback(cb);
1139 #else
1140     return -1;
1141 #endif
1142 }
1143 
esp_vhci_host_check_send_available(void)1144 bool esp_vhci_host_check_send_available(void)
1145 {
1146     return API_vhci_host_check_send_available();
1147 }
1148 
esp_vhci_host_send_packet(uint8_t * data,uint16_t len)1149 void esp_vhci_host_send_packet(uint8_t *data, uint16_t len)
1150 {
1151     async_wakeup_request(BTDM_ASYNC_WAKEUP_REQ_HCI);
1152 
1153     API_vhci_host_send_packet(data, len);
1154 
1155     async_wakeup_request_end(BTDM_ASYNC_WAKEUP_REQ_HCI);
1156 }
1157 
esp_vhci_host_register_callback(const esp_vhci_host_callback_t * callback)1158 esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback)
1159 {
1160     return API_vhci_host_register_callback((const vhci_host_callback_t *)callback) == 0 ? ESP_OK : ESP_FAIL;
1161 }
1162 
btdm_config_mask_load(void)1163 static uint32_t btdm_config_mask_load(void)
1164 {
1165     uint32_t mask = 0x0;
1166 
1167 #if CONFIG_BTDM_CTRL_HCI_MODE_UART_H4
1168     mask |= BTDM_CFG_HCI_UART;
1169 #endif
1170 #if CONFIG_BTDM_CTRL_PINNED_TO_CORE == 1
1171     mask |= BTDM_CFG_CONTROLLER_RUN_APP_CPU;
1172 #endif
1173 #if CONFIG_BTDM_CTRL_FULL_SCAN_SUPPORTED
1174     mask |= BTDM_CFG_BLE_FULL_SCAN_SUPPORTED;
1175 #endif /* CONFIG_BTDM_CTRL_FULL_SCAN_SUPPORTED */
1176     mask |= BTDM_CFG_SCAN_DUPLICATE_OPTIONS;
1177 
1178     mask |= BTDM_CFG_SEND_ADV_RESERVED_SIZE;
1179 
1180     return mask;
1181 }
1182 
btdm_controller_mem_init(void)1183 static void btdm_controller_mem_init(void)
1184 {
1185     /* initialise .data section */
1186     memcpy(&_data_start_btdm, (void *)_data_start_btdm_rom, &_data_end_btdm - &_data_start_btdm);
1187     ESP_LOGD(BTDM_LOG_TAG, ".data initialise [0x%08x] <== [0x%08x]", (uint32_t)&_data_start_btdm, _data_start_btdm_rom);
1188 
1189     //initial em, .bss section
1190     for (int i = 1; i < sizeof(btdm_dram_available_region)/sizeof(btdm_dram_available_region_t); i++) {
1191         if (btdm_dram_available_region[i].mode != ESP_BT_MODE_IDLE) {
1192             memset((void *)btdm_dram_available_region[i].start, 0x0, btdm_dram_available_region[i].end - btdm_dram_available_region[i].start);
1193             ESP_LOGD(BTDM_LOG_TAG, ".bss initialise [0x%08x] - [0x%08x]", btdm_dram_available_region[i].start, btdm_dram_available_region[i].end);
1194         }
1195     }
1196 }
1197 
try_heap_caps_add_region(intptr_t start,intptr_t end)1198 static esp_err_t try_heap_caps_add_region(intptr_t start, intptr_t end)
1199 {
1200     int ret = heap_caps_add_region(start, end);
1201     /* heap_caps_add_region() returns ESP_ERR_INVALID_SIZE if the memory region is
1202      * is too small to fit a heap. This cannot be termed as a fatal error and hence
1203      * we replace it by ESP_OK
1204      */
1205     if (ret == ESP_ERR_INVALID_SIZE) {
1206         return ESP_OK;
1207     }
1208     return ret;
1209 }
1210 
esp_bt_controller_mem_release(esp_bt_mode_t mode)1211 esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode)
1212 {
1213     bool update = true;
1214     intptr_t mem_start=(intptr_t) NULL, mem_end=(intptr_t) NULL;
1215 
1216     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
1217         return ESP_ERR_INVALID_STATE;
1218     }
1219 
1220     //already released
1221     if (!(mode & btdm_dram_available_region[0].mode)) {
1222         return ESP_ERR_INVALID_STATE;
1223     }
1224 
1225     for (int i = 0; i < sizeof(btdm_dram_available_region)/sizeof(btdm_dram_available_region_t); i++) {
1226         //skip the share mode, idle mode and other mode
1227         if (btdm_dram_available_region[i].mode == ESP_BT_MODE_IDLE
1228                 || (mode & btdm_dram_available_region[i].mode) != btdm_dram_available_region[i].mode) {
1229             //clear the bit of the mode which will be released
1230             btdm_dram_available_region[i].mode &= ~mode;
1231             continue;
1232         } else {
1233             //clear the bit of the mode which will be released
1234             btdm_dram_available_region[i].mode &= ~mode;
1235         }
1236 
1237         if (update) {
1238             mem_start = btdm_dram_available_region[i].start;
1239             mem_end = btdm_dram_available_region[i].end;
1240             update = false;
1241         }
1242 
1243         if (i < sizeof(btdm_dram_available_region)/sizeof(btdm_dram_available_region_t) - 1) {
1244             mem_end = btdm_dram_available_region[i].end;
1245             if (btdm_dram_available_region[i+1].mode != ESP_BT_MODE_IDLE
1246                     && (mode & btdm_dram_available_region[i+1].mode) == btdm_dram_available_region[i+1].mode
1247                     && mem_end == btdm_dram_available_region[i+1].start) {
1248                 continue;
1249             } else {
1250                 ESP_LOGD(BTDM_LOG_TAG, "Release DRAM [0x%08x] - [0x%08x]", mem_start, mem_end);
1251                 ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
1252                 update = true;
1253             }
1254         } else {
1255             mem_end = btdm_dram_available_region[i].end;
1256             ESP_LOGD(BTDM_LOG_TAG, "Release DRAM [0x%08x] - [0x%08x]", mem_start, mem_end);
1257             ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
1258             update = true;
1259         }
1260     }
1261 
1262     if (mode == ESP_BT_MODE_BTDM) {
1263         mem_start = (intptr_t)&_btdm_bss_start;
1264         mem_end = (intptr_t)&_btdm_bss_end;
1265         if (mem_start != mem_end) {
1266             ESP_LOGD(BTDM_LOG_TAG, "Release BTDM BSS [0x%08x] - [0x%08x]", mem_start, mem_end);
1267             ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
1268         }
1269         mem_start = (intptr_t)&_btdm_data_start;
1270         mem_end = (intptr_t)&_btdm_data_end;
1271         if (mem_start != mem_end) {
1272             ESP_LOGD(BTDM_LOG_TAG, "Release BTDM Data [0x%08x] - [0x%08x]", mem_start, mem_end);
1273             ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
1274         }
1275     }
1276     return ESP_OK;
1277 }
1278 
esp_bt_mem_release(esp_bt_mode_t mode)1279 esp_err_t esp_bt_mem_release(esp_bt_mode_t mode)
1280 {
1281     int ret;
1282     intptr_t mem_start, mem_end;
1283 
1284     ret = esp_bt_controller_mem_release(mode);
1285     if (ret != ESP_OK) {
1286         return ret;
1287     }
1288 
1289     if (mode == ESP_BT_MODE_BTDM) {
1290         mem_start = (intptr_t)&_bt_bss_start;
1291         mem_end = (intptr_t)&_bt_bss_end;
1292         if (mem_start != mem_end) {
1293             ESP_LOGD(BTDM_LOG_TAG, "Release BT BSS [0x%08x] - [0x%08x]", mem_start, mem_end);
1294             ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
1295         }
1296         mem_start = (intptr_t)&_bt_data_start;
1297         mem_end = (intptr_t)&_bt_data_end;
1298         if (mem_start != mem_end) {
1299             ESP_LOGD(BTDM_LOG_TAG, "Release BT Data [0x%08x] - [0x%08x]", mem_start, mem_end);
1300             ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
1301         }
1302 
1303         mem_start = (intptr_t)&_nimble_bss_start;
1304         mem_end = (intptr_t)&_nimble_bss_end;
1305         if (mem_start != mem_end) {
1306             ESP_LOGD(BTDM_LOG_TAG, "Release NimBLE BSS [0x%08x] - [0x%08x]", mem_start, mem_end);
1307             ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
1308         }
1309         mem_start = (intptr_t)&_nimble_data_start;
1310         mem_end = (intptr_t)&_nimble_data_end;
1311         if (mem_start != mem_end) {
1312             ESP_LOGD(BTDM_LOG_TAG, "Release NimBLE Data [0x%08x] - [0x%08x]", mem_start, mem_end);
1313             ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end));
1314         }
1315     }
1316     return ESP_OK;
1317 }
1318 
esp_bt_controller_init(esp_bt_controller_config_t * cfg)1319 esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg)
1320 {
1321     esp_err_t err;
1322     uint32_t btdm_cfg_mask = 0;
1323 
1324     //if all the bt available memory was already released, cannot initialize bluetooth controller
1325     if (btdm_dram_available_region[0].mode == ESP_BT_MODE_IDLE) {
1326         return ESP_ERR_INVALID_STATE;
1327     }
1328 
1329     osi_funcs_p = (struct osi_funcs_t *)malloc_internal_wrapper(sizeof(struct osi_funcs_t));
1330     if (osi_funcs_p == NULL) {
1331         return ESP_ERR_NO_MEM;
1332     }
1333 
1334     memcpy(osi_funcs_p, &osi_funcs_ro, sizeof(struct osi_funcs_t));
1335     if (btdm_osi_funcs_register(osi_funcs_p) != 0) {
1336         return ESP_ERR_INVALID_ARG;
1337     }
1338 
1339     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
1340         return ESP_ERR_INVALID_STATE;
1341     }
1342 
1343     if (cfg == NULL) {
1344         return ESP_ERR_INVALID_ARG;
1345     }
1346 
1347     if (cfg->controller_task_prio != ESP_TASK_BT_CONTROLLER_PRIO
1348             || cfg->controller_task_stack_size < ESP_TASK_BT_CONTROLLER_STACK) {
1349         return ESP_ERR_INVALID_ARG;
1350     }
1351 
1352     //overwrite some parameters
1353     cfg->bt_max_sync_conn = CONFIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN_EFF;
1354     cfg->magic  = ESP_BT_CONTROLLER_CONFIG_MAGIC_VAL;
1355 
1356     if (((cfg->mode & ESP_BT_MODE_BLE) && (cfg->ble_max_conn <= 0 || cfg->ble_max_conn > BTDM_CONTROLLER_BLE_MAX_CONN_LIMIT))
1357             || ((cfg->mode & ESP_BT_MODE_CLASSIC_BT) && (cfg->bt_max_acl_conn <= 0 || cfg->bt_max_acl_conn > BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_LIMIT))
1358             || ((cfg->mode & ESP_BT_MODE_CLASSIC_BT) && (cfg->bt_max_sync_conn > BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_LIMIT))) {
1359         return ESP_ERR_INVALID_ARG;
1360     }
1361 
1362     ESP_LOGI(BTDM_LOG_TAG, "BT controller compile version [%s]", btdm_controller_get_compile_version());
1363 
1364 #if CONFIG_SPIRAM_USE_MALLOC
1365     btdm_queue_table_mux = xSemaphoreCreateMutex();
1366     if (btdm_queue_table_mux == NULL) {
1367         return ESP_ERR_NO_MEM;
1368     }
1369     memset(btdm_queue_table, 0, sizeof(btdm_queue_item_t) * BTDM_MAX_QUEUE_NUM);
1370 #endif
1371 
1372     s_wakeup_req_sem = semphr_create_wrapper(1, 0);
1373     if (s_wakeup_req_sem == NULL) {
1374         err = ESP_ERR_NO_MEM;
1375         goto error;
1376     }
1377 
1378     btdm_controller_mem_init();
1379 
1380     periph_module_enable(PERIPH_BT_MODULE);
1381 
1382 #ifdef CONFIG_PM_ENABLE
1383     s_btdm_allow_light_sleep = false;
1384 #endif
1385 
1386     // set default sleep clock cycle and its fractional bits
1387     btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
1388     btdm_lpcycle_us = 2 << (btdm_lpcycle_us_frac);
1389 
1390 #if CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE_ORIG
1391 
1392     btdm_lpclk_sel = BTDM_LPCLK_SEL_XTAL; // set default value
1393 #if CONFIG_BTDM_CTRL_LPCLK_SEL_EXT_32K_XTAL
1394     // check whether or not EXT_CRYS is working
1395     if (rtc_clk_slow_freq_get() == RTC_SLOW_FREQ_32K_XTAL) {
1396         btdm_lpclk_sel = BTDM_LPCLK_SEL_XTAL32K; // External 32kHz XTAL
1397 #ifdef CONFIG_PM_ENABLE
1398         s_btdm_allow_light_sleep = true;
1399 #endif
1400     } else {
1401         ESP_LOGW(BTDM_LOG_TAG, "32.768kHz XTAL not detected, fall back to main XTAL as Bluetooth sleep clock\n"
1402                  "light sleep mode will not be able to apply when bluetooth is enabled");
1403         btdm_lpclk_sel = BTDM_LPCLK_SEL_XTAL; // set default value
1404     }
1405 #else
1406     btdm_lpclk_sel = BTDM_LPCLK_SEL_XTAL; // set default value
1407 #endif
1408 
1409     bool select_src_ret, set_div_ret;
1410     if (btdm_lpclk_sel == BTDM_LPCLK_SEL_XTAL) {
1411         select_src_ret = btdm_lpclk_select_src(BTDM_LPCLK_SEL_XTAL);
1412         set_div_ret = btdm_lpclk_set_div(rtc_clk_xtal_freq_get() * 2 - 1);
1413         assert(select_src_ret && set_div_ret);
1414         btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
1415         btdm_lpcycle_us = 2 << (btdm_lpcycle_us_frac);
1416     } else { // btdm_lpclk_sel == BTDM_LPCLK_SEL_XTAL32K
1417         select_src_ret = btdm_lpclk_select_src(BTDM_LPCLK_SEL_XTAL32K);
1418         set_div_ret = btdm_lpclk_set_div(0);
1419         assert(select_src_ret && set_div_ret);
1420         btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
1421         btdm_lpcycle_us = (RTC_CLK_CAL_FRACT > 15) ? (1000000 << (RTC_CLK_CAL_FRACT - 15)) :
1422             (1000000 >> (15 - RTC_CLK_CAL_FRACT));
1423         assert(btdm_lpcycle_us != 0);
1424     }
1425     btdm_controller_set_sleep_mode(BTDM_MODEM_SLEEP_MODE_ORIG);
1426 
1427 #elif CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE_EVED
1428     btdm_controller_set_sleep_mode(BTDM_MODEM_SLEEP_MODE_EVED);
1429 #else
1430     btdm_controller_set_sleep_mode(BTDM_MODEM_SLEEP_MODE_NONE);
1431 #endif
1432 
1433 #ifdef CONFIG_PM_ENABLE
1434     if (!s_btdm_allow_light_sleep) {
1435         if ((err = esp_pm_lock_create(ESP_PM_NO_LIGHT_SLEEP, 0, "btLS", &s_light_sleep_pm_lock)) != ESP_OK) {
1436             goto error;
1437         }
1438     }
1439     if ((err = esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "bt", &s_pm_lock)) != ESP_OK) {
1440         goto error;
1441     }
1442     esp_timer_create_args_t create_args = {
1443         .callback = btdm_slp_tmr_callback,
1444         .arg = NULL,
1445         .name = "btSlp"
1446     };
1447     if ((err = esp_timer_create(&create_args, &s_btdm_slp_tmr)) != ESP_OK) {
1448         goto error;
1449     }
1450 
1451     s_pm_lock_acquired = true;
1452 #endif
1453 
1454 #if CONFIG_SW_COEXIST_ENABLE
1455     coex_init();
1456 #endif
1457 
1458     btdm_cfg_mask = btdm_config_mask_load();
1459 
1460     if (btdm_controller_init(btdm_cfg_mask, cfg) != 0) {
1461         err = ESP_ERR_NO_MEM;
1462         goto error;
1463     }
1464 
1465     btdm_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;
1466 
1467     return ESP_OK;
1468 
1469 error:
1470 #ifdef CONFIG_PM_ENABLE
1471     if (!s_btdm_allow_light_sleep) {
1472         if (s_light_sleep_pm_lock != NULL) {
1473             esp_pm_lock_delete(s_light_sleep_pm_lock);
1474             s_light_sleep_pm_lock = NULL;
1475         }
1476     }
1477     if (s_pm_lock != NULL) {
1478         esp_pm_lock_delete(s_pm_lock);
1479         s_pm_lock = NULL;
1480     }
1481     if (s_btdm_slp_tmr != NULL) {
1482         esp_timer_delete(s_btdm_slp_tmr);
1483         s_btdm_slp_tmr = NULL;
1484     }
1485 #endif
1486     if (s_wakeup_req_sem) {
1487         semphr_delete_wrapper(s_wakeup_req_sem);
1488         s_wakeup_req_sem = NULL;
1489     }
1490     return err;
1491 }
1492 
esp_bt_controller_deinit(void)1493 esp_err_t esp_bt_controller_deinit(void)
1494 {
1495     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_INITED) {
1496         return ESP_ERR_INVALID_STATE;
1497     }
1498 
1499     btdm_controller_deinit();
1500 
1501     periph_module_disable(PERIPH_BT_MODULE);
1502 
1503 #ifdef CONFIG_PM_ENABLE
1504     if (!s_btdm_allow_light_sleep) {
1505         esp_pm_lock_delete(s_light_sleep_pm_lock);
1506         s_light_sleep_pm_lock = NULL;
1507     }
1508     esp_timer_stop(s_btdm_slp_tmr);
1509     esp_timer_delete(s_btdm_slp_tmr);
1510     s_btdm_slp_tmr = NULL;
1511     s_pm_lock_acquired = false;
1512 #endif
1513     semphr_delete_wrapper(s_wakeup_req_sem);
1514     s_wakeup_req_sem = NULL;
1515 
1516 #if CONFIG_SPIRAM_USE_MALLOC
1517     vSemaphoreDelete(btdm_queue_table_mux);
1518     btdm_queue_table_mux = NULL;
1519     memset(btdm_queue_table, 0, sizeof(btdm_queue_item_t) * BTDM_MAX_QUEUE_NUM);
1520 #endif
1521 
1522     free(osi_funcs_p);
1523     osi_funcs_p = NULL;
1524 
1525     btdm_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;
1526 
1527     btdm_lpcycle_us = 0;
1528     btdm_controller_set_sleep_mode(BTDM_MODEM_SLEEP_MODE_NONE);
1529 
1530     return ESP_OK;
1531 }
1532 
bt_shutdown(void)1533 static void bt_shutdown(void)
1534 {
1535     esp_err_t ret = ESP_OK;
1536     ESP_LOGD(BTDM_LOG_TAG, "stop Bluetooth");
1537 
1538     ret = esp_bt_controller_disable();
1539     if (ESP_OK != ret) {
1540         ESP_LOGW(BTDM_LOG_TAG, "controller disable ret=%d", ret);
1541     }
1542     return;
1543 }
1544 
1545 
esp_bt_controller_enable(esp_bt_mode_t mode)1546 esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode)
1547 {
1548     int ret;
1549 
1550     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_INITED) {
1551         return ESP_ERR_INVALID_STATE;
1552     }
1553 
1554     //As the history reason, mode should be equal to the mode which set in esp_bt_controller_init()
1555     if (mode != btdm_controller_get_mode()) {
1556         return ESP_ERR_INVALID_ARG;
1557     }
1558 
1559 #ifdef CONFIG_PM_ENABLE
1560     if (!s_btdm_allow_light_sleep) {
1561         esp_pm_lock_acquire(s_light_sleep_pm_lock);
1562     }
1563     esp_pm_lock_acquire(s_pm_lock);
1564 #endif
1565 
1566     esp_phy_enable();
1567 
1568 #if CONFIG_SW_COEXIST_ENABLE
1569     coex_enable();
1570 #endif
1571 
1572     if (btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_ORIG) {
1573         btdm_controller_enable_sleep(true);
1574     }
1575 
1576     // inititalize bluetooth baseband
1577     btdm_check_and_init_bb();
1578 
1579     ret = btdm_controller_enable(mode);
1580     if (ret != 0) {
1581 #if CONFIG_SW_COEXIST_ENABLE
1582         coex_disable();
1583 #endif
1584         esp_phy_disable();
1585 #ifdef CONFIG_PM_ENABLE
1586         if (!s_btdm_allow_light_sleep) {
1587             esp_pm_lock_release(s_light_sleep_pm_lock);
1588         }
1589         esp_pm_lock_release(s_pm_lock);
1590 #endif
1591         return ESP_ERR_INVALID_STATE;
1592     }
1593 
1594     btdm_controller_status = ESP_BT_CONTROLLER_STATUS_ENABLED;
1595     ret = esp_register_shutdown_handler(bt_shutdown);
1596     if (ret != ESP_OK) {
1597         ESP_LOGW(BTDM_LOG_TAG, "Register shutdown handler failed, ret = 0x%x", ret);
1598     }
1599 
1600     return ESP_OK;
1601 }
1602 
esp_bt_controller_disable(void)1603 esp_err_t esp_bt_controller_disable(void)
1604 {
1605     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
1606         return ESP_ERR_INVALID_STATE;
1607     }
1608 
1609     // disable modem sleep and wake up from sleep mode
1610     if (btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_ORIG) {
1611         btdm_controller_enable_sleep(false);
1612         async_wakeup_request(BTDM_ASYNC_WAKEUP_REQ_CTRL_DISA);
1613         while (!btdm_power_state_active()) {
1614             esp_rom_delay_us(1000);
1615         }
1616     }
1617 
1618     btdm_controller_disable();
1619 
1620 #if CONFIG_SW_COEXIST_ENABLE
1621     coex_disable();
1622 #endif
1623 
1624     esp_phy_disable();
1625     btdm_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;
1626     esp_unregister_shutdown_handler(bt_shutdown);
1627 
1628 #ifdef CONFIG_PM_ENABLE
1629     if (!s_btdm_allow_light_sleep) {
1630         esp_pm_lock_release(s_light_sleep_pm_lock);
1631     }
1632     esp_pm_lock_release(s_pm_lock);
1633 #endif
1634 
1635     return ESP_OK;
1636 }
1637 
esp_bt_controller_get_status(void)1638 esp_bt_controller_status_t esp_bt_controller_get_status(void)
1639 {
1640     return btdm_controller_status;
1641 }
1642 
1643 /* extra functions */
esp_ble_tx_power_set(esp_ble_power_type_t power_type,esp_power_level_t power_level)1644 esp_err_t esp_ble_tx_power_set(esp_ble_power_type_t power_type, esp_power_level_t power_level)
1645 {
1646     if (ble_txpwr_set(power_type, power_level) != 0) {
1647         return ESP_ERR_INVALID_ARG;
1648     }
1649 
1650     return ESP_OK;
1651 }
1652 
esp_ble_tx_power_get(esp_ble_power_type_t power_type)1653 esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type)
1654 {
1655     return (esp_power_level_t)ble_txpwr_get(power_type);
1656 }
1657 
esp_bredr_tx_power_set(esp_power_level_t min_power_level,esp_power_level_t max_power_level)1658 esp_err_t esp_bredr_tx_power_set(esp_power_level_t min_power_level, esp_power_level_t max_power_level)
1659 {
1660     esp_err_t err;
1661     int ret;
1662 
1663     ret = bredr_txpwr_set(min_power_level, max_power_level);
1664 
1665     if (ret == 0) {
1666         err = ESP_OK;
1667     } else if (ret == -1) {
1668         err = ESP_ERR_INVALID_ARG;
1669     } else {
1670         err = ESP_ERR_INVALID_STATE;
1671     }
1672 
1673     return err;
1674 }
1675 
esp_bredr_tx_power_get(esp_power_level_t * min_power_level,esp_power_level_t * max_power_level)1676 esp_err_t esp_bredr_tx_power_get(esp_power_level_t *min_power_level, esp_power_level_t *max_power_level)
1677 {
1678     if (bredr_txpwr_get((int *)min_power_level, (int *)max_power_level) != 0) {
1679         return ESP_ERR_INVALID_ARG;
1680     }
1681 
1682     return ESP_OK;
1683 }
1684 
esp_bt_sleep_enable(void)1685 esp_err_t esp_bt_sleep_enable (void)
1686 {
1687     esp_err_t status;
1688     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
1689         return ESP_ERR_INVALID_STATE;
1690     }
1691     if (btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_ORIG ||
1692             btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_EVED) {
1693         btdm_controller_enable_sleep (true);
1694         status = ESP_OK;
1695     } else {
1696         status = ESP_ERR_NOT_SUPPORTED;
1697     }
1698 
1699     return status;
1700 }
1701 
esp_bt_sleep_disable(void)1702 esp_err_t esp_bt_sleep_disable (void)
1703 {
1704     esp_err_t status;
1705     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
1706         return ESP_ERR_INVALID_STATE;
1707     }
1708     if (btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_ORIG ||
1709             btdm_controller_get_sleep_mode() == BTDM_MODEM_SLEEP_MODE_EVED) {
1710         btdm_controller_enable_sleep (false);
1711         status = ESP_OK;
1712     } else {
1713         status = ESP_ERR_NOT_SUPPORTED;
1714     }
1715 
1716     return status;
1717 }
1718 
esp_bredr_sco_datapath_set(esp_sco_data_path_t data_path)1719 esp_err_t esp_bredr_sco_datapath_set(esp_sco_data_path_t data_path)
1720 {
1721     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
1722         return ESP_ERR_INVALID_STATE;
1723     }
1724     bredr_sco_datapath_set(data_path);
1725     return ESP_OK;
1726 }
1727 
esp_ble_scan_dupilcate_list_flush(void)1728 esp_err_t esp_ble_scan_dupilcate_list_flush(void)
1729 {
1730     if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
1731         return ESP_ERR_INVALID_STATE;
1732     }
1733     btdm_controller_scan_duplicate_list_clear();
1734     return ESP_OK;
1735 }
1736 
1737 #endif /*  CONFIG_BT_ENABLED */
1738