summaryrefslogtreecommitdiff
path: root/lib/bt/controller/esp32c3/bt.c
blob: e053cfdf40eea1540f361fe7311ecbc3037a0201 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
/*
 * SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "sdkconfig.h"
#include "esp_heap_caps.h"
#include "esp_heap_caps_init.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/portmacro.h"
#include "esp_types.h"
#include "esp_mac.h"
#include "esp_random.h"
#include "esp_task.h"
#include "esp_attr.h"
#ifdef CONFIG_ESP_PHY_ENABLED
#include "esp_phy_init.h"
#include "esp_private/phy.h"
#endif
#include "esp_bt.h"
#include "esp_err.h"
#include "esp_log.h"
#include "esp_pm.h"
#include "esp_ipc.h"
#include "esp_private/periph_ctrl.h"
#include "esp_private/esp_clk.h"
#include "soc/soc_caps.h"
#include "soc/rtc.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/soc_memory_layout.h"
#ifdef CONFIG_ESP_COEX_ENABLED
#include "private/esp_coexist_internal.h"
#endif
#include "esp_timer.h"
#include "esp_sleep.h"
#include "esp_rom_sys.h"
#if CONFIG_IDF_TARGET_ESP32C3
#include "riscv/interrupt.h"
#include "esp32c3/rom/rom_layout.h"
#else //CONFIG_IDF_TARGET_ESP32S3
#include "esp32s3/rom/rom_layout.h"
#endif
#if CONFIG_BT_ENABLED

/* Macro definition
 ************************************************************************
 */

#define BT_LOG_TAG                          "BLE_INIT"

#define BTDM_INIT_PERIOD                    (5000)    /* ms */

/* Low Power Clock Selection */
#define BTDM_LPCLK_SEL_XTAL      (0)
#define BTDM_LPCLK_SEL_XTAL32K   (1)
#define BTDM_LPCLK_SEL_RTC_SLOW  (2)
#define BTDM_LPCLK_SEL_8M        (3)

// wakeup request sources
enum {
    BTDM_ASYNC_WAKEUP_SRC_VHCI = 0,
    BTDM_ASYNC_WAKEUP_REQ_COEX,
    BTDM_ASYNC_WAKEUP_SRC_DISA,
    BTDM_ASYNC_WAKEUP_SRC_TMR,
    BTDM_ASYNC_WAKEUP_SRC_MAX,
};

// low power control struct
typedef union {
    struct {
        uint32_t enable                  :  1; // whether low power mode is required
        uint32_t lpclk_sel               :  3; // low power clock source
        uint32_t mac_bb_pd               :  1; // whether hardware(MAC, BB) force-power-down is required during sleep
        uint32_t wakeup_timer_required   :  1; // whether system timer is needed
        uint32_t no_light_sleep          :  1; // do not allow system to enter light sleep after bluetooth is enabled
        uint32_t main_xtal_pu            :  1; // power up main XTAL
        uint32_t reserved                : 24; // reserved
    };
    uint32_t val;
} btdm_lpcntl_t;

// low power control status
typedef union {
    struct {
        uint32_t pm_lock_released        :  1; // whether power management lock is released
        uint32_t mac_bb_pd               :  1; // whether hardware(MAC, BB) is powered down
        uint32_t phy_enabled             :  1; // whether phy is switched on
        uint32_t wakeup_timer_started    :  1; // whether wakeup timer is started
        uint32_t reserved                : 28; // reserved
    };
    uint32_t val;
} btdm_lpstat_t;

/* Sleep and wakeup interval control */
#define BTDM_MIN_SLEEP_DURATION          (24) // threshold of interval in half slots to allow to fall into modem sleep
#define BTDM_MODEM_WAKE_UP_DELAY         (8)  // delay in half slots of modem wake up procedure, including re-enable PHY/RF

#define BT_DEBUG(...)
#define BT_API_CALL_CHECK(info, api_call, ret) \
do{\
    esp_err_t __err = (api_call);\
    if ((ret) != __err) {\
        BT_DEBUG("%s %d %s ret=0x%X\n", __FUNCTION__, __LINE__, (info), __err);\
        return __err;\
    }\
} while(0)

#define OSI_FUNCS_TIME_BLOCKING  0xffffffff
#define OSI_VERSION              0x00010008
#define OSI_MAGIC_VALUE          0xFADEBEAD

/* Types definition
 ************************************************************************
 */
/* vendor dependent signals to be posted to controller task */
typedef enum {
    BTDM_VND_OL_SIG_WAKEUP_TMR = 0,
    BTDM_VND_OL_SIG_NUM,
} btdm_vnd_ol_sig_t;

/* prototype of function to handle vendor dependent signals */
typedef void (* btdm_vnd_ol_task_func_t)(void *param);

/* VHCI function interface */
typedef struct vhci_host_callback {
    void (*notify_host_send_available)(void);               /*!< callback used to notify that the host can send packet to controller */
    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*/
} vhci_host_callback_t;

typedef struct {
    void *handle;
} btdm_queue_item_t;

typedef void (* osi_intr_handler)(void);

/* OSI function */
struct osi_funcs_t {
    uint32_t _magic;
    uint32_t _version;
    void (*_interrupt_set)(int cpu_no, int intr_source, int interrupt_no, int interrpt_prio);
    void (*_interrupt_clear)(int interrupt_source, int interrupt_no);
    void (*_interrupt_handler_set)(int interrupt_no, intr_handler_t fn, void *arg);
    void (*_interrupt_disable)(void);
    void (*_interrupt_restore)(void);
    void (*_task_yield)(void);
    void (*_task_yield_from_isr)(void);
    void *(*_semphr_create)(uint32_t max, uint32_t init);
    void (*_semphr_delete)(void *semphr);
    int (*_semphr_take_from_isr)(void *semphr, void *hptw);
    int (*_semphr_give_from_isr)(void *semphr, void *hptw);
    int (*_semphr_take)(void *semphr, uint32_t block_time_ms);
    int (*_semphr_give)(void *semphr);
    void *(*_mutex_create)(void);
    void (*_mutex_delete)(void *mutex);
    int (*_mutex_lock)(void *mutex);
    int (*_mutex_unlock)(void *mutex);
    void *(* _queue_create)(uint32_t queue_len, uint32_t item_size);
    void (* _queue_delete)(void *queue);
    int (* _queue_send)(void *queue, void *item, uint32_t block_time_ms);
    int (* _queue_send_from_isr)(void *queue, void *item, void *hptw);
    int (* _queue_recv)(void *queue, void *item, uint32_t block_time_ms);
    int (* _queue_recv_from_isr)(void *queue, void *item, void *hptw);
    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);
    void (* _task_delete)(void *task_handle);
    bool (* _is_in_isr)(void);
    int (* _cause_sw_intr_to_core)(int core_id, int intr_no);
    void *(* _malloc)(size_t size);
    void *(* _malloc_internal)(size_t size);
    void (* _free)(void *p);
    int (* _read_efuse_mac)(uint8_t mac[6]);
    void (* _srand)(unsigned int seed);
    int (* _rand)(void);
    uint32_t (* _btdm_lpcycles_2_hus)(uint32_t cycles, uint32_t *error_corr);
    uint32_t (* _btdm_hus_2_lpcycles)(uint32_t hus);
    bool (* _btdm_sleep_check_duration)(int32_t *slot_cnt);
    void (* _btdm_sleep_enter_phase1)(uint32_t lpcycles);  /* called when interrupt is disabled */
    void (* _btdm_sleep_enter_phase2)(void);
    void (* _btdm_sleep_exit_phase1)(void);  /* called from ISR */
    void (* _btdm_sleep_exit_phase2)(void);  /* called from ISR */
    void (* _btdm_sleep_exit_phase3)(void);  /* called from task */
    void (* _coex_wifi_sleep_set)(bool sleep);
    int (* _coex_core_ble_conn_dyn_prio_get)(bool *low, bool *high);
    int (* _coex_schm_register_btdm_callback)(void *callback);
    void (* _coex_schm_status_bit_set)(uint32_t type, uint32_t status);
    void (* _coex_schm_status_bit_clear)(uint32_t type, uint32_t status);
    uint32_t (* _coex_schm_interval_get)(void);
    uint8_t (* _coex_schm_curr_period_get)(void);
    void *(* _coex_schm_curr_phase_get)(void);
    void (* _interrupt_on)(int intr_num);
    void (* _interrupt_off)(int intr_num);
    void (* _esp_hw_power_down)(void);
    void (* _esp_hw_power_up)(void);
    void (* _ets_backup_dma_copy)(uint32_t reg, uint32_t mem_addr, uint32_t num, bool to_rem);
    void (* _ets_delay_us)(uint32_t us);
    void (* _btdm_rom_table_ready)(void);
    bool (* _coex_bt_wakeup_request)(void);
    void (* _coex_bt_wakeup_request_end)(void);
};


/* External functions or values
 ************************************************************************
 */

/* not for user call, so don't put to include file */
/* OSI */
extern int btdm_osi_funcs_register(void *osi_funcs);
/* Initialise and De-initialise */
extern int btdm_controller_init(esp_bt_controller_config_t *config_opts);
extern void btdm_controller_deinit(void);
extern int btdm_controller_enable(esp_bt_mode_t mode);
extern void btdm_controller_disable(void);
extern uint8_t btdm_controller_get_mode(void);
extern const char *btdm_controller_get_compile_version(void);
extern void btdm_rf_bb_init_phase2(void); // shall be called after PHY/RF is enabled
/* Sleep */
extern void btdm_controller_enable_sleep(bool enable);
extern uint8_t btdm_controller_get_sleep_mode(void);
extern bool btdm_power_state_active(void);
extern void btdm_wakeup_request(void);
extern void btdm_in_wakeup_requesting_set(bool in_wakeup_requesting);

/* vendor dependent tasks to be posted and handled by controller task*/
extern int btdm_vnd_offload_task_register(btdm_vnd_ol_sig_t sig, btdm_vnd_ol_task_func_t func);
extern int btdm_vnd_offload_task_deregister(btdm_vnd_ol_sig_t sig);
extern int r_btdm_vnd_offload_post_from_isr(btdm_vnd_ol_sig_t sig, void *param, bool need_yield);
extern int r_btdm_vnd_offload_post(btdm_vnd_ol_sig_t sig, void *param);

/* Low Power Clock */
extern bool btdm_lpclk_select_src(uint32_t sel);
extern bool btdm_lpclk_set_div(uint32_t div);
extern int btdm_hci_tl_io_event_post(int event);

/* VHCI */
extern bool API_vhci_host_check_send_available(void);
extern void API_vhci_host_send_packet(uint8_t *data, uint16_t len);
extern int API_vhci_host_register_callback(const vhci_host_callback_t *callback);
/* TX power */
extern int ble_txpwr_set(int power_type, int power_level);
extern int ble_txpwr_get(int power_type);

extern uint16_t l2c_ble_link_get_tx_buf_num(void);
extern void coex_pti_v2(void);

extern bool btdm_deep_sleep_mem_init(void);
extern void btdm_deep_sleep_mem_deinit(void);
extern void btdm_ble_power_down_dma_copy(bool copy);
extern uint8_t btdm_sleep_clock_sync(void);
extern void sdk_config_extend_set_pll_track(bool enable);

#if CONFIG_MAC_BB_PD
extern void esp_mac_bb_power_down(void);
extern void esp_mac_bb_power_up(void);
extern void ets_backup_dma_copy(uint32_t reg, uint32_t mem_addr, uint32_t num, bool to_mem);
#endif

extern void btdm_cca_feature_enable(void);

extern uint32_t _bt_bss_start;
extern uint32_t _bt_bss_end;
extern uint32_t _bt_controller_bss_start;
extern uint32_t _bt_controller_bss_end;
extern uint32_t _bt_data_start;
extern uint32_t _bt_data_end;
extern uint32_t _bt_controller_data_start;
extern uint32_t _bt_controller_data_end;

/* Local Function Declare
 *********************************************************************
 */
static void interrupt_set_wrapper(int cpu_no, int intr_source, int intr_num, int intr_prio);
static void interrupt_clear_wrapper(int intr_source, int intr_num);
static void interrupt_handler_set_wrapper(int n, intr_handler_t fn, void *arg);
static void interrupt_disable(void);
static void interrupt_restore(void);
static void task_yield_from_isr(void);
static void *semphr_create_wrapper(uint32_t max, uint32_t init);
static void semphr_delete_wrapper(void *semphr);
static int semphr_take_from_isr_wrapper(void *semphr, void *hptw);
static int semphr_give_from_isr_wrapper(void *semphr, void *hptw);
static int  semphr_take_wrapper(void *semphr, uint32_t block_time_ms);
static int  semphr_give_wrapper(void *semphr);
static void *mutex_create_wrapper(void);
static void mutex_delete_wrapper(void *mutex);
static int mutex_lock_wrapper(void *mutex);
static int mutex_unlock_wrapper(void *mutex);
static void *queue_create_wrapper(uint32_t queue_len, uint32_t item_size);
static void queue_delete_wrapper(void *queue);
static int queue_send_wrapper(void *queue, void *item, uint32_t block_time_ms);
static int queue_send_from_isr_wrapper(void *queue, void *item, void *hptw);
static int queue_recv_wrapper(void *queue, void *item, uint32_t block_time_ms);
static int queue_recv_from_isr_wrapper(void *queue, void *item, void *hptw);
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);
static void task_delete_wrapper(void *task_handle);
static bool is_in_isr_wrapper(void);
static void *malloc_internal_wrapper(size_t size);
static int read_mac_wrapper(uint8_t mac[6]);
static void srand_wrapper(unsigned int seed);
static int rand_wrapper(void);
static uint32_t btdm_lpcycles_2_hus(uint32_t cycles, uint32_t *error_corr);
static uint32_t btdm_hus_2_lpcycles(uint32_t hus);
static bool btdm_sleep_check_duration(int32_t *slot_cnt);
static void btdm_sleep_enter_phase1_wrapper(uint32_t lpcycles);
static void btdm_sleep_enter_phase2_wrapper(void);
static void btdm_sleep_exit_phase3_wrapper(void);
static void coex_wifi_sleep_set_hook(bool sleep);
static int coex_schm_register_btdm_callback_wrapper(void *callback);
static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status);
static void coex_schm_status_bit_clear_wrapper(uint32_t type, uint32_t status);
static uint32_t coex_schm_interval_get_wrapper(void);
static uint8_t coex_schm_curr_period_get_wrapper(void);
static void * coex_schm_curr_phase_get_wrapper(void);
static void interrupt_on_wrapper(int intr_num);
static void interrupt_off_wrapper(int intr_num);
static void btdm_hw_mac_power_up_wrapper(void);
static void btdm_hw_mac_power_down_wrapper(void);
static void btdm_backup_dma_copy_wrapper(uint32_t reg, uint32_t mem_addr, uint32_t num,  bool to_mem);
static void btdm_funcs_table_ready_wrapper(void);
static bool coex_bt_wakeup_request(void);
static void coex_bt_wakeup_request_end(void);

static void btdm_slp_tmr_callback(void *arg);

static esp_err_t try_heap_caps_add_region(intptr_t start, intptr_t end);

static void bt_controller_deinit_internal(void);

/* Local variable definition
 ***************************************************************************
 */
/* OSI funcs */
static const struct osi_funcs_t osi_funcs_ro = {
    ._magic = OSI_MAGIC_VALUE,
    ._version = OSI_VERSION,
    ._interrupt_set = interrupt_set_wrapper,
    ._interrupt_clear = interrupt_clear_wrapper,
    ._interrupt_handler_set = interrupt_handler_set_wrapper,
    ._interrupt_disable = interrupt_disable,
    ._interrupt_restore = interrupt_restore,
    ._task_yield = vPortYield,
    ._task_yield_from_isr = task_yield_from_isr,
    ._semphr_create = semphr_create_wrapper,
    ._semphr_delete = semphr_delete_wrapper,
    ._semphr_take_from_isr = semphr_take_from_isr_wrapper,
    ._semphr_give_from_isr = semphr_give_from_isr_wrapper,
    ._semphr_take = semphr_take_wrapper,
    ._semphr_give = semphr_give_wrapper,
    ._mutex_create = mutex_create_wrapper,
    ._mutex_delete = mutex_delete_wrapper,
    ._mutex_lock = mutex_lock_wrapper,
    ._mutex_unlock = mutex_unlock_wrapper,
    ._queue_create = queue_create_wrapper,
    ._queue_delete = queue_delete_wrapper,
    ._queue_send = queue_send_wrapper,
    ._queue_send_from_isr = queue_send_from_isr_wrapper,
    ._queue_recv = queue_recv_wrapper,
    ._queue_recv_from_isr = queue_recv_from_isr_wrapper,
    ._task_create = task_create_wrapper,
    ._task_delete = task_delete_wrapper,
    ._is_in_isr = is_in_isr_wrapper,
    ._cause_sw_intr_to_core = NULL,
    ._malloc = malloc,
    ._malloc_internal = malloc_internal_wrapper,
    ._free = free,
    ._read_efuse_mac = read_mac_wrapper,
    ._srand = srand_wrapper,
    ._rand = rand_wrapper,
    ._btdm_lpcycles_2_hus = btdm_lpcycles_2_hus,
    ._btdm_hus_2_lpcycles = btdm_hus_2_lpcycles,
    ._btdm_sleep_check_duration = btdm_sleep_check_duration,
    ._btdm_sleep_enter_phase1 = btdm_sleep_enter_phase1_wrapper,
    ._btdm_sleep_enter_phase2 = btdm_sleep_enter_phase2_wrapper,
    ._btdm_sleep_exit_phase1 = NULL,
    ._btdm_sleep_exit_phase2 = NULL,
    ._btdm_sleep_exit_phase3 = btdm_sleep_exit_phase3_wrapper,
    ._coex_wifi_sleep_set = coex_wifi_sleep_set_hook,
    ._coex_core_ble_conn_dyn_prio_get = NULL,
    ._coex_schm_register_btdm_callback = coex_schm_register_btdm_callback_wrapper,
    ._coex_schm_status_bit_set = coex_schm_status_bit_set_wrapper,
    ._coex_schm_status_bit_clear = coex_schm_status_bit_clear_wrapper,
    ._coex_schm_interval_get = coex_schm_interval_get_wrapper,
    ._coex_schm_curr_period_get = coex_schm_curr_period_get_wrapper,
    ._coex_schm_curr_phase_get = coex_schm_curr_phase_get_wrapper,
    ._interrupt_on = interrupt_on_wrapper,
    ._interrupt_off = interrupt_off_wrapper,
    ._esp_hw_power_down = btdm_hw_mac_power_down_wrapper,
    ._esp_hw_power_up = btdm_hw_mac_power_up_wrapper,
    ._ets_backup_dma_copy = btdm_backup_dma_copy_wrapper,
    ._ets_delay_us = esp_rom_delay_us,
    ._btdm_rom_table_ready = btdm_funcs_table_ready_wrapper,
    ._coex_bt_wakeup_request = coex_bt_wakeup_request,
    ._coex_bt_wakeup_request_end = coex_bt_wakeup_request_end,
};

static DRAM_ATTR struct osi_funcs_t *osi_funcs_p;

/* Static variable declare */
static DRAM_ATTR esp_bt_controller_status_t btdm_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;

static DRAM_ATTR portMUX_TYPE global_int_mux = portMUX_INITIALIZER_UNLOCKED;

// low power control struct
static DRAM_ATTR btdm_lpcntl_t s_lp_cntl;
// low power status struct
static DRAM_ATTR btdm_lpstat_t s_lp_stat;
// measured average low power clock period in micro seconds
static DRAM_ATTR uint32_t btdm_lpcycle_us = 0;
// number of fractional bit for btdm_lpcycle_us
static DRAM_ATTR uint8_t btdm_lpcycle_us_frac = 0;
// semaphore used for blocking VHCI API to wait for controller to wake up
static DRAM_ATTR QueueHandle_t s_wakeup_req_sem = NULL;
// wakeup timer
static DRAM_ATTR esp_timer_handle_t s_btdm_slp_tmr = NULL;

#ifdef CONFIG_PM_ENABLE
static DRAM_ATTR esp_pm_lock_handle_t s_pm_lock;
// pm_lock to prevent light sleep due to incompatibility currently
static DRAM_ATTR esp_pm_lock_handle_t s_light_sleep_pm_lock;
#endif

void IRAM_ATTR btdm_hw_mac_power_down_wrapper(void)
{
#if CONFIG_MAC_BB_PD
#if SOC_PM_SUPPORT_BT_PD
    // Bluetooth module power down
    SET_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_BT_FORCE_ISO);
    SET_PERI_REG_MASK(RTC_CNTL_DIG_PWC_REG, RTC_CNTL_BT_FORCE_PD);
#endif
    esp_mac_bb_power_down();
#endif
}

void IRAM_ATTR btdm_hw_mac_power_up_wrapper(void)
{
#if CONFIG_MAC_BB_PD
#if SOC_PM_SUPPORT_BT_PD
    // Bluetooth module power up
    CLEAR_PERI_REG_MASK(RTC_CNTL_DIG_PWC_REG, RTC_CNTL_BT_FORCE_PD);
    CLEAR_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_BT_FORCE_ISO);
#endif
    esp_mac_bb_power_up();
#endif
}

void IRAM_ATTR btdm_backup_dma_copy_wrapper(uint32_t reg, uint32_t mem_addr, uint32_t num,  bool to_mem)
{
#if CONFIG_MAC_BB_PD
    ets_backup_dma_copy(reg, mem_addr, num, to_mem);
#endif
}

static inline void esp_bt_power_domain_on(void)
{
    // Bluetooth module power up
#if SOC_PM_SUPPORT_BT_PD
    CLEAR_PERI_REG_MASK(RTC_CNTL_DIG_PWC_REG, RTC_CNTL_BT_FORCE_PD);
    CLEAR_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_BT_FORCE_ISO);
#endif
    esp_wifi_bt_power_domain_on();
}

static inline void esp_bt_power_domain_off(void)
{
    // Bluetooth module power down
#if SOC_PM_SUPPORT_BT_PD
    SET_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_BT_FORCE_ISO);
    SET_PERI_REG_MASK(RTC_CNTL_DIG_PWC_REG, RTC_CNTL_BT_FORCE_PD);
#endif
    esp_wifi_bt_power_domain_off();
}

static void interrupt_set_wrapper(int cpu_no, int intr_source, int intr_num, int intr_prio)
{
    esp_rom_route_intr_matrix(cpu_no, intr_source, intr_num);
#if __riscv
    esprv_int_set_priority(intr_num, intr_prio);
    esprv_int_set_type(intr_num, 0);
#endif
}

static void interrupt_clear_wrapper(int intr_source, int intr_num)
{
}

static void interrupt_handler_set_wrapper(int n, intr_handler_t fn, void *arg)
{
    esp_cpu_intr_set_handler(n, fn, arg);
}

static void interrupt_on_wrapper(int intr_num)
{
    esp_cpu_intr_enable(1 << intr_num);
}

static void interrupt_off_wrapper(int intr_num)
{
    esp_cpu_intr_disable(1<<intr_num);
}

static void IRAM_ATTR interrupt_disable(void)
{
    if (xPortInIsrContext()) {
        portENTER_CRITICAL_ISR(&global_int_mux);
    } else {
        portENTER_CRITICAL(&global_int_mux);
    }
}

static void IRAM_ATTR interrupt_restore(void)
{
    if (xPortInIsrContext()) {
        portEXIT_CRITICAL_ISR(&global_int_mux);
    } else {
        portEXIT_CRITICAL(&global_int_mux);
    }
}

static void IRAM_ATTR task_yield_from_isr(void)
{
    portYIELD_FROM_ISR();
}

static void *semphr_create_wrapper(uint32_t max, uint32_t init)
{
    btdm_queue_item_t *semphr = heap_caps_calloc(1, sizeof(btdm_queue_item_t), MALLOC_CAP_8BIT|MALLOC_CAP_INTERNAL);
    assert(semphr);

    /* IDF FreeRTOS guarantees that all dynamic memory allocation goes to internal RAM. */
    semphr->handle = (void *)xSemaphoreCreateCounting(max, init);
    assert(semphr->handle);

    return semphr;
}

static void semphr_delete_wrapper(void *semphr)
{
    if (semphr == NULL) {
        return;
    }

    btdm_queue_item_t *semphr_item = (btdm_queue_item_t *)semphr;

    if (semphr_item->handle) {
        vSemaphoreDelete(semphr_item->handle);
    }

    free(semphr);
}

static int IRAM_ATTR semphr_take_from_isr_wrapper(void *semphr, void *hptw)
{
    return (int)xSemaphoreTakeFromISR(((btdm_queue_item_t *)semphr)->handle, hptw);
}

static int IRAM_ATTR semphr_give_from_isr_wrapper(void *semphr, void *hptw)
{
    return (int)xSemaphoreGiveFromISR(((btdm_queue_item_t *)semphr)->handle, hptw);
}

static int semphr_take_wrapper(void *semphr, uint32_t block_time_ms)
{
    if (block_time_ms == OSI_FUNCS_TIME_BLOCKING) {
        return (int)xSemaphoreTake(((btdm_queue_item_t *)semphr)->handle, portMAX_DELAY);
    } else {
        return (int)xSemaphoreTake(((btdm_queue_item_t *)semphr)->handle, block_time_ms / portTICK_PERIOD_MS);
    }
}

static int semphr_give_wrapper(void *semphr)
{
    return (int)xSemaphoreGive(((btdm_queue_item_t *)semphr)->handle);
}

static void *mutex_create_wrapper(void)
{
    return (void *)xSemaphoreCreateMutex();
}

static void mutex_delete_wrapper(void *mutex)
{
    vSemaphoreDelete(mutex);
}

static int mutex_lock_wrapper(void *mutex)
{
    return (int)xSemaphoreTake(mutex, portMAX_DELAY);
}

static int mutex_unlock_wrapper(void *mutex)
{
    return (int)xSemaphoreGive(mutex);
}

static void *queue_create_wrapper(uint32_t queue_len, uint32_t item_size)
{
    btdm_queue_item_t *queue = NULL;

    queue = (btdm_queue_item_t*)heap_caps_malloc(sizeof(btdm_queue_item_t), MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
    assert(queue);

    /* IDF FreeRTOS guarantees that all dynamic memory allocation goes to internal RAM. */
    queue->handle = xQueueCreate( queue_len, item_size);
    assert(queue->handle);

    return queue;
}

static void queue_delete_wrapper(void *queue)
{
    btdm_queue_item_t *queue_item = (btdm_queue_item_t *)queue;
    if (queue_item) {
        if(queue_item->handle){
            vQueueDelete(queue_item->handle);
        }
        free(queue_item);
    }
}

static int queue_send_wrapper(void *queue, void *item, uint32_t block_time_ms)
{
    if (block_time_ms == OSI_FUNCS_TIME_BLOCKING) {
        return (int)xQueueSend(((btdm_queue_item_t*)queue)->handle, item, portMAX_DELAY);
    } else {
        return (int)xQueueSend(((btdm_queue_item_t*)queue)->handle, item, block_time_ms / portTICK_PERIOD_MS);
    }
}

static int IRAM_ATTR queue_send_from_isr_wrapper(void *queue, void *item, void *hptw)
{
    return (int)xQueueSendFromISR(((btdm_queue_item_t*)queue)->handle, item, hptw);
}

static int queue_recv_wrapper(void *queue, void *item, uint32_t block_time_ms)
{
    if (block_time_ms == OSI_FUNCS_TIME_BLOCKING) {
        return (int)xQueueReceive(((btdm_queue_item_t*)queue)->handle, item, portMAX_DELAY);
    } else {
        return (int)xQueueReceive(((btdm_queue_item_t*)queue)->handle, item, block_time_ms / portTICK_PERIOD_MS);
    }
}

static int IRAM_ATTR queue_recv_from_isr_wrapper(void *queue, void *item, void *hptw)
{
    return (int)xQueueReceiveFromISR(((btdm_queue_item_t*)queue)->handle, item, hptw);
}

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)
{
    return (uint32_t)xTaskCreatePinnedToCore(task_func, name, stack_depth, param, prio, task_handle, (core_id < CONFIG_FREERTOS_NUMBER_OF_CORES ? core_id : tskNO_AFFINITY));
}

static void task_delete_wrapper(void *task_handle)
{
    vTaskDelete(task_handle);
}

static bool IRAM_ATTR is_in_isr_wrapper(void)
{
    return (bool)xPortInIsrContext();
}

static void *malloc_internal_wrapper(size_t size)
{
    void *p = heap_caps_malloc(size, MALLOC_CAP_INTERNAL|MALLOC_CAP_DMA);
    if(p == NULL) {
        ESP_LOGE(BT_LOG_TAG, "Malloc failed");
    }
    return p;
}

static int IRAM_ATTR read_mac_wrapper(uint8_t mac[6])
{
    int ret = esp_read_mac(mac, ESP_MAC_BT);
    ESP_LOGI(BT_LOG_TAG, "Bluetooth MAC: %02x:%02x:%02x:%02x:%02x:%02x",
               mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    return ret;
}

static void IRAM_ATTR srand_wrapper(unsigned int seed)
{
    /* empty function */
}

static int IRAM_ATTR rand_wrapper(void)
{
    return (int)esp_random();
}

static uint32_t IRAM_ATTR btdm_lpcycles_2_hus(uint32_t cycles, uint32_t *error_corr)
{
    uint64_t local_error_corr = (error_corr == NULL) ? 0 : (uint64_t)(*error_corr);
    uint64_t res = (uint64_t)btdm_lpcycle_us * cycles * 2;
    local_error_corr += res;
    res = (local_error_corr >> btdm_lpcycle_us_frac);
    local_error_corr -= (res << btdm_lpcycle_us_frac);
    if (error_corr) {
        *error_corr = (uint32_t) local_error_corr;
    }
    return (uint32_t)res;
}

/*
 * @brief Converts a duration in half us into a number of low power clock cycles.
 */
static uint32_t IRAM_ATTR btdm_hus_2_lpcycles(uint32_t hus)
{
    // The number of sleep duration(us) should not lead to overflow. Thrs: 100s
    // Compute the sleep duration in us to low power clock cycles, with calibration result applied
    // clock measurement is conducted
    uint64_t cycles = ((uint64_t)(hus) << btdm_lpcycle_us_frac) / btdm_lpcycle_us;
    cycles >>= 1;

    return (uint32_t)cycles;
}

static bool IRAM_ATTR btdm_sleep_check_duration(int32_t *half_slot_cnt)
{
    if (*half_slot_cnt < BTDM_MIN_SLEEP_DURATION) {
        return false;
    }
    /* wake up in advance considering the delay in enabling PHY/RF */
    *half_slot_cnt -= BTDM_MODEM_WAKE_UP_DELAY;
    return true;
}

static void btdm_sleep_enter_phase1_wrapper(uint32_t lpcycles)
{
    if (s_lp_cntl.wakeup_timer_required == 0) {
        return;
    }

    uint32_t us_to_sleep = btdm_lpcycles_2_hus(lpcycles, NULL) >> 1;

#define BTDM_MIN_TIMER_UNCERTAINTY_US      (1800)
#define BTDM_RTC_SLOW_CLK_RC_DRIFT_PERCENT 7
    assert(us_to_sleep > BTDM_MIN_TIMER_UNCERTAINTY_US);
    // allow a maximum time uncertainty to be about 488ppm(1/2048) at least as clock drift
    // and set the timer in advance
    uint32_t uncertainty = (us_to_sleep >> 11);
#if CONFIG_FREERTOS_USE_TICKLESS_IDLE
    if (rtc_clk_slow_src_get() == SOC_RTC_SLOW_CLK_SRC_RC_SLOW) {
        uncertainty = us_to_sleep * BTDM_RTC_SLOW_CLK_RC_DRIFT_PERCENT / 100;
    }
#endif

    if (uncertainty < BTDM_MIN_TIMER_UNCERTAINTY_US) {
        uncertainty = BTDM_MIN_TIMER_UNCERTAINTY_US;
    }

    assert (s_lp_stat.wakeup_timer_started == 0);
    // start a timer to wake up and acquire the pm_lock before modem_sleep awakes
    if (esp_timer_start_once(s_btdm_slp_tmr, us_to_sleep - uncertainty) == ESP_OK) {
        s_lp_stat.wakeup_timer_started = 1;
    } else {
        ESP_LOGE(BT_LOG_TAG, "timer start failed");
        assert(0);
    }
}

static void btdm_sleep_enter_phase2_wrapper(void)
{
    if (btdm_controller_get_sleep_mode() == ESP_BT_SLEEP_MODE_1) {
        if (s_lp_stat.phy_enabled) {
            esp_phy_disable(PHY_MODEM_BT);
            s_lp_stat.phy_enabled = 0;
        } else {
            assert(0);
        }

#ifdef CONFIG_PM_ENABLE
        if (s_lp_stat.pm_lock_released == 0) {
            esp_pm_lock_release(s_pm_lock);
            s_lp_stat.pm_lock_released = 1;
        }
#endif
    }
}

static void btdm_sleep_exit_phase3_wrapper(void)
{
#ifdef CONFIG_PM_ENABLE
    // If BT wakeup before esp timer coming due to timer task have no chance to run.
    // Then we will not run into `btdm_sleep_exit_phase0` and acquire PM lock,
    // Do it again here to fix this issue.
    if (s_lp_stat.pm_lock_released) {
        esp_pm_lock_acquire(s_pm_lock);
        s_lp_stat.pm_lock_released = 0;
    }
#endif

    if (btdm_controller_get_sleep_mode() == ESP_BT_SLEEP_MODE_1) {
        if (s_lp_stat.phy_enabled == 0) {
            esp_phy_enable(PHY_MODEM_BT);
            s_lp_stat.phy_enabled = 1;
        }
    }

    // If BT wakeup before esp timer coming due to timer task have no chance to run.
    // Then we will not run into `btdm_sleep_exit_phase0` and stop esp timer,
    // Do it again here to fix this issue.
    if (s_lp_cntl.wakeup_timer_required && s_lp_stat.wakeup_timer_started) {
        esp_timer_stop(s_btdm_slp_tmr);
        s_lp_stat.wakeup_timer_started = 0;
    }

    // wait for the sleep state to change
    // the procedure duration is at micro-second level or less
    while (btdm_sleep_clock_sync()) {
        ;
    }
}

static void IRAM_ATTR btdm_sleep_exit_phase0(void *param)
{
    assert(s_lp_cntl.enable == 1);

#ifdef CONFIG_PM_ENABLE
    if (s_lp_stat.pm_lock_released) {
        esp_pm_lock_acquire(s_pm_lock);
        s_lp_stat.pm_lock_released = 0;
    }
#endif

    int event = (int) param;
    if (event == BTDM_ASYNC_WAKEUP_SRC_VHCI || event == BTDM_ASYNC_WAKEUP_SRC_DISA) {
        btdm_wakeup_request();
    }

    if (s_lp_cntl.wakeup_timer_required && s_lp_stat.wakeup_timer_started) {
        esp_timer_stop(s_btdm_slp_tmr);
        s_lp_stat.wakeup_timer_started = 0;
    }

    if (event == BTDM_ASYNC_WAKEUP_SRC_VHCI || event == BTDM_ASYNC_WAKEUP_SRC_DISA) {
        semphr_give_wrapper(s_wakeup_req_sem);
    }
}

static void IRAM_ATTR btdm_slp_tmr_callback(void *arg)
{
#ifdef CONFIG_PM_ENABLE
    r_btdm_vnd_offload_post(BTDM_VND_OL_SIG_WAKEUP_TMR, (void *)BTDM_ASYNC_WAKEUP_SRC_TMR);
#endif
}


static bool async_wakeup_request(int event)
{
    if (s_lp_cntl.enable == 0) {
        return false;
    }

    bool do_wakeup_request = false;
    switch (event) {
        case BTDM_ASYNC_WAKEUP_SRC_VHCI:
        case BTDM_ASYNC_WAKEUP_SRC_DISA:
            btdm_in_wakeup_requesting_set(true);
            if (!btdm_power_state_active()) {
                r_btdm_vnd_offload_post(BTDM_VND_OL_SIG_WAKEUP_TMR, (void *)event);
                do_wakeup_request = true;
                semphr_take_wrapper(s_wakeup_req_sem, OSI_FUNCS_TIME_BLOCKING);
            }
            break;
        case BTDM_ASYNC_WAKEUP_REQ_COEX:
            if (!btdm_power_state_active()) {
                do_wakeup_request = true;
#if CONFIG_PM_ENABLE
                if (s_lp_stat.pm_lock_released) {
                    esp_pm_lock_acquire(s_pm_lock);
                    s_lp_stat.pm_lock_released = 0;
                }
#endif
                btdm_wakeup_request();

                if (s_lp_cntl.wakeup_timer_required && s_lp_stat.wakeup_timer_started) {
                    esp_timer_stop(s_btdm_slp_tmr);
                    s_lp_stat.wakeup_timer_started = 0;
                }
            }
        default:
            break;
    }

    return do_wakeup_request;
}

static void async_wakeup_request_end(int event)
{
    if (s_lp_cntl.enable == 0) {
        return;
    }

    bool allow_to_sleep;
    switch (event) {
        case BTDM_ASYNC_WAKEUP_SRC_VHCI:
        case BTDM_ASYNC_WAKEUP_SRC_DISA:
            allow_to_sleep = true;
            break;
        case BTDM_ASYNC_WAKEUP_REQ_COEX:
            allow_to_sleep = false;
            break;
        default:
            allow_to_sleep = true;
            break;
    }

    if (allow_to_sleep) {
        btdm_in_wakeup_requesting_set(false);
    }

    return;
}

static void btdm_funcs_table_ready_wrapper(void)
{
#if BT_BLE_CCA_MODE == 2
    btdm_cca_feature_enable();
#endif
}

bool bt_async_wakeup_request(void)
{
    return async_wakeup_request(BTDM_ASYNC_WAKEUP_SRC_VHCI);
}

void bt_wakeup_request_end(void)
{
    async_wakeup_request_end(BTDM_ASYNC_WAKEUP_SRC_VHCI);
}

static bool coex_bt_wakeup_request(void)
{
    return async_wakeup_request(BTDM_ASYNC_WAKEUP_REQ_COEX);
}

static void coex_bt_wakeup_request_end(void)
{
    async_wakeup_request_end(BTDM_ASYNC_WAKEUP_REQ_COEX);
    return;
}

bool esp_vhci_host_check_send_available(void)
{
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
        return false;
    }
    return API_vhci_host_check_send_available();
}

void esp_vhci_host_send_packet(uint8_t *data, uint16_t len)
{
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
        return;
    }
    async_wakeup_request(BTDM_ASYNC_WAKEUP_SRC_VHCI);

    API_vhci_host_send_packet(data, len);

    async_wakeup_request_end(BTDM_ASYNC_WAKEUP_SRC_VHCI);
}

esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback)
{
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
        return ESP_FAIL;
    }
    return API_vhci_host_register_callback((const vhci_host_callback_t *)callback) == 0 ? ESP_OK : ESP_FAIL;
}

static void btdm_controller_mem_init(void)
{
    extern void btdm_controller_rom_data_init(void );
    btdm_controller_rom_data_init();
}

/**
 * Release two memory areas to the heap. If both areas are consecutive, they will be released as
 * a single area.
 */
typedef struct {
    intptr_t start;
    intptr_t end;
    const char* name;
} bt_area_t;

static esp_err_t esp_bt_mem_release_area(const bt_area_t *area)
{
    esp_err_t ret = ESP_OK;
    intptr_t mem_start = area->start;
    intptr_t mem_end = area->end;
    if (mem_start != mem_end) {
        ESP_LOGD(BT_LOG_TAG, "Release %s [0x%08x] - [0x%08x], len %d", area->name, mem_start, mem_end, mem_end - mem_start);
        ret = try_heap_caps_add_region(mem_start, mem_end);
    }
    return ret;
}

static esp_err_t esp_bt_mem_release_areas(const bt_area_t *area1, const bt_area_t *area2)
{
    esp_err_t ret = ESP_OK;

    if (area1->end == area2->start) {
        bt_area_t merged_area = {
            .start = area1->start,
            .end = area2->end,
            .name = area1->name
        };
        ret = esp_bt_mem_release_area(&merged_area);
    } else {
        esp_bt_mem_release_area(area1);
        ret = esp_bt_mem_release_area(area2);
    }

    return ret;
}

esp_err_t esp_bt_controller_rom_mem_release(esp_bt_mode_t mode)
{
    esp_err_t ret = ESP_OK;

    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
        return ESP_ERR_INVALID_STATE;
    }

    bt_area_t rom_btdm_data = {
        .start = (intptr_t) ets_rom_layout_p->data_start_btdm,
        .end   = (intptr_t) ets_rom_layout_p->data_end_btdm,
        .name  = "ROM btdm data",
    };
    bt_area_t rom_btdm_bss = {
        .start = (intptr_t)ets_rom_layout_p->bss_start_btdm,
        .end   = (intptr_t)ets_rom_layout_p->bss_end_btdm,
        .name  = "ROM btdm BSS",
    };
    bt_area_t rom_btdm_inter_data = {
        .start = (intptr_t) ets_rom_layout_p->data_start_interface_btdm,
        .end   = (intptr_t) ets_rom_layout_p->data_end_interface_btdm,
        .name  = "ROM interface btdm data",
    };
    bt_area_t rom_btdm_inter_bss = {
        .start = (intptr_t)ets_rom_layout_p->bss_start_interface_btdm,
        .end   = (intptr_t)ets_rom_layout_p->bss_end_interface_btdm,
        .name  = "ROM interface btdm BSS",
    };

    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
        ret = ESP_ERR_INVALID_STATE;
    }

    if (mode & ESP_BT_MODE_BLE) {
        /* Free BTDM memory used by the ROM */
        if (ret == ESP_OK) {
            ret = esp_bt_mem_release_areas(&rom_btdm_data, &rom_btdm_bss);
        }

        if (ret == ESP_OK) {
            ret = esp_bt_mem_release_areas(&rom_btdm_inter_data, &rom_btdm_inter_bss);
        }
    }

    return ret;
}

esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode)
{
    esp_err_t ret = ESP_OK;

    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
        return ESP_ERR_INVALID_STATE;
    }

    bt_area_t cont_bss = {
        .start = (intptr_t)&_bt_controller_bss_start,
        .end   = (intptr_t)&_bt_controller_bss_end,
        .name  = "BT Controller BSS",
    };

    bt_area_t cont_data = {
        .start = (intptr_t)&_bt_controller_data_start,
        .end   = (intptr_t)&_bt_controller_data_end,
        .name  = "BT Controller Data"
    };

    if (mode & ESP_BT_MODE_BLE) {
        /* free data and BSS section for libbtdm_app.a */
        if (ret == ESP_OK) {
            ret = esp_bt_mem_release_areas(&cont_data, &cont_bss);
        }
        /* free data and BSS section for Bluetooth controller ROM code */
        if (ret == ESP_OK) {
            ret = esp_bt_controller_rom_mem_release(mode);
        }
    }

    return ret;
}

esp_err_t esp_bt_mem_release(esp_bt_mode_t mode)
{
    esp_err_t ret = ESP_OK;

    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
        return ESP_ERR_INVALID_STATE;
    }

    bt_area_t bss = {
        .start = (intptr_t)&_bt_bss_start,
        .end   = (intptr_t)&_bt_bss_end,
        .name  = "BT BSS",
    };
    bt_area_t cont_bss = {
        .start = (intptr_t)&_bt_controller_bss_start,
        .end   = (intptr_t)&_bt_controller_bss_end,
        .name  = "BT Controller BSS",
    };
    bt_area_t data = {
        .start = (intptr_t)&_bt_data_start,
        .end   = (intptr_t)&_bt_data_end,
        .name  = "BT Data",
    };
    bt_area_t cont_data = {
        .start = (intptr_t)&_bt_controller_data_start,
        .end   = (intptr_t)&_bt_controller_data_end,
        .name  = "BT Controller Data"
    };

    if (mode & ESP_BT_MODE_BLE) {
        /* Start by freeing Bluetooth BSS section */
        if (ret == ESP_OK) {
            ret = esp_bt_mem_release_areas(&bss, &cont_bss);
        }

        /* Do the same thing with the Bluetooth data section */
        if (ret == ESP_OK) {
            ret = esp_bt_mem_release_areas(&data, &cont_data);
        }

        /* free data and BSS section for Bluetooth controller ROM code */
        if (ret == ESP_OK) {
            ret = esp_bt_controller_rom_mem_release(mode);
        }
    }

    return ret;
}

static esp_err_t try_heap_caps_add_region(intptr_t start, intptr_t end)
{
    int ret = heap_caps_add_region(start, end);
    /* heap_caps_add_region() returns ESP_ERR_INVALID_SIZE if the memory region is
     * is too small to fit a heap. This cannot be termed as a fatal error and hence
     * we replace it by ESP_OK
     */

    if (ret == ESP_ERR_INVALID_SIZE) {
        return ESP_OK;
    }
    return ret;
}

#if CONFIG_MAC_BB_PD
static void IRAM_ATTR btdm_mac_bb_power_down_cb(void)
{
    if (s_lp_cntl.mac_bb_pd && s_lp_stat.mac_bb_pd == 0) {
        btdm_ble_power_down_dma_copy(true);
        s_lp_stat.mac_bb_pd = 1;
    }
}

static void IRAM_ATTR btdm_mac_bb_power_up_cb(void)
{
    if (s_lp_cntl.mac_bb_pd && s_lp_stat.mac_bb_pd) {
        btdm_ble_power_down_dma_copy(false);
        s_lp_stat.mac_bb_pd = 0;
    }
}
#endif

// init low-power control resources
static esp_err_t btdm_low_power_mode_init(esp_bt_controller_config_t *cfg)
{
    esp_err_t err = ESP_OK;

    do {
        // set default values for global states or resources
        s_lp_stat.val = 0;
        s_lp_cntl.val = 0;
        s_lp_cntl.main_xtal_pu = 0;
        s_wakeup_req_sem = NULL;
        s_btdm_slp_tmr = NULL;

        // configure and initialize resources
        s_lp_cntl.enable = (cfg->sleep_mode == ESP_BT_SLEEP_MODE_1) ? 1 : 0;
        s_lp_cntl.lpclk_sel = (cfg->sleep_mode == ESP_BT_SLEEP_MODE_1) ? cfg->sleep_clock : ESP_BT_SLEEP_CLOCK_MAIN_XTAL;
        s_lp_cntl.no_light_sleep = 0;

        if (s_lp_cntl.enable) {
#if CONFIG_MAC_BB_PD
            if (!btdm_deep_sleep_mem_init()) {
                err = ESP_ERR_NO_MEM;
                break;
            }
            s_lp_cntl.mac_bb_pd = 1;
#endif
#ifdef CONFIG_PM_ENABLE
            s_lp_cntl.wakeup_timer_required = 1;
#endif
            // async wakeup semaphore for VHCI
            s_wakeup_req_sem = semphr_create_wrapper(1, 0);
            if (s_wakeup_req_sem == NULL) {
                err = ESP_ERR_NO_MEM;
                break;
            }
            btdm_vnd_offload_task_register(BTDM_VND_OL_SIG_WAKEUP_TMR, btdm_sleep_exit_phase0);

            if (s_lp_cntl.wakeup_timer_required) {
                esp_timer_create_args_t create_args = {
                    .callback = btdm_slp_tmr_callback,
                    .arg = NULL,
                    .name = "btSlp",
                };
                if ((err = esp_timer_create(&create_args, &s_btdm_slp_tmr)) != ESP_OK) {
                    break;
                }
            }

            // set default bluetooth sleep clock cycle and its fractional bits
            btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
            btdm_lpcycle_us = 2 << (btdm_lpcycle_us_frac);

            if (s_lp_cntl.lpclk_sel == ESP_BT_SLEEP_CLOCK_EXT_32K_XTAL) { // External 32 kHz XTAL
                // check whether or not EXT_CRYS is working
                if (rtc_clk_slow_src_get() != SOC_RTC_SLOW_CLK_SRC_XTAL32K) {
                    ESP_LOGW(BT_LOG_TAG, "32.768kHz XTAL not detected, fall back to main XTAL as Bluetooth sleep clock");
                    s_lp_cntl.lpclk_sel = ESP_BT_SLEEP_CLOCK_MAIN_XTAL;
#if !CONFIG_BT_CTRL_MAIN_XTAL_PU_DURING_LIGHT_SLEEP
                    s_lp_cntl.no_light_sleep = 1;
#endif
                }
            } else if (s_lp_cntl.lpclk_sel == ESP_BT_SLEEP_CLOCK_RTC_SLOW) {  // Internal 136kHz RC oscillator
                if (rtc_clk_slow_src_get() == SOC_RTC_SLOW_CLK_SRC_RC_SLOW) {
                    ESP_LOGW(BT_LOG_TAG, "Internal 136kHz RC oscillator. The accuracy of this clock is a lot larger than 500ppm which is "
                                "required in Bluetooth communication, so don't select this option in scenarios such as BLE connection state.");
                } else {
                    ESP_LOGW(BT_LOG_TAG, "Internal 136kHz RC oscillator not detected.");
                    assert(0);
                }
            } else if (s_lp_cntl.lpclk_sel == ESP_BT_SLEEP_CLOCK_MAIN_XTAL) {
                ESP_LOGI(BT_LOG_TAG, "Bluetooth will use main XTAL as Bluetooth sleep clock.");
#if !CONFIG_BT_CTRL_MAIN_XTAL_PU_DURING_LIGHT_SLEEP
                s_lp_cntl.no_light_sleep = 1;
#endif
            }
        } else {
            s_lp_cntl.no_light_sleep = 1;
        }

        bool select_src_ret __attribute__((unused));
        bool set_div_ret __attribute__((unused));
        if (s_lp_cntl.lpclk_sel == ESP_BT_SLEEP_CLOCK_MAIN_XTAL) {
#ifdef CONFIG_BT_CTRL_MAIN_XTAL_PU_DURING_LIGHT_SLEEP
            ESP_ERROR_CHECK(esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_ON));
            s_lp_cntl.main_xtal_pu = 1;
#endif
            select_src_ret = btdm_lpclk_select_src(BTDM_LPCLK_SEL_XTAL);
            set_div_ret = btdm_lpclk_set_div(esp_clk_xtal_freq() / MHZ);
            assert(select_src_ret && set_div_ret);
            btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
            btdm_lpcycle_us = 1 << (btdm_lpcycle_us_frac);
        } else if (s_lp_cntl.lpclk_sel == ESP_BT_SLEEP_CLOCK_EXT_32K_XTAL) {
            select_src_ret = btdm_lpclk_select_src(BTDM_LPCLK_SEL_XTAL32K);
            set_div_ret = btdm_lpclk_set_div(0);
            assert(select_src_ret && set_div_ret);
            btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
            btdm_lpcycle_us = (RTC_CLK_CAL_FRACT > 15) ? (1000000 << (RTC_CLK_CAL_FRACT - 15)) :
                (1000000 >> (15 - RTC_CLK_CAL_FRACT));
            assert(btdm_lpcycle_us != 0);
        } else if (s_lp_cntl.lpclk_sel == ESP_BT_SLEEP_CLOCK_RTC_SLOW) {
            select_src_ret = btdm_lpclk_select_src(BTDM_LPCLK_SEL_RTC_SLOW);
            set_div_ret = btdm_lpclk_set_div(0);
            assert(select_src_ret && set_div_ret);
            btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT;
            btdm_lpcycle_us = esp_clk_slowclk_cal_get();
        } else {
            err = ESP_ERR_INVALID_ARG;
            break;
        }
#if CONFIG_SW_COEXIST_ENABLE
        coex_update_lpclk_interval();
#endif

#ifdef CONFIG_PM_ENABLE
        if (s_lp_cntl.no_light_sleep) {
            if ((err = esp_pm_lock_create(ESP_PM_NO_LIGHT_SLEEP, 0, "btLS", &s_light_sleep_pm_lock)) != ESP_OK) {
                break;
            }
            ESP_LOGW(BT_LOG_TAG, "light sleep mode will not be able to apply when bluetooth is enabled.");
        }
        if ((err = esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "bt", &s_pm_lock)) != ESP_OK) {
            break;
        } else {
            s_lp_stat.pm_lock_released = 1;
        }
#endif
    } while (0);

    return err;
}

esp_bt_sleep_clock_t esp_bt_get_lpclk_src(void)
{
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_INITED &&
            btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
        return ESP_BT_SLEEP_CLOCK_NONE;
    }

    return s_lp_cntl.lpclk_sel;
}

esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg)
{
    esp_err_t err = ESP_FAIL;

    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_IDLE) {
        return ESP_ERR_INVALID_STATE;
    }

    if (cfg == NULL) {
        return ESP_ERR_INVALID_ARG;
    }

    if (cfg->controller_task_prio != ESP_TASK_BT_CONTROLLER_PRIO
        || cfg->controller_task_stack_size < ESP_TASK_BT_CONTROLLER_STACK) {
        ESP_LOGE(BT_LOG_TAG, "Invalid controller task prioriy or stack size");
        return ESP_ERR_INVALID_ARG;
    }

    if (cfg->bluetooth_mode != ESP_BT_MODE_BLE) {
        ESP_LOGE(BT_LOG_TAG, "%s controller only support BLE only mode", __func__);
        return ESP_ERR_NOT_SUPPORTED;
    }

    if (cfg->bluetooth_mode & ESP_BT_MODE_BLE) {
        if ((cfg->ble_max_act <= 0) || (cfg->ble_max_act > BT_CTRL_BLE_MAX_ACT_LIMIT)) {
            ESP_LOGE(BT_LOG_TAG, "Invalid value of ble_max_act");
            return ESP_ERR_INVALID_ARG;
        }
    }

    if (cfg->sleep_mode == ESP_BT_SLEEP_MODE_1) {
        if (cfg->sleep_clock == ESP_BT_SLEEP_CLOCK_NONE) {
            ESP_LOGE(BT_LOG_TAG, "SLEEP_MODE_1 enabled but sleep clock not configured");
            return ESP_ERR_INVALID_ARG;
        }
        if (cfg->sleep_clock > ESP_BT_SLEEP_CLOCK_RTC_SLOW) {
            ESP_LOGE(BT_LOG_TAG, "SLEEP_MODE_1 is enabled but this sleep clock is not supported");
            return ESP_ERR_INVALID_ARG;
        }
    }

    // overwrite some parameters
    cfg->magic = ESP_BT_CTRL_CONFIG_MAGIC_VAL;

#if CONFIG_MAC_BB_PD
    esp_mac_bb_pd_mem_init();
#endif
    esp_phy_modem_init();
    esp_bt_power_domain_on();

    btdm_controller_mem_init();

    osi_funcs_p = (struct osi_funcs_t *)malloc_internal_wrapper(sizeof(struct osi_funcs_t));
    if (osi_funcs_p == NULL) {
        return ESP_ERR_NO_MEM;
    }

    memcpy(osi_funcs_p, &osi_funcs_ro, sizeof(struct osi_funcs_t));
    if (btdm_osi_funcs_register(osi_funcs_p) != 0) {
        return ESP_ERR_INVALID_ARG;
    }

    ESP_LOGI(BT_LOG_TAG, "BT controller compile version [%s]", btdm_controller_get_compile_version());

    if ((err = btdm_low_power_mode_init(cfg)) != ESP_OK) {
        ESP_LOGE(BT_LOG_TAG, "Low power module initialization failed");
        goto error;
    }

#if CONFIG_SW_COEXIST_ENABLE
    coex_init();
#endif

    periph_module_enable(PERIPH_BT_MODULE);
    periph_module_reset(PERIPH_BT_MODULE);

    if (btdm_controller_init(cfg) != 0) {
        err = ESP_ERR_NO_MEM;
        goto error;
    }

    btdm_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;

    return ESP_OK;

error:

    bt_controller_deinit_internal();

    return err;
}

esp_err_t esp_bt_controller_deinit(void)
{
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_INITED) {
        return ESP_ERR_INVALID_STATE;
    }

    btdm_controller_deinit();

    bt_controller_deinit_internal();

    return ESP_OK;
}

// deinit low power control resources
static void btdm_low_power_mode_deinit(void)
{
#if CONFIG_MAC_BB_PD
    if (s_lp_cntl.mac_bb_pd) {
        btdm_deep_sleep_mem_deinit();
        s_lp_cntl.mac_bb_pd = 0;
    }
#endif

#ifdef CONFIG_PM_ENABLE
    if (s_lp_cntl.no_light_sleep) {
        if (s_light_sleep_pm_lock != NULL) {
            esp_pm_lock_delete(s_light_sleep_pm_lock);
            s_light_sleep_pm_lock = NULL;
        }
    }

    if (s_pm_lock != NULL) {
        esp_pm_lock_delete(s_pm_lock);
        s_pm_lock = NULL;
        s_lp_stat.pm_lock_released = 0;
    }
#endif

    if (s_lp_cntl.wakeup_timer_required && s_btdm_slp_tmr != NULL) {
        if (s_lp_stat.wakeup_timer_started) {
            esp_timer_stop(s_btdm_slp_tmr);
        }
        s_lp_stat.wakeup_timer_started = 0;
        esp_timer_delete(s_btdm_slp_tmr);
        s_btdm_slp_tmr = NULL;
    }

    if (s_lp_cntl.enable) {
        btdm_vnd_offload_task_deregister(BTDM_VND_OL_SIG_WAKEUP_TMR);
        if (s_wakeup_req_sem != NULL) {
            semphr_delete_wrapper(s_wakeup_req_sem);
            s_wakeup_req_sem = NULL;
        }
    }

    if (s_lp_cntl.lpclk_sel == ESP_BT_SLEEP_CLOCK_MAIN_XTAL) {
#ifdef CONFIG_BT_CTRL_MAIN_XTAL_PU_DURING_LIGHT_SLEEP
        if (s_lp_cntl.main_xtal_pu) {
            ESP_ERROR_CHECK(esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_OFF));
            s_lp_cntl.main_xtal_pu = 0;
        }
#endif
        btdm_lpclk_select_src(BTDM_LPCLK_SEL_RTC_SLOW);
        btdm_lpclk_set_div(0);
#if CONFIG_SW_COEXIST_ENABLE
        coex_update_lpclk_interval();
#endif
    }

    btdm_lpcycle_us = 0;
}

static void bt_controller_deinit_internal(void)
{
    periph_module_disable(PERIPH_BT_MODULE);

    btdm_low_power_mode_deinit();

    esp_bt_power_domain_off();
#if CONFIG_MAC_BB_PD
    esp_mac_bb_pd_mem_deinit();
#endif
    esp_phy_modem_deinit();

    if (osi_funcs_p != NULL) {
        free(osi_funcs_p);
        osi_funcs_p = NULL;
    }

    btdm_controller_status = ESP_BT_CONTROLLER_STATUS_IDLE;
}

esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode)
{
    esp_err_t ret = ESP_OK;

    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_INITED) {
        return ESP_ERR_INVALID_STATE;
    }

    //As the history reason, mode should be equal to the mode which set in esp_bt_controller_init()
    if (mode != btdm_controller_get_mode()) {
        ESP_LOGE(BT_LOG_TAG, "invalid mode %d, controller support mode is %d", mode, btdm_controller_get_mode());
        return ESP_ERR_INVALID_ARG;
    }

    /* Enable PHY when enabling controller to reduce power dissipation after controller init
     * Notice the init order: esp_phy_enable() -> bt_bb_v2_init_cmplx() -> coex_pti_v2()
     */
    esp_phy_enable(PHY_MODEM_BT);
    s_lp_stat.phy_enabled = 1;

#if CONFIG_SW_COEXIST_ENABLE
    coex_enable();
#endif

    // enable low power mode
    do {
#ifdef CONFIG_PM_ENABLE
        if (s_lp_cntl.no_light_sleep) {
            esp_pm_lock_acquire(s_light_sleep_pm_lock);
        }
        esp_pm_lock_acquire(s_pm_lock);
        s_lp_stat.pm_lock_released = 0;
#endif

#if CONFIG_MAC_BB_PD
        if (esp_register_mac_bb_pd_callback(btdm_mac_bb_power_down_cb) != 0) {
            ret = ESP_ERR_INVALID_ARG;
            goto error;
        }

        if (esp_register_mac_bb_pu_callback(btdm_mac_bb_power_up_cb) != 0) {
            ret = ESP_ERR_INVALID_ARG;
            goto error;
        }
#endif

        if (s_lp_cntl.enable) {
            btdm_controller_enable_sleep(true);
        }
    } while (0);

    // Disable pll track by default in BLE controller on ESP32-C3 and ESP32-S3
    sdk_config_extend_set_pll_track(false);

    if (btdm_controller_enable(mode) != 0) {
        ret = ESP_ERR_INVALID_STATE;
        goto error;
    }

    coex_pti_v2();

    btdm_controller_status = ESP_BT_CONTROLLER_STATUS_ENABLED;

    return ret;

error:
    // disable low power mode
    do {
#if CONFIG_MAC_BB_PD
        esp_unregister_mac_bb_pd_callback(btdm_mac_bb_power_down_cb);
        esp_unregister_mac_bb_pu_callback(btdm_mac_bb_power_up_cb);
#endif

        btdm_controller_enable_sleep(false);
#ifdef CONFIG_PM_ENABLE
        if (s_lp_cntl.no_light_sleep) {
            esp_pm_lock_release(s_light_sleep_pm_lock);
        }
        if (s_lp_stat.pm_lock_released == 0) {
            esp_pm_lock_release(s_pm_lock);
            s_lp_stat.pm_lock_released = 1;
        }
#endif
    } while (0);

#if CONFIG_SW_COEXIST_ENABLE
    coex_disable();
#endif
    if (s_lp_stat.phy_enabled) {
        esp_phy_disable(PHY_MODEM_BT);
        s_lp_stat.phy_enabled = 0;
    }
    return ret;
}

esp_err_t esp_bt_controller_disable(void)
{
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
        return ESP_ERR_INVALID_STATE;
    }

    async_wakeup_request(BTDM_ASYNC_WAKEUP_SRC_DISA);
    while (!btdm_power_state_active()){}
    btdm_controller_disable();

    async_wakeup_request_end(BTDM_ASYNC_WAKEUP_SRC_DISA);

#if CONFIG_SW_COEXIST_ENABLE
    coex_disable();
#endif
    if (s_lp_stat.phy_enabled) {
        esp_phy_disable(PHY_MODEM_BT);
        s_lp_stat.phy_enabled = 0;
    }

    btdm_controller_status = ESP_BT_CONTROLLER_STATUS_INITED;

    // disable low power mode
    do {
#if CONFIG_MAC_BB_PD
        esp_unregister_mac_bb_pd_callback(btdm_mac_bb_power_down_cb);
        esp_unregister_mac_bb_pu_callback(btdm_mac_bb_power_up_cb);
#endif

#ifdef CONFIG_PM_ENABLE
        if (s_lp_cntl.no_light_sleep) {
            esp_pm_lock_release(s_light_sleep_pm_lock);
        }

        if (s_lp_stat.pm_lock_released == 0) {
            esp_pm_lock_release(s_pm_lock);
            s_lp_stat.pm_lock_released = 1;
        } else {
            assert(0);
        }
#endif
    } while (0);

    return ESP_OK;
}

esp_bt_controller_status_t esp_bt_controller_get_status(void)
{
    return btdm_controller_status;
}

/* extra functions */
esp_err_t esp_ble_tx_power_set(esp_ble_power_type_t power_type, esp_power_level_t power_level)
{
    esp_err_t stat = ESP_FAIL;

    switch (power_type) {
    case ESP_BLE_PWR_TYPE_ADV:
    case ESP_BLE_PWR_TYPE_SCAN:
    case ESP_BLE_PWR_TYPE_DEFAULT:
        if (ble_txpwr_set(power_type, power_level) == 0) {
            stat = ESP_OK;
        }
        break;
    default:
        stat = ESP_ERR_NOT_SUPPORTED;
        break;
    }

    return stat;
}

esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type)
{
    esp_power_level_t lvl;

    switch (power_type) {
    case ESP_BLE_PWR_TYPE_ADV:
    case ESP_BLE_PWR_TYPE_SCAN:
        lvl = (esp_power_level_t)ble_txpwr_get(power_type);
        break;
    case ESP_BLE_PWR_TYPE_CONN_HDL0:
    case ESP_BLE_PWR_TYPE_CONN_HDL1:
    case ESP_BLE_PWR_TYPE_CONN_HDL2:
    case ESP_BLE_PWR_TYPE_CONN_HDL3:
    case ESP_BLE_PWR_TYPE_CONN_HDL4:
    case ESP_BLE_PWR_TYPE_CONN_HDL5:
    case ESP_BLE_PWR_TYPE_CONN_HDL6:
    case ESP_BLE_PWR_TYPE_CONN_HDL7:
    case ESP_BLE_PWR_TYPE_CONN_HDL8:
    case ESP_BLE_PWR_TYPE_DEFAULT:
        lvl = (esp_power_level_t)ble_txpwr_get(ESP_BLE_PWR_TYPE_DEFAULT);
        break;
    default:
        lvl = ESP_PWR_LVL_INVALID;
        break;
    }

    return lvl;
}

esp_err_t esp_bt_sleep_enable (void)
{
    esp_err_t status;
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
        return ESP_ERR_INVALID_STATE;
    }
    if (btdm_controller_get_sleep_mode() == ESP_BT_SLEEP_MODE_1) {
        btdm_controller_enable_sleep (true);
        status = ESP_OK;
    } else {
        status = ESP_ERR_NOT_SUPPORTED;
    }

    return status;
}

esp_err_t esp_bt_sleep_disable (void)
{
    esp_err_t status;
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED) {
        return ESP_ERR_INVALID_STATE;
    }
    if (btdm_controller_get_sleep_mode() == ESP_BT_SLEEP_MODE_1) {
        btdm_controller_enable_sleep (false);
        status = ESP_OK;
    } else {
        status = ESP_ERR_NOT_SUPPORTED;
    }

    return status;
}

bool esp_bt_controller_is_sleeping(void)
{
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED ||
        btdm_controller_get_sleep_mode() != ESP_BT_SLEEP_MODE_1) {
        return false;
    }

    return !btdm_power_state_active();
}

void esp_bt_controller_wakeup_request(void)
{
    if (btdm_controller_status != ESP_BT_CONTROLLER_STATUS_ENABLED ||
        btdm_controller_get_sleep_mode() != ESP_BT_SLEEP_MODE_1) {
        return;
    }

    btdm_wakeup_request();

}

int IRAM_ATTR esp_bt_h4tl_eif_io_event_notify(int event)
{
    return btdm_hci_tl_io_event_post(event);
}

uint16_t esp_bt_get_tx_buf_num(void)
{
    return l2c_ble_link_get_tx_buf_num();
}

static void coex_wifi_sleep_set_hook(bool sleep)
{

}

static int coex_schm_register_btdm_callback_wrapper(void *callback)
{
#if CONFIG_SW_COEXIST_ENABLE
    return coex_schm_register_callback(COEX_SCHM_CALLBACK_TYPE_BT, callback);
#else
    return 0;
#endif
}

static void coex_schm_status_bit_clear_wrapper(uint32_t type, uint32_t status)
{
#if CONFIG_SW_COEXIST_ENABLE
    coex_schm_status_bit_clear(type, status);
#endif
}

static void coex_schm_status_bit_set_wrapper(uint32_t type, uint32_t status)
{
#if CONFIG_SW_COEXIST_ENABLE
    coex_schm_status_bit_set(type, status);
#endif
}

static uint32_t coex_schm_interval_get_wrapper(void)
{
#if CONFIG_SW_COEXIST_ENABLE
    return coex_schm_interval_get();
#else
    return 0;
#endif
}

static uint8_t coex_schm_curr_period_get_wrapper(void)
{
#if CONFIG_SW_COEXIST_ENABLE
    return coex_schm_curr_period_get();
#else
    return 1;
#endif
}

static void * coex_schm_curr_phase_get_wrapper(void)
{
#if CONFIG_SW_COEXIST_ENABLE
    return coex_schm_curr_phase_get();
#else
    return NULL;
#endif
}

#endif /*  CONFIG_BT_ENABLED */