xref: /btstack/src/hci.c (revision 6be3cf7f3281776ad8dddaa291de20100935c6e3)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "hci.c"
39 
40 /*
41  *  hci.c
42  *
43  *  Created by Matthias Ringwald on 4/29/09.
44  *
45  */
46 
47 #include "btstack_config.h"
48 
49 
50 #ifdef ENABLE_CLASSIC
51 #ifdef HAVE_EMBEDDED_TICK
52 #include "btstack_run_loop_embedded.h"
53 #endif
54 #endif
55 
56 #ifdef HAVE_PLATFORM_IPHONE_OS
57 #include "../port/ios/src/btstack_control_iphone.h"
58 #endif
59 
60 #ifdef ENABLE_BLE
61 #include "gap.h"
62 #include "ble/le_device_db.h"
63 #endif
64 
65 #include <stdarg.h>
66 #include <string.h>
67 #include <inttypes.h>
68 
69 #include "btstack_debug.h"
70 #include "btstack_event.h"
71 #include "btstack_linked_list.h"
72 #include "btstack_memory.h"
73 #include "bluetooth_company_id.h"
74 #include "bluetooth_data_types.h"
75 #include "gap.h"
76 #include "hci.h"
77 #include "hci_cmd.h"
78 #include "hci_dump.h"
79 #include "ad_parser.h"
80 
81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
82 #ifndef HCI_HOST_ACL_PACKET_NUM
83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
84 #endif
85 #ifndef HCI_HOST_ACL_PACKET_LEN
86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
87 #endif
88 #ifndef HCI_HOST_SCO_PACKET_NUM
89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
90 #endif
91 #ifndef HCI_HOST_SCO_PACKET_LEN
92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
93 #endif
94 #endif
95 
96 #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
97 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM."
98 #endif
99 
100 #define HCI_CONNECTION_TIMEOUT_MS 10000
101 
102 #ifndef HCI_RESET_RESEND_TIMEOUT_MS
103 #define HCI_RESET_RESEND_TIMEOUT_MS 200
104 #endif
105 
106 // Names are arbitrarily shortened to 32 bytes if not requested otherwise
107 #ifndef GAP_INQUIRY_MAX_NAME_LEN
108 #define GAP_INQUIRY_MAX_NAME_LEN 32
109 #endif
110 
111 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
112 #define GAP_INQUIRY_DURATION_MIN 0x01
113 #define GAP_INQUIRY_DURATION_MAX 0x30
114 #define GAP_INQUIRY_STATE_ACTIVE 0x80
115 #define GAP_INQUIRY_STATE_IDLE 0
116 #define GAP_INQUIRY_STATE_W2_CANCEL 0x81
117 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x82
118 
119 // GAP Remote Name Request
120 #define GAP_REMOTE_NAME_STATE_IDLE 0
121 #define GAP_REMOTE_NAME_STATE_W2_SEND 1
122 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
123 
124 // GAP Pairing
125 #define GAP_PAIRING_STATE_IDLE                       0
126 #define GAP_PAIRING_STATE_SEND_PIN                   1
127 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
128 #define GAP_PAIRING_STATE_SEND_PASSKEY               3
129 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
130 #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
131 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
132 
133 
134 // prototypes
135 #ifdef ENABLE_CLASSIC
136 static void hci_update_scan_enable(void);
137 static void hci_emit_discoverable_enabled(uint8_t enabled);
138 static int  hci_local_ssp_activated(void);
139 static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
140 static bool hci_ssp_supported(hci_connection_t * connection);
141 static void hci_notify_if_sco_can_send_now(void);
142 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
143 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
144 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
145 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
146 static void hci_connection_timestamp(hci_connection_t *connection);
147 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
148 static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
149 #endif
150 
151 static int  hci_power_control_on(void);
152 static void hci_power_control_off(void);
153 static void hci_state_reset(void);
154 static void hci_emit_transport_packet_sent(void);
155 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
156 static void hci_emit_nr_connections_changed(void);
157 static void hci_emit_hci_open_failed(void);
158 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
159 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
160 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
161 static void hci_run(void);
162 static int  hci_is_le_connection(hci_connection_t * connection);
163 static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
164 
165 #ifdef ENABLE_CLASSIC
166 static int hci_have_usb_transport(void);
167 #endif
168 
169 #ifdef ENABLE_BLE
170 #ifdef ENABLE_LE_CENTRAL
171 // called from test/ble_client/advertising_data_parser.c
172 void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
173 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
174 static hci_connection_t * gap_get_outgoing_connection(void);
175 #endif
176 #endif
177 
178 // the STACK is here
179 #ifndef HAVE_MALLOC
180 static hci_stack_t   hci_stack_static;
181 #endif
182 static hci_stack_t * hci_stack = NULL;
183 
184 #ifdef ENABLE_CLASSIC
185 // default name
186 static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
187 
188 // test helper
189 static uint8_t disable_l2cap_timeouts = 0;
190 #endif
191 
192 /**
193  * create connection for given address
194  *
195  * @return connection OR NULL, if no memory left
196  */
197 static hci_connection_t * create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){
198     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
199     hci_connection_t * conn = btstack_memory_hci_connection_get();
200     if (!conn) return NULL;
201     bd_addr_copy(conn->address, addr);
202     conn->role = HCI_ROLE_INVALID;
203     conn->address_type = addr_type;
204     conn->con_handle = 0xffff;
205     conn->authentication_flags = AUTH_FLAGS_NONE;
206     conn->bonding_flags = 0;
207     conn->requested_security_level = LEVEL_0;
208 #ifdef ENABLE_CLASSIC
209     conn->request_role = HCI_ROLE_INVALID;
210     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
211     btstack_run_loop_set_timer_context(&conn->timeout, conn);
212     hci_connection_timestamp(conn);
213 #endif
214     conn->acl_recombination_length = 0;
215     conn->acl_recombination_pos = 0;
216     conn->num_packets_sent = 0;
217 
218     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
219 #ifdef ENABLE_BLE
220     conn->le_phy_update_all_phys = 0xff;
221 #endif
222 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
223     conn->le_max_tx_octets = 27;
224 #endif
225     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
226     return conn;
227 }
228 
229 
230 /**
231  * get le connection parameter range
232 *
233  * @return le connection parameter range struct
234  */
235 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
236     *range = hci_stack->le_connection_parameter_range;
237 }
238 
239 /**
240  * set le connection parameter range
241  *
242  */
243 
244 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
245     hci_stack->le_connection_parameter_range = *range;
246 }
247 
248 /**
249  * @brief Test if connection parameters are inside in existing rage
250  * @param conn_interval_min (unit: 1.25ms)
251  * @param conn_interval_max (unit: 1.25ms)
252  * @param conn_latency
253  * @param supervision_timeout (unit: 10ms)
254  * @returns 1 if included
255  */
256 int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){
257     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
258     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
259 
260     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
261     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
262 
263     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
264     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
265 
266     return 1;
267 }
268 
269 /**
270  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
271  * @note: default: 1
272  * @param max_peripheral_connections
273  */
274 #ifdef ENABLE_LE_PERIPHERAL
275 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
276     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
277 }
278 #endif
279 
280 /**
281  * get hci connections iterator
282  *
283  * @return hci connections iterator
284  */
285 
286 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
287     btstack_linked_list_iterator_init(it, &hci_stack->connections);
288 }
289 
290 /**
291  * get connection for a given handle
292  *
293  * @return connection OR NULL, if not found
294  */
295 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
296     btstack_linked_list_iterator_t it;
297     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
298     while (btstack_linked_list_iterator_has_next(&it)){
299         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
300         if ( item->con_handle == con_handle ) {
301             return item;
302         }
303     }
304     return NULL;
305 }
306 
307 /**
308  * get connection for given address
309  *
310  * @return connection OR NULL, if not found
311  */
312 hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
313     btstack_linked_list_iterator_t it;
314     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
315     while (btstack_linked_list_iterator_has_next(&it)){
316         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
317         if (connection->address_type != addr_type)  continue;
318         if (memcmp(addr, connection->address, 6) != 0) continue;
319         return connection;
320     }
321     return NULL;
322 }
323 
324 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
325     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
326 }
327 
328 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
329     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
330 }
331 
332 #ifdef ENABLE_CLASSIC
333 
334 #ifdef ENABLE_SCO_OVER_HCI
335 static int hci_number_sco_connections(void){
336     int connections = 0;
337     btstack_linked_list_iterator_t it;
338     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
339     while (btstack_linked_list_iterator_has_next(&it)){
340         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
341         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
342         connections++;
343     }
344     return connections;
345 }
346 #endif
347 
348 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
349     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
350 #ifdef HAVE_EMBEDDED_TICK
351     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
352         // connections might be timed out
353         hci_emit_l2cap_check_timeout(connection);
354     }
355 #else
356     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
357         // connections might be timed out
358         hci_emit_l2cap_check_timeout(connection);
359     }
360 #endif
361 }
362 
363 static void hci_connection_timestamp(hci_connection_t *connection){
364 #ifdef HAVE_EMBEDDED_TICK
365     connection->timestamp = btstack_run_loop_embedded_get_ticks();
366 #else
367     connection->timestamp = btstack_run_loop_get_time_ms();
368 #endif
369 }
370 
371 /**
372  * add authentication flags and reset timer
373  * @note: assumes classic connection
374  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
375  */
376 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
377     bd_addr_t addr;
378     reverse_bd_addr(bd_addr, addr);
379     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
380     if (conn) {
381         connectionSetAuthenticationFlags(conn, flags);
382         hci_connection_timestamp(conn);
383     }
384 }
385 
386 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
387     hci_connection_t * conn = hci_connection_for_handle(handle);
388     if (!conn) return 0;
389     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
390     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
391     return 0;
392 }
393 
394 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
395     if (!hci_stack->link_key_db) return;
396     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
397     hci_stack->link_key_db->delete_link_key(addr);
398 }
399 
400 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
401     if (!hci_stack->link_key_db) return;
402     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
403     hci_stack->link_key_db->put_link_key(addr, link_key, type);
404 }
405 
406 bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
407 	if (!hci_stack->link_key_db) return false;
408 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
409 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
410 	return result;
411 }
412 
413 void gap_delete_all_link_keys(void){
414     bd_addr_t  addr;
415     link_key_t link_key;
416     link_key_type_t type;
417     btstack_link_key_iterator_t it;
418     int ok = gap_link_key_iterator_init(&it);
419     if (!ok) {
420         log_error("could not initialize iterator");
421         return;
422     }
423     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
424         gap_drop_link_key_for_bd_addr(addr);
425     }
426     gap_link_key_iterator_done(&it);
427 }
428 
429 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
430     if (!hci_stack->link_key_db) return 0;
431     if (!hci_stack->link_key_db->iterator_init) return 0;
432     return hci_stack->link_key_db->iterator_init(it);
433 }
434 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){
435     if (!hci_stack->link_key_db) return 0;
436     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
437 }
438 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
439     if (!hci_stack->link_key_db) return;
440     hci_stack->link_key_db->iterator_done(it);
441 }
442 #endif
443 
444 static bool hci_is_le_connection_type(bd_addr_type_t address_type){
445     switch (address_type){
446         case BD_ADDR_TYPE_LE_PUBLIC:
447         case BD_ADDR_TYPE_LE_RANDOM:
448         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC:
449         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM:
450             return true;
451         default:
452             return false;
453     }
454 }
455 
456 static int hci_is_le_connection(hci_connection_t * connection){
457     return hci_is_le_connection_type(connection->address_type);
458 }
459 
460 /**
461  * count connections
462  */
463 static int nr_hci_connections(void){
464     int count = 0;
465     btstack_linked_item_t *it;
466     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
467         count++;
468     }
469     return count;
470 }
471 
472 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
473 
474     unsigned int num_packets_sent_classic = 0;
475     unsigned int num_packets_sent_le = 0;
476 
477     btstack_linked_item_t *it;
478     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
479         hci_connection_t * connection = (hci_connection_t *) it;
480         if (hci_is_le_connection(connection)){
481             num_packets_sent_le += connection->num_packets_sent;
482         }
483         if (connection->address_type == BD_ADDR_TYPE_ACL){
484             num_packets_sent_classic += connection->num_packets_sent;
485         }
486     }
487     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
488     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
489     int free_slots_le = 0;
490 
491     if (free_slots_classic < 0){
492         log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num);
493         return 0;
494     }
495 
496     if (hci_stack->le_acl_packets_total_num){
497         // if we have LE slots, they are used
498         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
499         if (free_slots_le < 0){
500             log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num);
501             return 0;
502         }
503     } else {
504         // otherwise, classic slots are used for LE, too
505         free_slots_classic -= num_packets_sent_le;
506         if (free_slots_classic < 0){
507             log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num);
508             return 0;
509         }
510     }
511 
512     switch (address_type){
513         case BD_ADDR_TYPE_UNKNOWN:
514             log_error("hci_number_free_acl_slots: unknown address type");
515             return 0;
516 
517         case BD_ADDR_TYPE_ACL:
518             return free_slots_classic;
519 
520         default:
521            if (hci_stack->le_acl_packets_total_num){
522                return free_slots_le;
523            }
524            return free_slots_classic;
525     }
526 }
527 
528 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
529     // get connection type
530     hci_connection_t * connection = hci_connection_for_handle(con_handle);
531     if (!connection){
532         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
533         return 0;
534     }
535     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
536 }
537 
538 #ifdef ENABLE_CLASSIC
539 static int hci_number_free_sco_slots(void){
540     unsigned int num_sco_packets_sent  = 0;
541     btstack_linked_item_t *it;
542     if (hci_stack->synchronous_flow_control_enabled){
543         // explicit flow control
544         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
545             hci_connection_t * connection = (hci_connection_t *) it;
546             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
547             num_sco_packets_sent += connection->num_packets_sent;
548         }
549         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
550             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
551             return 0;
552         }
553         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
554     } else {
555         // implicit flow control -- TODO
556         int num_ready = 0;
557         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
558             hci_connection_t * connection = (hci_connection_t *) it;
559             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
560             if (connection->sco_tx_ready == 0) continue;
561             num_ready++;
562         }
563         return num_ready;
564     }
565 }
566 #endif
567 
568 // only used to send HCI Host Number Completed Packets
569 static int hci_can_send_comand_packet_transport(void){
570     if (hci_stack->hci_packet_buffer_reserved) return 0;
571 
572     // check for async hci transport implementations
573     if (hci_stack->hci_transport->can_send_packet_now){
574         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
575             return 0;
576         }
577     }
578     return 1;
579 }
580 
581 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
582 int hci_can_send_command_packet_now(void){
583     if (hci_can_send_comand_packet_transport() == 0) return 0;
584     return hci_stack->num_cmd_packets > 0u;
585 }
586 
587 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
588     // check for async hci transport implementations
589     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
590     return hci_stack->hci_transport->can_send_packet_now(packet_type);
591 }
592 
593 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
594     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
595     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
596 }
597 
598 int hci_can_send_acl_le_packet_now(void){
599     if (hci_stack->hci_packet_buffer_reserved) return 0;
600     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
601 }
602 
603 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
604     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
605     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
606 }
607 
608 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
609     if (hci_stack->hci_packet_buffer_reserved) return 0;
610     return hci_can_send_prepared_acl_packet_now(con_handle);
611 }
612 
613 #ifdef ENABLE_CLASSIC
614 int hci_can_send_acl_classic_packet_now(void){
615     if (hci_stack->hci_packet_buffer_reserved) return 0;
616     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
617 }
618 
619 int hci_can_send_prepared_sco_packet_now(void){
620     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
621     if (hci_have_usb_transport()){
622         return hci_stack->sco_can_send_now;
623     } else {
624         return hci_number_free_sco_slots() > 0;
625     }
626 }
627 
628 int hci_can_send_sco_packet_now(void){
629     if (hci_stack->hci_packet_buffer_reserved) return 0;
630     return hci_can_send_prepared_sco_packet_now();
631 }
632 
633 void hci_request_sco_can_send_now_event(void){
634     hci_stack->sco_waiting_for_can_send_now = 1;
635     hci_notify_if_sco_can_send_now();
636 }
637 #endif
638 
639 // used for internal checks in l2cap.c
640 int hci_is_packet_buffer_reserved(void){
641     return hci_stack->hci_packet_buffer_reserved;
642 }
643 
644 // reserves outgoing packet buffer. @returns 1 if successful
645 int hci_reserve_packet_buffer(void){
646     if (hci_stack->hci_packet_buffer_reserved) {
647         log_error("hci_reserve_packet_buffer called but buffer already reserved");
648         return 0;
649     }
650     hci_stack->hci_packet_buffer_reserved = 1;
651     return 1;
652 }
653 
654 void hci_release_packet_buffer(void){
655     hci_stack->hci_packet_buffer_reserved = 0;
656 }
657 
658 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
659 static int hci_transport_synchronous(void){
660     return hci_stack->hci_transport->can_send_packet_now == NULL;
661 }
662 
663 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
664 
665     // log_info("hci_send_acl_packet_fragments  %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle);
666 
667     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
668     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
669     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
670         max_acl_data_packet_length = hci_stack->le_data_packets_length;
671     }
672 
673 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
674     if (hci_is_le_connection(connection)){
675         max_acl_data_packet_length = connection->le_max_tx_octets;
676     }
677 #endif
678 
679     log_debug("hci_send_acl_packet_fragments entered");
680 
681     int err;
682     // multiple packets could be send on a synchronous HCI transport
683     while (true){
684 
685         log_debug("hci_send_acl_packet_fragments loop entered");
686 
687         // get current data
688         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
689         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
690         bool more_fragments = false;
691 
692         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
693         if (current_acl_data_packet_length > max_acl_data_packet_length){
694             more_fragments = true;
695             current_acl_data_packet_length = max_acl_data_packet_length;
696         }
697 
698         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
699         if (acl_header_pos > 0u){
700             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
701             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
702             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
703         }
704 
705         // update header len
706         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
707 
708         // count packet
709         connection->num_packets_sent++;
710         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
711 
712         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
713         if (more_fragments){
714             // update start of next fragment to send
715             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
716         } else {
717             // done
718             hci_stack->acl_fragmentation_pos = 0;
719             hci_stack->acl_fragmentation_total_size = 0;
720         }
721 
722         // send packet
723         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
724         const int size = current_acl_data_packet_length + 4;
725         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
726         hci_stack->acl_fragmentation_tx_active = 1;
727         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
728 
729         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
730 
731         // done yet?
732         if (!more_fragments) break;
733 
734         // can send more?
735         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
736     }
737 
738     log_debug("hci_send_acl_packet_fragments loop over");
739 
740     // release buffer now for synchronous transport
741     if (hci_transport_synchronous()){
742         hci_stack->acl_fragmentation_tx_active = 0;
743         hci_release_packet_buffer();
744         hci_emit_transport_packet_sent();
745     }
746 
747     return err;
748 }
749 
750 // pre: caller has reserved the packet buffer
751 int hci_send_acl_packet_buffer(int size){
752 
753     // log_info("hci_send_acl_packet_buffer size %u", size);
754 
755     if (!hci_stack->hci_packet_buffer_reserved) {
756         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
757         return 0;
758     }
759 
760     uint8_t * packet = hci_stack->hci_packet_buffer;
761     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
762 
763     // check for free places on Bluetooth module
764     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
765         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
766         hci_release_packet_buffer();
767         hci_emit_transport_packet_sent();
768         return BTSTACK_ACL_BUFFERS_FULL;
769     }
770 
771     hci_connection_t *connection = hci_connection_for_handle( con_handle);
772     if (!connection) {
773         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
774         hci_release_packet_buffer();
775         hci_emit_transport_packet_sent();
776         return 0;
777     }
778 
779 #ifdef ENABLE_CLASSIC
780     hci_connection_timestamp(connection);
781 #endif
782 
783     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
784 
785     // setup data
786     hci_stack->acl_fragmentation_total_size = size;
787     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
788 
789     return hci_send_acl_packet_fragments(connection);
790 }
791 
792 #ifdef ENABLE_CLASSIC
793 // pre: caller has reserved the packet buffer
794 int hci_send_sco_packet_buffer(int size){
795 
796     // log_info("hci_send_acl_packet_buffer size %u", size);
797 
798     if (!hci_stack->hci_packet_buffer_reserved) {
799         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
800         return 0;
801     }
802 
803     uint8_t * packet = hci_stack->hci_packet_buffer;
804 
805     // skip checks in loopback mode
806     if (!hci_stack->loopback_mode){
807         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
808 
809         // check for free places on Bluetooth module
810         if (!hci_can_send_prepared_sco_packet_now()) {
811             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
812             hci_release_packet_buffer();
813             hci_emit_transport_packet_sent();
814             return BTSTACK_ACL_BUFFERS_FULL;
815         }
816 
817         // track send packet in connection struct
818         hci_connection_t *connection = hci_connection_for_handle( con_handle);
819         if (!connection) {
820             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
821             hci_release_packet_buffer();
822             hci_emit_transport_packet_sent();
823             return 0;
824         }
825 
826         if (hci_have_usb_transport()){
827             // token used
828             hci_stack->sco_can_send_now = 0;
829         } else {
830             if (hci_stack->synchronous_flow_control_enabled){
831                 connection->num_packets_sent++;
832             } else {
833                 connection->sco_tx_ready--;
834             }
835         }
836     }
837 
838     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
839     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
840 
841     if (hci_transport_synchronous()){
842         hci_release_packet_buffer();
843         hci_emit_transport_packet_sent();
844     }
845 
846     return err;
847 }
848 #endif
849 
850 static void acl_handler(uint8_t *packet, uint16_t size){
851 
852     // get info
853     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
854     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
855     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
856     uint16_t acl_length         = READ_ACL_LENGTH(packet);
857 
858     // ignore non-registered handle
859     if (!conn){
860         log_error("acl_handler called with non-registered handle %u!" , con_handle);
861         return;
862     }
863 
864     // assert packet is complete
865     if ((acl_length + 4u) != size){
866         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
867         return;
868     }
869 
870 #ifdef ENABLE_CLASSIC
871     // update idle timestamp
872     hci_connection_timestamp(conn);
873 #endif
874 
875 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
876     hci_stack->host_completed_packets = 1;
877     conn->num_packets_completed++;
878 #endif
879 
880     // handle different packet types
881     switch (acl_flags & 0x03u) {
882 
883         case 0x01: // continuation fragment
884 
885             // sanity checks
886             if (conn->acl_recombination_pos == 0u) {
887                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
888                 return;
889             }
890             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
891                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
892                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
893                 conn->acl_recombination_pos = 0;
894                 return;
895             }
896 
897             // append fragment payload (header already stored)
898             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
899                          &packet[4], acl_length);
900             conn->acl_recombination_pos += acl_length;
901 
902             // forward complete L2CAP packet if complete.
903             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
904                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
905                 // reset recombination buffer
906                 conn->acl_recombination_length = 0;
907                 conn->acl_recombination_pos = 0;
908             }
909             break;
910 
911         case 0x02: { // first fragment
912 
913             // sanity check
914             if (conn->acl_recombination_pos) {
915                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
916                 conn->acl_recombination_pos = 0;
917             }
918 
919             // peek into L2CAP packet!
920             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
921 
922             // compare fragment size to L2CAP packet size
923             if (acl_length >= (l2cap_length + 4u)){
924                 // forward fragment as L2CAP packet
925                 hci_emit_acl_packet(packet, acl_length + 4u);
926             } else {
927 
928                 if (acl_length > HCI_ACL_BUFFER_SIZE){
929                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
930                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
931                     return;
932                 }
933 
934                 // store first fragment and tweak acl length for complete package
935                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
936                              packet, acl_length + 4u);
937                 conn->acl_recombination_pos    = acl_length + 4u;
938                 conn->acl_recombination_length = l2cap_length;
939                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
940             }
941             break;
942 
943         }
944         default:
945             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
946             return;
947     }
948 
949     // execute main loop
950     hci_run();
951 }
952 
953 static void hci_shutdown_connection(hci_connection_t *conn){
954     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
955 
956 #ifdef ENABLE_CLASSIC
957 #ifdef ENABLE_SCO_OVER_HCI
958     int addr_type = conn->address_type;
959 #endif
960 #endif
961 
962     btstack_run_loop_remove_timer(&conn->timeout);
963 
964     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
965     btstack_memory_hci_connection_free( conn );
966 
967     // now it's gone
968     hci_emit_nr_connections_changed();
969 
970 #ifdef ENABLE_CLASSIC
971 #ifdef ENABLE_SCO_OVER_HCI
972     // update SCO
973     if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
974         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
975     }
976 #endif
977 #endif
978 }
979 
980 #ifdef ENABLE_CLASSIC
981 
982 static const uint16_t packet_type_sizes[] = {
983     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
984     HCI_ACL_DH1_SIZE, 0, 0, 0,
985     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
986     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
987 };
988 static const uint8_t  packet_type_feature_requirement_bit[] = {
989      0, // 3 slot packets
990      1, // 5 slot packets
991     25, // EDR 2 mpbs
992     26, // EDR 3 mbps
993     39, // 3 slot EDR packts
994     40, // 5 slot EDR packet
995 };
996 static const uint16_t packet_type_feature_packet_mask[] = {
997     0x0f00, // 3 slot packets
998     0xf000, // 5 slot packets
999     0x1102, // EDR 2 mpbs
1000     0x2204, // EDR 3 mbps
1001     0x0300, // 3 slot EDR packts
1002     0x3000, // 5 slot EDR packet
1003 };
1004 
1005 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
1006     // enable packet types based on size
1007     uint16_t packet_types = 0;
1008     unsigned int i;
1009     for (i=0;i<16;i++){
1010         if (packet_type_sizes[i] == 0) continue;
1011         if (packet_type_sizes[i] <= buffer_size){
1012             packet_types |= 1 << i;
1013         }
1014     }
1015     // disable packet types due to missing local supported features
1016     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
1017         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
1018         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1019         if (feature_set) continue;
1020         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
1021         packet_types &= ~packet_type_feature_packet_mask[i];
1022     }
1023     // flip bits for "may not be used"
1024     packet_types ^= 0x3306;
1025     return packet_types;
1026 }
1027 
1028 uint16_t hci_usable_acl_packet_types(void){
1029     return hci_stack->packet_types;
1030 }
1031 #endif
1032 
1033 uint8_t* hci_get_outgoing_packet_buffer(void){
1034     // hci packet buffer is >= acl data packet length
1035     return hci_stack->hci_packet_buffer;
1036 }
1037 
1038 uint16_t hci_max_acl_data_packet_length(void){
1039     return hci_stack->acl_data_packet_length;
1040 }
1041 
1042 #ifdef ENABLE_CLASSIC
1043 int hci_extended_sco_link_supported(void){
1044     // No. 31, byte 3, bit 7
1045     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
1046 }
1047 #endif
1048 
1049 int hci_non_flushable_packet_boundary_flag_supported(void){
1050     // No. 54, byte 6, bit 6
1051     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
1052 }
1053 
1054 static int gap_ssp_supported(void){
1055     // No. 51, byte 6, bit 3
1056     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1057 }
1058 
1059 static int hci_classic_supported(void){
1060 #ifdef ENABLE_CLASSIC
1061     // No. 37, byte 4, bit 5, = No BR/EDR Support
1062     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
1063 #else
1064     return 0;
1065 #endif
1066 }
1067 
1068 static int hci_le_supported(void){
1069 #ifdef ENABLE_BLE
1070     // No. 37, byte 4, bit 6 = LE Supported (Controller)
1071     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1072 #else
1073     return 0;
1074 #endif
1075 }
1076 
1077 #ifdef ENABLE_BLE
1078 
1079 /**
1080  * @brief Get addr type and address used for LE in Advertisements, Scan Responses,
1081  */
1082 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
1083     *addr_type = hci_stack->le_own_addr_type;
1084     if (hci_stack->le_own_addr_type){
1085         (void)memcpy(addr, hci_stack->le_random_address, 6);
1086     } else {
1087         (void)memcpy(addr, hci_stack->local_bd_addr, 6);
1088     }
1089 }
1090 
1091 #ifdef ENABLE_LE_CENTRAL
1092 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
1093 
1094     int offset = 3;
1095     int num_reports = packet[offset];
1096     offset += 1;
1097 
1098     int i;
1099     // log_info("HCI: handle adv report with num reports: %d", num_reports);
1100     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1101     for (i=0; (i<num_reports) && (offset < size);i++){
1102         // sanity checks on data_length:
1103         uint8_t data_length = packet[offset + 8];
1104         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1105         if ((offset + 9u + data_length + 1u) > size)    return;
1106         // setup event
1107         uint8_t event_size = 10u + data_length;
1108         int pos = 0;
1109         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1110         event[pos++] = event_size;
1111         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1112         offset += 8;
1113         pos += 8;
1114         event[pos++] = packet[offset + 1 + data_length]; // rssi
1115         event[pos++] = data_length;
1116         offset++;
1117         (void)memcpy(&event[pos], &packet[offset], data_length);
1118         pos +=    data_length;
1119         offset += data_length + 1u; // rssi
1120         hci_emit_event(event, pos, 1);
1121     }
1122 }
1123 #endif
1124 #endif
1125 
1126 #ifdef ENABLE_BLE
1127 #ifdef ENABLE_LE_PERIPHERAL
1128 static void hci_update_advertisements_enabled_for_current_roles(void){
1129     if (hci_stack->le_advertisements_enabled){
1130         // get number of active le slave connections
1131         int num_slave_connections = 0;
1132         btstack_linked_list_iterator_t it;
1133         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
1134         while (btstack_linked_list_iterator_has_next(&it)){
1135             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
1136             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
1137             if (con->state != OPEN) continue;
1138             if (con->role  != HCI_ROLE_SLAVE) continue;
1139             if (!hci_is_le_connection(con)) continue;
1140             num_slave_connections++;
1141         }
1142         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1143         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1144     } else {
1145         hci_stack->le_advertisements_enabled_for_current_roles = false;
1146     }
1147 }
1148 #endif
1149 #endif
1150 
1151 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1152 
1153 static uint32_t hci_transport_uart_get_main_baud_rate(void){
1154     if (!hci_stack->config) return 0;
1155     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1156     // Limit baud rate for Broadcom chipsets to 3 mbps
1157     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
1158         baud_rate = 3000000;
1159     }
1160     return baud_rate;
1161 }
1162 
1163 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
1164     UNUSED(ds);
1165 
1166     switch (hci_stack->substate){
1167         case HCI_INIT_W4_SEND_RESET:
1168             log_info("Resend HCI Reset");
1169             hci_stack->substate = HCI_INIT_SEND_RESET;
1170             hci_stack->num_cmd_packets = 1;
1171             hci_run();
1172             break;
1173         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
1174             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
1175             if (hci_stack->hci_transport->reset_link){
1176                 hci_stack->hci_transport->reset_link();
1177             }
1178 
1179             /* fall through */
1180 
1181         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1182             log_info("Resend HCI Reset - CSR Warm Boot");
1183             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1184             hci_stack->num_cmd_packets = 1;
1185             hci_run();
1186             break;
1187         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1188             if (hci_stack->hci_transport->set_baudrate){
1189                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1190                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
1191                 hci_stack->hci_transport->set_baudrate(baud_rate);
1192             }
1193             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
1194             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1195                 if (hci_stack->hci_transport->reset_link){
1196                     log_info("Link Reset");
1197                     hci_stack->hci_transport->reset_link();
1198                 }
1199                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1200                 hci_run();
1201             }
1202             break;
1203         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1204             // otherwise continue
1205             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1206             hci_send_cmd(&hci_read_local_supported_commands);
1207             break;
1208         default:
1209             break;
1210     }
1211 }
1212 #endif
1213 
1214 static void hci_initializing_next_state(void){
1215     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
1216 }
1217 
1218 // assumption: hci_can_send_command_packet_now() == true
1219 static void hci_initializing_run(void){
1220     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1221     switch (hci_stack->substate){
1222         case HCI_INIT_SEND_RESET:
1223             hci_state_reset();
1224 
1225 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1226             // prepare reset if command complete not received in 100ms
1227             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1228             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1229             btstack_run_loop_add_timer(&hci_stack->timeout);
1230 #endif
1231             // send command
1232             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1233             hci_send_cmd(&hci_reset);
1234             break;
1235         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1236             hci_send_cmd(&hci_read_local_version_information);
1237             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1238             break;
1239         case HCI_INIT_SEND_READ_LOCAL_NAME:
1240             hci_send_cmd(&hci_read_local_name);
1241             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1242             break;
1243 
1244 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1245         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1246             hci_state_reset();
1247             // prepare reset if command complete not received in 100ms
1248             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1249             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1250             btstack_run_loop_add_timer(&hci_stack->timeout);
1251             // send command
1252             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1253             hci_send_cmd(&hci_reset);
1254             break;
1255         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1256             hci_state_reset();
1257             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1258             hci_send_cmd(&hci_reset);
1259             break;
1260         case HCI_INIT_SEND_BAUD_CHANGE: {
1261             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1262             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1263             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1264             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1265             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1266             // STLC25000D: baudrate change happens within 0.5 s after command was send,
1267             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1268             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1269                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1270                 btstack_run_loop_add_timer(&hci_stack->timeout);
1271             }
1272             break;
1273         }
1274         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1275             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1276             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1277             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1278             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1279             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1280             break;
1281         }
1282         case HCI_INIT_CUSTOM_INIT:
1283             // Custom initialization
1284             if (hci_stack->chipset && hci_stack->chipset->next_command){
1285                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1286                 bool send_cmd = false;
1287                 switch (hci_stack->chipset_result){
1288                     case BTSTACK_CHIPSET_VALID_COMMAND:
1289                         send_cmd = true;
1290                         hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1291                         break;
1292                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1293                         send_cmd = true;
1294                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1295                         log_info("CSR Warm Boot");
1296                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1297                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1298                         btstack_run_loop_add_timer(&hci_stack->timeout);
1299                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1300                             && hci_stack->config
1301                             && hci_stack->chipset
1302                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
1303                             && hci_stack->hci_transport->set_baudrate
1304                             && hci_transport_uart_get_main_baud_rate()){
1305                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1306                         } else {
1307                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1308                         }
1309                         break;
1310                     default:
1311                         break;
1312                 }
1313 
1314                 if (send_cmd){
1315                     int size = 3u + hci_stack->hci_packet_buffer[2u];
1316                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1317                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1318                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1319                     break;
1320                 }
1321                 log_info("Init script done");
1322 
1323                 // Init script download on Broadcom chipsets causes:
1324                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1325                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
1326                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
1327 
1328                     // - baud rate to reset, restore UART baud rate if needed
1329                     int need_baud_change = hci_stack->config
1330                         && hci_stack->chipset
1331                         && hci_stack->chipset->set_baudrate_command
1332                         && hci_stack->hci_transport->set_baudrate
1333                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1334                     if (need_baud_change) {
1335                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1336                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
1337                         hci_stack->hci_transport->set_baudrate(baud_rate);
1338                     }
1339 
1340                     uint16_t bcm_delay_ms = 300;
1341                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
1342                     //   -> Work around: wait here.
1343                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
1344                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1345                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
1346                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1347                     btstack_run_loop_add_timer(&hci_stack->timeout);
1348                     break;
1349                 }
1350             }
1351             // otherwise continue
1352             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1353             hci_send_cmd(&hci_read_local_supported_commands);
1354             break;
1355         case HCI_INIT_SET_BD_ADDR:
1356             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1357             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1358             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1359             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1360             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1361             break;
1362 #endif
1363 
1364         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1365             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1366             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1367             hci_send_cmd(&hci_read_local_supported_commands);
1368             break;
1369         case HCI_INIT_READ_BD_ADDR:
1370             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1371             hci_send_cmd(&hci_read_bd_addr);
1372             break;
1373         case HCI_INIT_READ_BUFFER_SIZE:
1374             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1375             hci_send_cmd(&hci_read_buffer_size);
1376             break;
1377         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1378             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1379             hci_send_cmd(&hci_read_local_supported_features);
1380             break;
1381 
1382 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1383         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
1384             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
1385             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
1386             break;
1387         case HCI_INIT_HOST_BUFFER_SIZE:
1388             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
1389             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
1390                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
1391             break;
1392 #endif
1393 
1394         case HCI_INIT_SET_EVENT_MASK:
1395             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1396             if (hci_le_supported()){
1397                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1398             } else {
1399                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1400                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1401             }
1402             break;
1403 
1404 #ifdef ENABLE_CLASSIC
1405         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1406             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1407             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1408             break;
1409         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1410             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1411             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1412             break;
1413         case HCI_INIT_WRITE_DEFAULT_LINK_POLICY_SETTING:
1414             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_LINK_POLICY_SETTING;
1415             hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1416             break;
1417         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1418             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1419             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1420             break;
1421         case HCI_INIT_WRITE_LOCAL_NAME: {
1422             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1423             hci_reserve_packet_buffer();
1424             uint8_t * packet = hci_stack->hci_packet_buffer;
1425             // construct HCI Command and send
1426             uint16_t opcode = hci_write_local_name.opcode;
1427             hci_stack->last_cmd_opcode = opcode;
1428             packet[0] = opcode & 0xff;
1429             packet[1] = opcode >> 8;
1430             packet[2] = DEVICE_NAME_LEN;
1431             memset(&packet[3], 0, DEVICE_NAME_LEN);
1432             uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1433             uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
1434             // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
1435             (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
1436             // expand '00:00:00:00:00:00' in name with bd_addr
1437             btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
1438             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1439             break;
1440         }
1441         case HCI_INIT_WRITE_EIR_DATA: {
1442             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1443             hci_reserve_packet_buffer();
1444             uint8_t * packet = hci_stack->hci_packet_buffer;
1445             // construct HCI Command in-place and send
1446             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1447             hci_stack->last_cmd_opcode = opcode;
1448             uint16_t offset = 0;
1449             packet[offset++] = opcode & 0xff;
1450             packet[offset++] = opcode >> 8;
1451             packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
1452             packet[offset++] = 0;  // FEC not required
1453             memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1454             if (hci_stack->eir_data){
1455                 // copy items and expand '00:00:00:00:00:00' in name with bd_addr
1456                 ad_context_t context;
1457                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
1458                     uint8_t data_type   = ad_iterator_get_data_type(&context);
1459                     uint8_t size        = ad_iterator_get_data_len(&context);
1460                     const uint8_t *data = ad_iterator_get_data(&context);
1461                     // copy item
1462                     packet[offset++] = size + 1;
1463                     packet[offset++] = data_type;
1464                     memcpy(&packet[offset], data, size);
1465                     // update name item
1466                     if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
1467                         btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
1468                     }
1469                     offset += size;
1470                 }
1471             } else {
1472                 uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1473                 uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
1474                 packet[offset++] = bytes_to_copy + 1;
1475                 packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1476                 (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
1477                 // expand '00:00:00:00:00:00' in name with bd_addr
1478                 btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
1479             }
1480             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1481             break;
1482         }
1483         case HCI_INIT_WRITE_INQUIRY_MODE:
1484             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1485             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1486             break;
1487         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
1488             hci_send_cmd(&hci_write_secure_connections_host_support, 1);
1489 			hci_stack->secure_connections_active = true;
1490             hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
1491             break;
1492         case HCI_INIT_WRITE_SCAN_ENABLE:
1493             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1494             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1495             break;
1496         // only sent if ENABLE_SCO_OVER_HCI is defined
1497         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1498             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1499             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1500             break;
1501         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1502             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1503             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1504             break;
1505         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
1506         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1507             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1508 #ifdef ENABLE_SCO_OVER_HCI
1509             log_info("BCM: Route SCO data via HCI transport");
1510             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1511 #endif
1512 #ifdef ENABLE_SCO_OVER_PCM
1513             log_info("BCM: Route SCO data via PCM interface");
1514 #ifdef ENABLE_BCM_PCM_WBS
1515             // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
1516             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
1517 #else
1518             // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
1519             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
1520 #endif
1521 #endif
1522             break;
1523 #ifdef ENABLE_SCO_OVER_PCM
1524         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
1525             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
1526             log_info("BCM: Config PCM interface for I2S");
1527 #ifdef ENABLE_BCM_PCM_WBS
1528             // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
1529             hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
1530 #else
1531             // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
1532             hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
1533 #endif
1534             break;
1535 #endif
1536 #endif
1537 
1538 #ifdef ENABLE_BLE
1539         // LE INIT
1540         case HCI_INIT_LE_READ_BUFFER_SIZE:
1541             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1542             hci_send_cmd(&hci_le_read_buffer_size);
1543             break;
1544         case HCI_INIT_LE_SET_EVENT_MASK:
1545             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1546             hci_send_cmd(&hci_le_set_event_mask, 0x809FF, 0x0); // bits 0-8, 11, 19
1547             break;
1548         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1549             // LE Supported Host = 1, Simultaneous Host = 0
1550             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1551             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1552             break;
1553 #endif
1554 
1555 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1556         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1557             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1558             hci_send_cmd(&hci_le_read_maximum_data_length);
1559             break;
1560         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1561             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1562             hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1563             break;
1564 #endif
1565 
1566 #ifdef ENABLE_LE_CENTRAL
1567         case HCI_INIT_READ_WHITE_LIST_SIZE:
1568             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1569             hci_send_cmd(&hci_le_read_white_list_size);
1570             break;
1571         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1572             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1573             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
1574             break;
1575 #endif
1576         default:
1577             return;
1578     }
1579 }
1580 
1581 static void hci_init_done(void){
1582     // done. tell the app
1583     log_info("hci_init_done -> HCI_STATE_WORKING");
1584     hci_stack->state = HCI_STATE_WORKING;
1585     hci_emit_state();
1586     hci_run();
1587 }
1588 
1589 static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
1590     bool command_completed = false;
1591     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1592         uint16_t opcode = little_endian_read_16(packet,3);
1593         if (opcode == hci_stack->last_cmd_opcode){
1594             command_completed = true;
1595             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1596         } else {
1597             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1598         }
1599     }
1600 
1601     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1602         uint8_t  status = packet[2];
1603         uint16_t opcode = little_endian_read_16(packet,4);
1604         if (opcode == hci_stack->last_cmd_opcode){
1605             if (status){
1606                 command_completed = true;
1607                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1608             } else {
1609                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1610             }
1611         } else {
1612             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1613         }
1614     }
1615 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1616     // Vendor == CSR
1617     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
1618         // TODO: track actual command
1619         command_completed = true;
1620     }
1621 
1622     // Vendor == Toshiba
1623     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
1624         // TODO: track actual command
1625         command_completed = true;
1626         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1627         hci_stack->num_cmd_packets = 1;
1628     }
1629 #endif
1630 
1631     return command_completed;
1632 }
1633 
1634 static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
1635 
1636     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
1637 
1638     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
1639 
1640 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1641 
1642     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1643     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1644     //
1645     // HCI Reset
1646     // Timeout 100 ms
1647     // HCI Reset
1648     // Command Complete Reset
1649     // HCI Read Local Version Information
1650     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1651     // hang...
1652     //
1653     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1654     if (!command_completed
1655             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
1656             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
1657 
1658         uint16_t opcode = little_endian_read_16(packet,3);
1659         if (opcode == hci_reset.opcode){
1660             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1661             return;
1662         }
1663     }
1664 
1665     // CSR & H5
1666     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1667     if (!command_completed
1668             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
1669             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
1670 
1671         uint16_t opcode = little_endian_read_16(packet,3);
1672         if (opcode == hci_reset.opcode){
1673             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1674             return;
1675         }
1676     }
1677 
1678     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1679     // fix: Correct substate and behave as command below
1680     if (command_completed){
1681         switch (hci_stack->substate){
1682             case HCI_INIT_SEND_RESET:
1683                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1684                 break;
1685             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1686                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1687                 break;
1688             default:
1689                 break;
1690         }
1691     }
1692 
1693 #endif
1694 
1695     if (!command_completed) return;
1696 
1697     bool need_baud_change = false;
1698     bool need_addr_change = false;
1699 
1700 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1701     need_baud_change = hci_stack->config
1702                         && hci_stack->chipset
1703                         && hci_stack->chipset->set_baudrate_command
1704                         && hci_stack->hci_transport->set_baudrate
1705                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1706 
1707     need_addr_change = hci_stack->custom_bd_addr_set
1708                         && hci_stack->chipset
1709                         && hci_stack->chipset->set_bd_addr_command;
1710 #endif
1711 
1712     switch(hci_stack->substate){
1713 
1714 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1715         case HCI_INIT_SEND_RESET:
1716             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1717             // fix: just correct substate and behave as command below
1718             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1719             btstack_run_loop_remove_timer(&hci_stack->timeout);
1720             break;
1721         case HCI_INIT_W4_SEND_RESET:
1722             btstack_run_loop_remove_timer(&hci_stack->timeout);
1723             break;
1724         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1725             log_info("Received local name, need baud change %d", (int) need_baud_change);
1726             if (need_baud_change){
1727                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1728                 return;
1729             }
1730             // skip baud change
1731             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1732             return;
1733         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1734             // for STLC2500D, baud rate change already happened.
1735             // for others, baud rate gets changed now
1736             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1737                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1738                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
1739                 hci_stack->hci_transport->set_baudrate(baud_rate);
1740             }
1741             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1742             return;
1743         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1744             btstack_run_loop_remove_timer(&hci_stack->timeout);
1745             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1746             return;
1747         case HCI_INIT_W4_CUSTOM_INIT:
1748             // repeat custom init
1749             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1750             return;
1751 #else
1752         case HCI_INIT_W4_SEND_RESET:
1753             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1754             return ;
1755 #endif
1756 
1757         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1758             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1759               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1760                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1761                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1762                 return;
1763             }
1764             if (need_addr_change){
1765                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1766                 return;
1767             }
1768             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1769             return;
1770 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1771         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1772             if (need_baud_change){
1773                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1774                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
1775                 hci_stack->hci_transport->set_baudrate(baud_rate);
1776             }
1777             if (need_addr_change){
1778                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1779                 return;
1780             }
1781             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1782             return;
1783         case HCI_INIT_W4_SET_BD_ADDR:
1784             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1785             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1786             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1787                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1788                 return;
1789             }
1790             // skipping st warm boot
1791             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1792             return;
1793         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1794             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1795             return;
1796 #endif
1797         case HCI_INIT_W4_READ_BD_ADDR:
1798             // only read buffer size if supported
1799             if (hci_stack->local_supported_commands[0u] & 0x01u) {
1800                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1801                 return;
1802             }
1803             // skipping read buffer size
1804             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1805             return;
1806         case HCI_INIT_W4_SET_EVENT_MASK:
1807             // skip Classic init commands for LE only chipsets
1808             if (!hci_classic_supported()){
1809 #ifdef ENABLE_BLE
1810                 if (hci_le_supported()){
1811                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1812                     return;
1813                 }
1814 #endif
1815                 log_error("Neither BR/EDR nor LE supported");
1816                 hci_init_done();
1817                 return;
1818             }
1819             if (!gap_ssp_supported()){
1820                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1821                 return;
1822             }
1823             break;
1824 #ifdef ENABLE_BLE
1825         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1826             // skip write le host if not supported (e.g. on LE only EM9301)
1827             if (hci_stack->local_supported_commands[0u] & 0x02u) break;
1828             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1829             return;
1830 
1831 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1832         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
1833             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
1834             if ((hci_stack->local_supported_commands[0u] & 0x30u) == 0x30u){
1835                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1836                 return;
1837             }
1838             // explicit fall through to reduce repetitions
1839 
1840 #ifdef ENABLE_LE_CENTRAL
1841             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1842 #else
1843             hci_init_done();
1844 #endif
1845             return;
1846 #endif  /* ENABLE_LE_DATA_LENGTH_EXTENSION */
1847 
1848 #endif  /* ENABLE_BLE */
1849 
1850         case HCI_INIT_W4_WRITE_INQUIRY_MODE:
1851             // skip write secure connections host support if not supported or disabled
1852             if (!hci_stack->secure_connections_enable || (hci_stack->local_supported_commands[1u] & 0x02u) == 0u) {
1853                 hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;
1854                 return;
1855             }
1856             break;
1857 
1858 #ifdef ENABLE_SCO_OVER_HCI
1859         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1860             // skip write synchronous flow control if not supported
1861             if (hci_stack->local_supported_commands[0] & 0x04) break;
1862             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1863 
1864             /* fall through */
1865 
1866         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1867             // skip write default erroneous data reporting if not supported
1868             if (hci_stack->local_supported_commands[0] & 0x08) break;
1869             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1870 
1871             /* fall through */
1872 
1873         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1874             // skip bcm set sco pcm config on non-Broadcom chipsets
1875             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1876             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1877 
1878             /* fall through */
1879 
1880         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1881             if (!hci_le_supported()){
1882                 // SKIP LE init for Classic only configuration
1883                 hci_init_done();
1884                 return;
1885             }
1886             break;
1887 
1888 #else /* !ENABLE_SCO_OVER_HCI */
1889 
1890         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1891 #ifdef ENABLE_SCO_OVER_PCM
1892             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) {
1893                 hci_stack->substate = HCI_INIT_BCM_WRITE_SCO_PCM_INT;
1894                 return;
1895             }
1896 #endif
1897             /* fall through */
1898 
1899         case HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
1900 #ifdef ENABLE_BLE
1901             if (hci_le_supported()){
1902                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1903                 return;
1904             }
1905 #endif
1906             // SKIP LE init for Classic only configuration
1907             hci_init_done();
1908             return;
1909 #endif /* ENABLE_SCO_OVER_HCI */
1910 
1911 // avoid compile error due to duplicate cases: HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT == HCI_INIT_DONE-1
1912 #if defined(ENABLE_BLE) || defined(ENABLE_LE_DATA_LENGTH_EXTENSION) || defined(ENABLE_LE_CENTRAL)
1913         // Response to command before init done state -> init done
1914         case (HCI_INIT_DONE-1):
1915             hci_init_done();
1916             return;
1917 #endif
1918 
1919         default:
1920             break;
1921     }
1922     hci_initializing_next_state();
1923 }
1924 
1925 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
1926     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
1927     bd_addr_t bd_address;
1928     (void)memcpy(&bd_address, conn->address, 6);
1929 
1930 #ifdef ENABLE_CLASSIC
1931     // cache needed data
1932     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1933 #endif
1934 
1935     // connection failed, remove entry
1936     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1937     btstack_memory_hci_connection_free( conn );
1938 
1939 #ifdef ENABLE_CLASSIC
1940     // notify client if dedicated bonding
1941     if (notify_dedicated_bonding_failed){
1942         log_info("hci notify_dedicated_bonding_failed");
1943         hci_emit_dedicated_bonding_result(bd_address, status);
1944     }
1945 
1946     // if authentication error, also delete link key
1947     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
1948         gap_drop_link_key_for_bd_addr(bd_address);
1949     }
1950 #else
1951     UNUSED(status);
1952 #endif
1953 }
1954 
1955 #ifdef ENABLE_CLASSIC
1956 static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
1957     // SSP Controller
1958     if (features[6] & (1 << 3)){
1959         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
1960     }
1961     // eSCO
1962     if (features[3] & (1<<7)){
1963         conn->remote_supported_features[0] |= 1;
1964     }
1965     // Extended features
1966     if (features[7] & (1<<7)){
1967         conn->remote_supported_features[0] |= 2;
1968     }
1969 }
1970 
1971 static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
1972     // SSP Host
1973     if (features[0] & (1 << 0)){
1974         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
1975     }
1976     // SC Host
1977     if (features[0] & (1 << 3)){
1978         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
1979     }
1980 }
1981 
1982 static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
1983     // SC Controller
1984     if (features[1] & (1 << 0)){
1985         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
1986     }
1987 }
1988 
1989 static void hci_handle_remote_features_received(hci_connection_t * conn){
1990     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1991     log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags);
1992     if (conn->bonding_flags & BONDING_DEDICATED){
1993         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1994     }
1995 }
1996 #endif
1997 
1998 static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
1999     // handle BT initialization
2000     if (hci_stack->state == HCI_STATE_INITIALIZING) {
2001         hci_initializing_event_handler(packet, size);
2002     }
2003 
2004     // help with BT sleep
2005     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
2006         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
2007         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)) {
2008         hci_initializing_next_state();
2009     }
2010 }
2011 
2012 #ifdef ENABLE_CLASSIC
2013 static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
2014     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2015     conn->encryption_key_size = encryption_key_size;
2016 
2017     if ((conn->authentication_flags & CONNECTION_AUTHENTICATED) != 0) {
2018         hci_emit_security_level(conn->con_handle, gap_security_level_for_connection(conn));
2019         return;
2020     }
2021 
2022     // Request Authentication if not already done
2023     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
2024     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2025 }
2026 #endif
2027 
2028 static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2029     UNUSED(size);
2030 
2031     uint16_t manufacturer;
2032 #ifdef ENABLE_CLASSIC
2033     hci_con_handle_t handle;
2034     hci_connection_t * conn;
2035     uint8_t status;
2036 #endif
2037     // get num cmd packets - limit to 1 to reduce complexity
2038     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
2039 
2040     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2041     switch (opcode){
2042         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2043             if (packet[5]) break;
2044             // terminate, name 248 chars
2045             packet[6+248] = 0;
2046             log_info("local name: %s", &packet[6]);
2047             break;
2048         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
2049             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2050             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2051                 uint16_t acl_len = little_endian_read_16(packet, 6);
2052                 uint16_t sco_len = packet[8];
2053 
2054                 // determine usable ACL/SCO payload size
2055                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2056                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2057 
2058                 hci_stack->acl_packets_total_num = little_endian_read_16(packet, 9);
2059                 hci_stack->sco_packets_total_num = little_endian_read_16(packet, 11);
2060 
2061                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2062                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
2063                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2064             }
2065             break;
2066         case HCI_OPCODE_HCI_READ_RSSI:
2067             if (packet[5] == ERROR_CODE_SUCCESS){
2068                 uint8_t event[5];
2069                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2070                 event[1] = 3;
2071                 (void)memcpy(&event[2], &packet[6], 3);
2072                 hci_emit_event(event, sizeof(event), 1);
2073             }
2074             break;
2075 #ifdef ENABLE_BLE
2076         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2077             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2078             hci_stack->le_acl_packets_total_num = packet[8];
2079             // determine usable ACL payload size
2080             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
2081                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
2082             }
2083             log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
2084             break;
2085 #endif
2086 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2087         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2088             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2089             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2090             log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
2091             break;
2092 #endif
2093 #ifdef ENABLE_LE_CENTRAL
2094         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2095             hci_stack->le_whitelist_capacity = packet[6];
2096             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2097             break;
2098 #endif
2099         case HCI_OPCODE_HCI_READ_BD_ADDR:
2100             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2101             log_info("Local Address, Status: 0x%02x: Addr: %s", packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
2102 #ifdef ENABLE_CLASSIC
2103             if (hci_stack->link_key_db){
2104                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
2105             }
2106 #endif
2107             break;
2108 #ifdef ENABLE_CLASSIC
2109         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
2110             hci_emit_discoverable_enabled(hci_stack->discoverable);
2111             break;
2112         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2113             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2114                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2115                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2116                 hci_emit_event(event, sizeof(event), 1);
2117             }
2118             break;
2119 #endif
2120         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
2121             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
2122 
2123 #ifdef ENABLE_CLASSIC
2124             // determine usable ACL packet types based on host buffer size and supported features
2125             hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
2126             log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
2127 #endif
2128             // Classic/LE
2129             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2130             break;
2131         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2132             manufacturer = little_endian_read_16(packet, 10);
2133             // map Cypress to Broadcom
2134             if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2135                 log_info("Treat Cypress as Broadcom");
2136                 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2137                 little_endian_store_16(packet, 10, manufacturer);
2138             }
2139             hci_stack->manufacturer = manufacturer;
2140             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2141             break;
2142         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2143             hci_stack->local_supported_commands[0] =
2144                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+14u] & 0x80u) >> 7u) |  // bit  0 = Octet 14, bit 7 / Read Buffer Size
2145                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+24u] & 0x40u) >> 5u) |  // bit  1 = Octet 24, bit 6 / Write Le Host Supported
2146                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+10u] & 0x10u) >> 2u) |  // bit  2 = Octet 10, bit 4 / Write Synchronous Flow Control Enable
2147                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+18u] & 0x08u)     )  |  // bit  3 = Octet 18, bit 3 / Write Default Erroneous Data Reporting
2148                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+34u] & 0x01u) << 4u) |  // bit  4 = Octet 34, bit 0 / LE Write Suggested Default Data Length
2149                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x08u) << 2u) |  // bit  5 = Octet 35, bit 3 / LE Read Maximum Data Length
2150                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x20u) << 1u) |  // bit  6 = Octet 35, bit 5 / LE Set Default PHY
2151                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+20u] & 0x10u) << 3u);   // bit  7 = Octet 20, bit 4 / Read Encryption Key Size
2152             hci_stack->local_supported_commands[1] =
2153                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+ 2u] & 0x40u) >> 6u) |  // bit  8 = Octet  2, bit 6 / Read Remote Extended Features
2154                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x08u) >> 2u) |  // bit  9 = Octet 32, bit 3 / Write Secure Connections Host
2155                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x02u) << 1u) |  // bit 10 = Octet 35, bit 1 / LE Set Address Resolution Enable
2156                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x02u) << 2u) |  // bit 11 = Octet 32, bit 1 / Remote OOB Extended Data Request Reply
2157                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x40u) >> 2u);   // bit 12 = Octet 32, bit 6 / Read Local OOB Extended Data command
2158             log_info("Local supported commands summary %02x - %02x", hci_stack->local_supported_commands[0],  hci_stack->local_supported_commands[1]);
2159             break;
2160 #ifdef ENABLE_CLASSIC
2161         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2162             if (packet[5]) return;
2163             hci_stack->synchronous_flow_control_enabled = 1;
2164             break;
2165         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2166             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2167             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2168             conn   = hci_connection_for_handle(handle);
2169             if (conn != NULL) {
2170                 uint8_t key_size = 0;
2171                 if (status == 0){
2172                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
2173                     log_info("Handle %04x key Size: %u", handle, key_size);
2174                 } else {
2175                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2176                 }
2177                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2178             }
2179             break;
2180 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2181         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
2182         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
2183             uint8_t event[67];
2184             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
2185             event[1] = 65;
2186             (void)memset(&event[2], 0, 65);
2187             if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){
2188                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
2189                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
2190                     event[2] = 3;
2191                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
2192                 } else {
2193                     event[2] = 1;
2194                 }
2195             }
2196             hci_emit_event(event, sizeof(event), 0);
2197             break;
2198         }
2199 #endif
2200 #endif
2201         default:
2202             break;
2203     }
2204 }
2205 
2206 #ifdef ENABLE_BLE
2207 static void event_handle_le_connection_complete(const uint8_t * packet){
2208 	bd_addr_t addr;
2209 	bd_addr_type_t addr_type;
2210 	hci_connection_t * conn;
2211 
2212 	// Connection management
2213 	reverse_bd_addr(&packet[8], addr);
2214 	addr_type = (bd_addr_type_t)packet[7];
2215 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2216 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2217 
2218 #ifdef ENABLE_LE_CENTRAL
2219 	// handle error: error is reported only to the initiator -> outgoing connection
2220 	if (packet[3]){
2221 
2222 		// handle cancelled outgoing connection
2223 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2224 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2225 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2226 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2227 			// whitelist connect
2228 			if (hci_is_le_connection_type(addr_type)){
2229 				hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2230 			}
2231 			// get outgoing connection conn struct for direct connect
2232 			conn = gap_get_outgoing_connection();
2233 		}
2234 
2235 		// outgoing le connection establishment is done
2236 		if (conn){
2237 			// remove entry
2238 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2239 			btstack_memory_hci_connection_free( conn );
2240 		}
2241 		return;
2242 	}
2243 #endif
2244 
2245 	// on success, both hosts receive connection complete event
2246 	if (packet[6] == HCI_ROLE_MASTER){
2247 #ifdef ENABLE_LE_CENTRAL
2248 		// if we're master on an le connection, it was an outgoing connection and we're done with it
2249 		// note: no hci_connection_t object exists yet for connect with whitelist
2250 		if (hci_is_le_connection_type(addr_type)){
2251 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2252 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2253 		}
2254 #endif
2255 	} else {
2256 #ifdef ENABLE_LE_PERIPHERAL
2257 		// if we're slave, it was an incoming connection, advertisements have stopped
2258 		hci_stack->le_advertisements_active = false;
2259 #endif
2260 	}
2261 
2262 	// LE connections are auto-accepted, so just create a connection if there isn't one already
2263 	if (!conn){
2264 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2265 	}
2266 
2267 	// no memory, sorry.
2268 	if (!conn){
2269 		return;
2270 	}
2271 
2272 	conn->state = OPEN;
2273 	conn->role  = packet[6];
2274 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
2275 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
2276 
2277 #ifdef ENABLE_LE_PERIPHERAL
2278 	if (packet[6] == HCI_ROLE_SLAVE){
2279 		hci_update_advertisements_enabled_for_current_roles();
2280 	}
2281 #endif
2282 
2283     // init unenhanced att bearer mtu
2284     conn->att_connection.mtu = ATT_DEFAULT_MTU;
2285     conn->att_connection.mtu_exchanged = false;
2286 
2287     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2288 
2289 	// restart timer
2290 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2291 	// btstack_run_loop_add_timer(&conn->timeout);
2292 
2293 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2294 
2295 	hci_emit_nr_connections_changed();
2296 }
2297 #endif
2298 
2299 static void event_handler(uint8_t *packet, uint16_t size){
2300 
2301     uint16_t event_length = packet[1];
2302 
2303     // assert packet is complete
2304     if (size != (event_length + 2u)){
2305         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
2306         return;
2307     }
2308 
2309     bd_addr_type_t addr_type;
2310     hci_con_handle_t handle;
2311     hci_connection_t * conn;
2312     int i;
2313     int create_connection_cmd;
2314 
2315 #ifdef ENABLE_CLASSIC
2316     hci_link_type_t link_type;
2317     bd_addr_t addr;
2318 #endif
2319 
2320     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
2321 
2322     switch (hci_event_packet_get_type(packet)) {
2323 
2324         case HCI_EVENT_COMMAND_COMPLETE:
2325             handle_command_complete_event(packet, size);
2326             break;
2327 
2328         case HCI_EVENT_COMMAND_STATUS:
2329             // get num cmd packets - limit to 1 to reduce complexity
2330             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2331 
2332             // check command status to detected failed outgoing connections
2333             create_connection_cmd = 0;
2334 #ifdef ENABLE_CLASSIC
2335             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2336                 create_connection_cmd = 1;
2337             }
2338 #endif
2339 #ifdef ENABLE_LE_CENTRAL
2340             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
2341                 create_connection_cmd = 1;
2342             }
2343 #endif
2344             if (create_connection_cmd) {
2345                 uint8_t status = hci_event_command_status_get_status(packet);
2346                 addr_type = hci_stack->outgoing_addr_type;
2347                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
2348                 log_info("command status (create connection), status %x, connection %p, addr %s, type %x", status, conn, bd_addr_to_str(hci_stack->outgoing_addr), addr_type);
2349 
2350                 // reset outgoing address info
2351                 memset(hci_stack->outgoing_addr, 0, 6);
2352                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2353 
2354                 // on error
2355                 if (status != ERROR_CODE_SUCCESS){
2356 #ifdef ENABLE_LE_CENTRAL
2357                     if (hci_is_le_connection_type(addr_type)){
2358                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2359                     }
2360 #endif
2361                     // error => outgoing connection failed
2362                     if (conn != NULL){
2363                         hci_handle_connection_failed(conn, status);
2364                     }
2365                 }
2366             }
2367             break;
2368 
2369         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
2370             if (size < 3) return;
2371             uint16_t num_handles = packet[2];
2372             if (size != (3u + num_handles * 4u)) return;
2373             uint16_t offset = 3;
2374             for (i=0; i<num_handles;i++){
2375                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
2376                 offset += 2u;
2377                 uint16_t num_packets = little_endian_read_16(packet, offset);
2378                 offset += 2u;
2379 
2380                 conn = hci_connection_for_handle(handle);
2381                 if (!conn){
2382                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
2383                     continue;
2384                 }
2385 
2386                 if (conn->num_packets_sent >= num_packets){
2387                     conn->num_packets_sent -= num_packets;
2388                 } else {
2389                     log_error("hci_number_completed_packets, more packet slots freed then sent.");
2390                     conn->num_packets_sent = 0;
2391                 }
2392                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
2393 
2394 #ifdef ENABLE_CLASSIC
2395                 // For SCO, we do the can_send_now_check here
2396                 hci_notify_if_sco_can_send_now();
2397 #endif
2398             }
2399             break;
2400         }
2401 
2402 #ifdef ENABLE_CLASSIC
2403         case HCI_EVENT_INQUIRY_COMPLETE:
2404             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2405                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2406                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2407                 hci_emit_event(event, sizeof(event), 1);
2408             }
2409             break;
2410         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2411             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2412                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2413             }
2414             break;
2415         case HCI_EVENT_CONNECTION_REQUEST:
2416             reverse_bd_addr(&packet[2], addr);
2417             link_type = (hci_link_type_t) packet[11];
2418             if (hci_stack->gap_classic_accept_callback != NULL){
2419                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
2420                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
2421                     bd_addr_copy(hci_stack->decline_addr, addr);
2422                     break;
2423                 }
2424             }
2425 
2426             // TODO: eval COD 8-10
2427             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
2428             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
2429             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2430             if (!conn) {
2431                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2432             }
2433             if (!conn) {
2434                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
2435                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
2436                 bd_addr_copy(hci_stack->decline_addr, addr);
2437                 break;
2438             }
2439             conn->role  = HCI_ROLE_SLAVE;
2440             conn->state = RECEIVED_CONNECTION_REQUEST;
2441             // store info about eSCO
2442             if (link_type == HCI_LINK_TYPE_ESCO){
2443                 conn->remote_supported_features[0] |= 1;
2444             }
2445             hci_run();
2446             break;
2447 
2448         case HCI_EVENT_CONNECTION_COMPLETE:
2449             // Connection management
2450             reverse_bd_addr(&packet[5], addr);
2451             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2452             addr_type = BD_ADDR_TYPE_ACL;
2453             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2454             if (conn) {
2455                 if (!packet[2]){
2456                     conn->state = OPEN;
2457                     conn->con_handle = little_endian_read_16(packet, 3);
2458 
2459                     // queue get remote feature
2460                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
2461 
2462                     // queue set supervision timeout if we're master
2463                     if ((hci_stack->link_supervision_timeout != 0) && (conn->role == HCI_ROLE_MASTER)){
2464                         connectionSetAuthenticationFlags(conn, WRITE_SUPERVISION_TIMEOUT);
2465                     }
2466 
2467                     // restart timer
2468                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2469                     btstack_run_loop_add_timer(&conn->timeout);
2470 
2471                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2472 
2473                     hci_emit_nr_connections_changed();
2474                 } else {
2475                     // connection failed
2476                     hci_handle_connection_failed(conn, packet[2]);
2477                 }
2478             }
2479             break;
2480 
2481         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2482             reverse_bd_addr(&packet[5], addr);
2483             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2484             if (packet[2]){
2485                 // connection failed
2486                 break;
2487             }
2488             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2489             if (!conn) {
2490                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2491             }
2492             if (!conn) {
2493                 break;
2494             }
2495             conn->state = OPEN;
2496             conn->con_handle = little_endian_read_16(packet, 3);
2497 
2498 #ifdef ENABLE_SCO_OVER_HCI
2499             // update SCO
2500             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2501                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2502             }
2503             // trigger can send now
2504             if (hci_have_usb_transport()){
2505                 hci_stack->sco_can_send_now = 1;
2506             }
2507 #endif
2508             break;
2509 
2510         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2511             handle = little_endian_read_16(packet, 3);
2512             conn = hci_connection_for_handle(handle);
2513             if (!conn) break;
2514             if (!packet[2]){
2515                 const uint8_t * features = &packet[5];
2516                 hci_handle_remote_features_page_0(conn, features);
2517 
2518                 // read extended features if possible
2519                 if (((hci_stack->local_supported_commands[1] & 1) != 0) && ((conn->remote_supported_features[0] & 2) != 0)) {
2520                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
2521                     break;
2522                 }
2523             }
2524             hci_handle_remote_features_received(conn);
2525             break;
2526 
2527         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
2528             handle = little_endian_read_16(packet, 3);
2529             conn = hci_connection_for_handle(handle);
2530             if (!conn) break;
2531             // status = ok, page = 1
2532             if (!packet[2]) {
2533                 uint8_t page_number = packet[5];
2534                 uint8_t maximum_page_number = packet[6];
2535                 const uint8_t * features = &packet[7];
2536                 bool done = false;
2537                 switch (page_number){
2538                     case 1:
2539                         hci_handle_remote_features_page_1(conn, features);
2540                         if (maximum_page_number >= 2){
2541                             // get Secure Connections (Controller) from Page 2 if available
2542                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
2543                         } else {
2544                             // otherwise, assume SC (Controller) == SC (Host)
2545                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
2546                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2547                             }
2548                             done = true;
2549                         }
2550                         break;
2551                     case 2:
2552                         hci_handle_remote_features_page_2(conn, features);
2553                         done = true;
2554                         break;
2555                     default:
2556                         break;
2557                 }
2558                 if (!done) break;
2559             }
2560             hci_handle_remote_features_received(conn);
2561             break;
2562 
2563         case HCI_EVENT_LINK_KEY_REQUEST:
2564             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2565             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2566             // request handled by hci_run()
2567             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2568             break;
2569 
2570         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2571             reverse_bd_addr(&packet[2], addr);
2572             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2573             if (!conn) break;
2574             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2575             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2576             // Change Connection Encryption keeps link key type
2577             if (link_key_type != CHANGED_COMBINATION_KEY){
2578                 conn->link_key_type = link_key_type;
2579             }
2580             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2581             // still forward event to allow dismiss of pairing dialog
2582             break;
2583         }
2584 
2585         case HCI_EVENT_PIN_CODE_REQUEST:
2586             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2587             // non-bondable mode: pin code negative reply will be sent
2588             if (!hci_stack->bondable){
2589                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2590                 hci_run();
2591                 return;
2592             }
2593             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2594             if (!hci_stack->link_key_db) break;
2595             hci_event_pin_code_request_get_bd_addr(packet, addr);
2596             hci_stack->link_key_db->delete_link_key(addr);
2597             break;
2598 
2599         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2600             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2601             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
2602 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
2603             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2604                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2605             } else {
2606                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2607             }
2608 #endif
2609             break;
2610 
2611 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2612         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
2613             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2614             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_REMOTE_OOB_DATA_REPLY);
2615             break;
2616 #endif
2617 
2618         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2619             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2620             if (!hci_stack->ssp_auto_accept) break;
2621             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2622             break;
2623 
2624         case HCI_EVENT_USER_PASSKEY_REQUEST:
2625             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2626             if (!hci_stack->ssp_auto_accept) break;
2627             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2628             break;
2629 
2630         case HCI_EVENT_MODE_CHANGE:
2631             handle = hci_event_mode_change_get_handle(packet);
2632             conn = hci_connection_for_handle(handle);
2633             if (!conn) break;
2634             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2635             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2636             break;
2637 #endif
2638 
2639         case HCI_EVENT_ENCRYPTION_CHANGE:
2640             handle = hci_event_encryption_change_get_connection_handle(packet);
2641             conn = hci_connection_for_handle(handle);
2642             if (!conn) break;
2643             if (hci_event_encryption_change_get_status(packet) == 0u) {
2644                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
2645                 if (encryption_enabled){
2646                     if (hci_is_le_connection(conn)){
2647                         // For LE, we accept connection as encrypted
2648                         conn->authentication_flags |= CONNECTION_ENCRYPTED;
2649                     }
2650 #ifdef ENABLE_CLASSIC
2651                     else {
2652                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
2653                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type) != 0;
2654                         bool connected_uses_aes_ccm = encryption_enabled == 2;
2655                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
2656                             log_info("SC during pairing, but only E0 now -> abort");
2657                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2658                             break;
2659                         }
2660 
2661                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
2662                         if (connected_uses_aes_ccm){
2663                             conn->authentication_flags |= CONNECTION_AUTHENTICATED;
2664                         }
2665 
2666                         if ((hci_stack->local_supported_commands[0] & 0x80) != 0){
2667                             // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
2668                             conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
2669                         } else {
2670                             // if not, pretend everything is perfect
2671                             hci_handle_read_encryption_key_size_complete(conn, 16);
2672                         }
2673                     }
2674 #endif
2675                 } else {
2676                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2677                 }
2678             }
2679 
2680             break;
2681 
2682 #ifdef ENABLE_CLASSIC
2683         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2684             handle = hci_event_authentication_complete_get_connection_handle(packet);
2685             conn = hci_connection_for_handle(handle);
2686             if (!conn) break;
2687 
2688             // ignore authentication event if we didn't request it
2689             if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) == 0) break;
2690 
2691             // dedicated bonding: send result and disconnect
2692             if (conn->bonding_flags & BONDING_DEDICATED){
2693                 conn->bonding_flags &= ~BONDING_DEDICATED;
2694                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2695                 conn->bonding_status = packet[2];
2696                 break;
2697             }
2698 
2699             // authenticated only if auth status == 0
2700             if (hci_event_authentication_complete_get_status(packet) == 0){
2701                 // authenticated
2702                 conn->authentication_flags |= CONNECTION_AUTHENTICATED;
2703 
2704                 // If link key sufficient for requested security and not already encrypted, start encryption
2705                 if (((gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level)) &&
2706                     ((conn->authentication_flags & CONNECTION_ENCRYPTED) == 0)){
2707                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2708                     break;
2709                 }
2710             }
2711 
2712             // emit updated security level
2713             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2714             break;
2715 #endif
2716 
2717         // HCI_EVENT_DISCONNECTION_COMPLETE
2718         // has been split, to first notify stack before shutting connection down
2719         // see end of function, too.
2720         case HCI_EVENT_DISCONNECTION_COMPLETE:
2721             if (packet[2]) break;   // status != 0
2722             handle = little_endian_read_16(packet, 3);
2723             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
2724             if (hci_stack->acl_fragmentation_total_size > 0u) {
2725                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2726                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
2727                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
2728                     hci_stack->acl_fragmentation_total_size = 0;
2729                     hci_stack->acl_fragmentation_pos = 0;
2730                     if (release_buffer){
2731                         hci_release_packet_buffer();
2732                     }
2733                 }
2734             }
2735 
2736             conn = hci_connection_for_handle(handle);
2737             if (!conn) break;
2738             // mark connection for shutdown
2739             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2740 
2741             // emit dedicatd bonding event
2742             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2743                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
2744             }
2745 
2746 #ifdef ENABLE_BLE
2747 #ifdef ENABLE_LE_PERIPHERAL
2748             // re-enable advertisements for le connections if active
2749             if (hci_is_le_connection(conn)){
2750                 hci_update_advertisements_enabled_for_current_roles();
2751             }
2752 #endif
2753 #endif
2754             break;
2755 
2756         case HCI_EVENT_HARDWARE_ERROR:
2757             log_error("Hardware Error: 0x%02x", packet[2]);
2758             if (hci_stack->hardware_error_callback){
2759                 (*hci_stack->hardware_error_callback)(packet[2]);
2760             } else {
2761                 // if no special requests, just reboot stack
2762                 hci_power_control_off();
2763                 hci_power_control_on();
2764             }
2765             break;
2766 
2767 #ifdef ENABLE_CLASSIC
2768         case HCI_EVENT_ROLE_CHANGE:
2769             if (packet[2]) break;   // status != 0
2770             reverse_bd_addr(&packet[3], addr);
2771             addr_type = BD_ADDR_TYPE_ACL;
2772             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2773             if (!conn) break;
2774             conn->role = packet[9];
2775             break;
2776 #endif
2777 
2778         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2779             // release packet buffer only for asynchronous transport and if there are not further fragements
2780             if (hci_transport_synchronous()) {
2781                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2782                 return; // instead of break: to avoid re-entering hci_run()
2783             }
2784             hci_stack->acl_fragmentation_tx_active = 0;
2785             if (hci_stack->acl_fragmentation_total_size) break;
2786             hci_release_packet_buffer();
2787 
2788             // L2CAP receives this event via the hci_emit_event below
2789 
2790 #ifdef ENABLE_CLASSIC
2791             // For SCO, we do the can_send_now_check here
2792             hci_notify_if_sco_can_send_now();
2793 #endif
2794             break;
2795 
2796 #ifdef ENABLE_CLASSIC
2797         case HCI_EVENT_SCO_CAN_SEND_NOW:
2798             // For SCO, we do the can_send_now_check here
2799             hci_stack->sco_can_send_now = 1;
2800             hci_notify_if_sco_can_send_now();
2801             return;
2802 
2803         // explode inquriy results for easier consumption
2804         case HCI_EVENT_INQUIRY_RESULT:
2805         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2806         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2807             gap_inquiry_explode(packet, size);
2808             break;
2809 #endif
2810 
2811 #ifdef ENABLE_BLE
2812         case HCI_EVENT_LE_META:
2813             switch (packet[2]){
2814 #ifdef ENABLE_LE_CENTRAL
2815                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2816                     // log_info("advertising report received");
2817                     if (!hci_stack->le_scanning_enabled) break;
2818                     le_handle_advertisement_report(packet, size);
2819                     break;
2820 #endif
2821                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2822 					event_handle_le_connection_complete(packet);
2823                     break;
2824 
2825                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2826                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
2827                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
2828                     conn = hci_connection_for_handle(handle);
2829                     if (!conn) break;
2830                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
2831                     break;
2832 
2833                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
2834                     // connection
2835                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
2836                     conn = hci_connection_for_handle(handle);
2837                     if (conn) {
2838                         // read arguments
2839                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
2840                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
2841                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
2842                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
2843 
2844                         // validate against current connection parameter range
2845                         le_connection_parameter_range_t existing_range;
2846                         gap_get_connection_parameter_range(&existing_range);
2847                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
2848                         if (update_parameter){
2849                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
2850                             conn->le_conn_interval_min = le_conn_interval_min;
2851                             conn->le_conn_interval_max = le_conn_interval_max;
2852                             conn->le_conn_latency = le_conn_latency;
2853                             conn->le_supervision_timeout = le_supervision_timeout;
2854                         } else {
2855                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
2856                         }
2857                     }
2858                     break;
2859 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
2860                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
2861                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
2862                     conn = hci_connection_for_handle(handle);
2863                     if (conn) {
2864                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
2865                     }
2866                     break;
2867 #endif
2868                 default:
2869                     break;
2870             }
2871             break;
2872 #endif
2873         case HCI_EVENT_VENDOR_SPECIFIC:
2874             // Vendor specific commands often create vendor specific event instead of num completed packets
2875             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
2876             switch (hci_stack->manufacturer){
2877                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
2878                     hci_stack->num_cmd_packets = 1;
2879                     break;
2880                 default:
2881                     break;
2882             }
2883             break;
2884         default:
2885             break;
2886     }
2887 
2888     handle_event_for_current_stack_state(packet, size);
2889 
2890     // notify upper stack
2891 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2892 
2893     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2894     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
2895 		handle = little_endian_read_16(packet, 3);
2896 		hci_connection_t * aConn = hci_connection_for_handle(handle);
2897 		// discard connection if app did not trigger a reconnect in the event handler
2898 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
2899 			hci_shutdown_connection(aConn);
2900 		}
2901     }
2902 
2903 	// execute main loop
2904 	hci_run();
2905 }
2906 
2907 #ifdef ENABLE_CLASSIC
2908 
2909 #ifdef ENABLE_SCO_OVER_HCI
2910 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
2911 static void sco_schedule_tx(hci_connection_t * conn);
2912 
2913 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
2914     log_debug("SCO TX Timeout");
2915     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
2916     hci_connection_t * conn = hci_connection_for_handle(con_handle);
2917     if (!conn) return;
2918 
2919     // trigger send
2920     conn->sco_tx_ready = 1;
2921     // extra packet if CVSD but SCO buffer is too short
2922     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
2923         conn->sco_tx_ready++;
2924     }
2925     hci_notify_if_sco_can_send_now();
2926 }
2927 
2928 
2929 #define SCO_TX_AFTER_RX_MS (6)
2930 
2931 static void sco_schedule_tx(hci_connection_t * conn){
2932 
2933     uint32_t now = btstack_run_loop_get_time_ms();
2934     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
2935     int time_delta_ms = sco_tx_ms - now;
2936 
2937     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
2938 
2939     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
2940     btstack_run_loop_set_timer(timer, time_delta_ms);
2941     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
2942     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
2943     btstack_run_loop_add_timer(timer);
2944 }
2945 #endif
2946 
2947 static void sco_handler(uint8_t * packet, uint16_t size){
2948     // lookup connection struct
2949     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2950     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
2951     if (!conn) return;
2952 
2953 #ifdef ENABLE_SCO_OVER_HCI
2954     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
2955     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
2956         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
2957             packet[2] = 0x3c;
2958             memmove(&packet[3], &packet[23], 63);
2959             size = 63;
2960         }
2961     }
2962 
2963     if (hci_have_usb_transport()){
2964         // Nothing to do
2965     } else {
2966         // log_debug("sco flow %u, handle 0x%04x, packets sent %u, bytes send %u", hci_stack->synchronous_flow_control_enabled, (int) con_handle, conn->num_packets_sent, conn->num_sco_bytes_sent);
2967         if (hci_stack->synchronous_flow_control_enabled == 0){
2968             uint32_t now = btstack_run_loop_get_time_ms();
2969 
2970             if (!conn->sco_rx_valid){
2971                 // ignore first 10 packets
2972                 conn->sco_rx_count++;
2973                 // log_debug("sco rx count %u", conn->sco_rx_count);
2974                 if (conn->sco_rx_count == 10) {
2975                     // use first timestamp as is and pretent it just started
2976                     conn->sco_rx_ms = now;
2977                     conn->sco_rx_valid = 1;
2978                     conn->sco_rx_count = 0;
2979                     sco_schedule_tx(conn);
2980                 }
2981             } else {
2982                 // track expected arrival timme
2983                 conn->sco_rx_count++;
2984                 conn->sco_rx_ms += 7;
2985                 int delta = (int32_t) (now - conn->sco_rx_ms);
2986                 if (delta > 0){
2987                     conn->sco_rx_ms++;
2988                 }
2989                 // log_debug("sco rx %u", conn->sco_rx_ms);
2990                 sco_schedule_tx(conn);
2991             }
2992         }
2993     }
2994 #endif
2995 
2996     // deliver to app
2997     if (hci_stack->sco_packet_handler) {
2998         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2999     }
3000 
3001 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3002     conn->num_packets_completed++;
3003     hci_stack->host_completed_packets = 1;
3004     hci_run();
3005 #endif
3006 }
3007 #endif
3008 
3009 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
3010     hci_dump_packet(packet_type, 1, packet, size);
3011     switch (packet_type) {
3012         case HCI_EVENT_PACKET:
3013             event_handler(packet, size);
3014             break;
3015         case HCI_ACL_DATA_PACKET:
3016             acl_handler(packet, size);
3017             break;
3018 #ifdef ENABLE_CLASSIC
3019         case HCI_SCO_DATA_PACKET:
3020             sco_handler(packet, size);
3021             break;
3022 #endif
3023         default:
3024             break;
3025     }
3026 }
3027 
3028 /**
3029  * @brief Add event packet handler.
3030  */
3031 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3032     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3033 }
3034 
3035 
3036 /** Register HCI packet handlers */
3037 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3038     hci_stack->acl_packet_handler = handler;
3039 }
3040 
3041 #ifdef ENABLE_CLASSIC
3042 /**
3043  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
3044  */
3045 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
3046     hci_stack->sco_packet_handler = handler;
3047 }
3048 #endif
3049 
3050 static void hci_state_reset(void){
3051     // no connections yet
3052     hci_stack->connections = NULL;
3053 
3054     // keep discoverable/connectable as this has been requested by the client(s)
3055     // hci_stack->discoverable = 0;
3056     // hci_stack->connectable = 0;
3057     // hci_stack->bondable = 1;
3058     // hci_stack->own_addr_type = 0;
3059 
3060     // buffer is free
3061     hci_stack->hci_packet_buffer_reserved = 0;
3062 
3063     // no pending cmds
3064     hci_stack->decline_reason = 0;
3065     hci_stack->new_scan_enable_value = 0xff;
3066 
3067     hci_stack->secure_connections_active = false;
3068 
3069 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3070     hci_stack->classic_read_local_oob_data = true;
3071 #endif
3072 
3073     // LE
3074 #ifdef ENABLE_BLE
3075     memset(hci_stack->le_random_address, 0, 6);
3076     hci_stack->le_random_address_set = 0;
3077 #endif
3078 #ifdef ENABLE_LE_CENTRAL
3079     hci_stack->le_scanning_active  = 0;
3080     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3081     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3082     hci_stack->le_whitelist_capacity = 0;
3083 #endif
3084 }
3085 
3086 #ifdef ENABLE_CLASSIC
3087 /**
3088  * @brief Configure Bluetooth hardware control. Has to be called before power on.
3089  */
3090 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
3091     // store and open remote device db
3092     hci_stack->link_key_db = link_key_db;
3093     if (hci_stack->link_key_db) {
3094         hci_stack->link_key_db->open();
3095     }
3096 }
3097 #endif
3098 
3099 void hci_init(const hci_transport_t *transport, const void *config){
3100 
3101 #ifdef HAVE_MALLOC
3102     if (!hci_stack) {
3103         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
3104     }
3105 #else
3106     hci_stack = &hci_stack_static;
3107 #endif
3108     memset(hci_stack, 0, sizeof(hci_stack_t));
3109 
3110     // reference to use transport layer implementation
3111     hci_stack->hci_transport = transport;
3112 
3113     // reference to used config
3114     hci_stack->config = config;
3115 
3116     // setup pointer for outgoing packet buffer
3117     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
3118 
3119     // max acl payload size defined in config.h
3120     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
3121 
3122     // register packet handlers with transport
3123     transport->register_packet_handler(&packet_handler);
3124 
3125     hci_stack->state = HCI_STATE_OFF;
3126 
3127     // class of device
3128     hci_stack->class_of_device = 0x007a020c; // Smartphone
3129 
3130     // bondable by default
3131     hci_stack->bondable = 1;
3132 
3133 #ifdef ENABLE_CLASSIC
3134     // classic name
3135     hci_stack->local_name = default_classic_name;
3136 
3137     // Master slave policy
3138     hci_stack->master_slave_policy = 1;
3139 
3140     // Allow Role Switch
3141     hci_stack->allow_role_switch = 1;
3142 
3143     // Default / minimum security level = 2
3144     hci_stack->gap_security_level = LEVEL_2;
3145 
3146     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3147     hci_stack->gap_required_encyrption_key_size = 7;
3148 #endif
3149 
3150     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
3151     hci_stack->ssp_enable = 1;
3152     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
3153     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
3154     hci_stack->ssp_auto_accept = 1;
3155 
3156     // Secure Connections: enable (requires support from Controller)
3157     hci_stack->secure_connections_enable = true;
3158 
3159     // voice setting - signed 16 bit pcm data with CVSD over the air
3160     hci_stack->sco_voice_setting = 0x60;
3161 
3162 #ifdef ENABLE_LE_CENTRAL
3163     // connection parameter to use for outgoing connections
3164     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3165     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3166     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3167     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3168     hci_stack->le_connection_latency      = 4;         // 4
3169     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3170     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3171     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
3172 
3173     // default LE Scanning
3174     hci_stack->le_scan_type     =   0x1; // active
3175     hci_stack->le_scan_interval = 0x1e0; // 300 ms
3176     hci_stack->le_scan_window   =  0x30; //  30 ms
3177 #endif
3178 
3179 #ifdef ENABLE_LE_PERIPHERAL
3180     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
3181 #endif
3182 
3183     // connection parameter range used to answer connection parameter update requests in l2cap
3184     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3185     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3186     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3187     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3188     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3189     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3190 
3191     hci_state_reset();
3192 }
3193 
3194 void hci_deinit(void){
3195 #ifdef HAVE_MALLOC
3196     if (hci_stack) {
3197         free(hci_stack);
3198     }
3199 #endif
3200     hci_stack = NULL;
3201 
3202 #ifdef ENABLE_CLASSIC
3203     disable_l2cap_timeouts = 0;
3204 #endif
3205 }
3206 
3207 /**
3208  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
3209  */
3210 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
3211     hci_stack->chipset = chipset_driver;
3212 
3213     // reset chipset driver - init is also called on power_up
3214     if (hci_stack->chipset && hci_stack->chipset->init){
3215         hci_stack->chipset->init(hci_stack->config);
3216     }
3217 }
3218 
3219 /**
3220  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3221  */
3222 void hci_set_control(const btstack_control_t *hardware_control){
3223     // references to used control implementation
3224     hci_stack->control = hardware_control;
3225     // init with transport config
3226     hardware_control->init(hci_stack->config);
3227 }
3228 
3229 void hci_close(void){
3230     // close remote device db
3231     if (hci_stack->link_key_db) {
3232         hci_stack->link_key_db->close();
3233     }
3234 
3235     btstack_linked_list_iterator_t lit;
3236     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
3237     while (btstack_linked_list_iterator_has_next(&lit)){
3238         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
3239         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
3240         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
3241         hci_shutdown_connection(connection);
3242     }
3243 
3244     hci_power_control(HCI_POWER_OFF);
3245 
3246 #ifdef HAVE_MALLOC
3247     free(hci_stack);
3248 #endif
3249     hci_stack = NULL;
3250 }
3251 
3252 #ifdef ENABLE_CLASSIC
3253 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3254     // validate ranage and set
3255     if (encryption_key_size < 7)  return;
3256     if (encryption_key_size > 16) return;
3257     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3258 }
3259 
3260 void gap_set_security_level(gap_security_level_t security_level){
3261     hci_stack->gap_security_level = security_level;
3262 }
3263 
3264 gap_security_level_t gap_get_security_level(void){
3265     return hci_stack->gap_security_level;
3266 }
3267 #endif
3268 
3269 #ifdef ENABLE_CLASSIC
3270 void gap_set_class_of_device(uint32_t class_of_device){
3271     hci_stack->class_of_device = class_of_device;
3272 }
3273 
3274 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3275     hci_stack->default_link_policy_settings = default_link_policy_settings;
3276 }
3277 
3278 void gap_set_allow_role_switch(bool allow_role_switch){
3279     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3280 }
3281 
3282 uint8_t hci_get_allow_role_switch(void){
3283     return  hci_stack->allow_role_switch;
3284 }
3285 
3286 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
3287     hci_stack->link_supervision_timeout = link_supervision_timeout;
3288 }
3289 
3290 void hci_disable_l2cap_timeout_check(void){
3291     disable_l2cap_timeouts = 1;
3292 }
3293 #endif
3294 
3295 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
3296 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3297 void hci_set_bd_addr(bd_addr_t addr){
3298     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3299     hci_stack->custom_bd_addr_set = 1;
3300 }
3301 #endif
3302 
3303 // State-Module-Driver overview
3304 // state                    module  low-level
3305 // HCI_STATE_OFF             off      close
3306 // HCI_STATE_INITIALIZING,   on       open
3307 // HCI_STATE_WORKING,        on       open
3308 // HCI_STATE_HALTING,        on       open
3309 // HCI_STATE_SLEEPING,    off/sleep   close
3310 // HCI_STATE_FALLING_ASLEEP  on       open
3311 
3312 static int hci_power_control_on(void){
3313 
3314     // power on
3315     int err = 0;
3316     if (hci_stack->control && hci_stack->control->on){
3317         err = (*hci_stack->control->on)();
3318     }
3319     if (err){
3320         log_error( "POWER_ON failed");
3321         hci_emit_hci_open_failed();
3322         return err;
3323     }
3324 
3325     // int chipset driver
3326     if (hci_stack->chipset && hci_stack->chipset->init){
3327         hci_stack->chipset->init(hci_stack->config);
3328     }
3329 
3330     // init transport
3331     if (hci_stack->hci_transport->init){
3332         hci_stack->hci_transport->init(hci_stack->config);
3333     }
3334 
3335     // open transport
3336     err = hci_stack->hci_transport->open();
3337     if (err){
3338         log_error( "HCI_INIT failed, turning Bluetooth off again");
3339         if (hci_stack->control && hci_stack->control->off){
3340             (*hci_stack->control->off)();
3341         }
3342         hci_emit_hci_open_failed();
3343         return err;
3344     }
3345     return 0;
3346 }
3347 
3348 static void hci_power_control_off(void){
3349 
3350     log_info("hci_power_control_off");
3351 
3352     // close low-level device
3353     hci_stack->hci_transport->close();
3354 
3355     log_info("hci_power_control_off - hci_transport closed");
3356 
3357     // power off
3358     if (hci_stack->control && hci_stack->control->off){
3359         (*hci_stack->control->off)();
3360     }
3361 
3362     log_info("hci_power_control_off - control closed");
3363 
3364     hci_stack->state = HCI_STATE_OFF;
3365 }
3366 
3367 static void hci_power_control_sleep(void){
3368 
3369     log_info("hci_power_control_sleep");
3370 
3371 #if 0
3372     // don't close serial port during sleep
3373 
3374     // close low-level device
3375     hci_stack->hci_transport->close(hci_stack->config);
3376 #endif
3377 
3378     // sleep mode
3379     if (hci_stack->control && hci_stack->control->sleep){
3380         (*hci_stack->control->sleep)();
3381     }
3382 
3383     hci_stack->state = HCI_STATE_SLEEPING;
3384 }
3385 
3386 static int hci_power_control_wake(void){
3387 
3388     log_info("hci_power_control_wake");
3389 
3390     // wake on
3391     if (hci_stack->control && hci_stack->control->wake){
3392         (*hci_stack->control->wake)();
3393     }
3394 
3395 #if 0
3396     // open low-level device
3397     int err = hci_stack->hci_transport->open(hci_stack->config);
3398     if (err){
3399         log_error( "HCI_INIT failed, turning Bluetooth off again");
3400         if (hci_stack->control && hci_stack->control->off){
3401             (*hci_stack->control->off)();
3402         }
3403         hci_emit_hci_open_failed();
3404         return err;
3405     }
3406 #endif
3407 
3408     return 0;
3409 }
3410 
3411 static void hci_power_transition_to_initializing(void){
3412     // set up state machine
3413     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
3414     hci_stack->hci_packet_buffer_reserved = 0;
3415     hci_stack->state = HCI_STATE_INITIALIZING;
3416     hci_stack->substate = HCI_INIT_SEND_RESET;
3417 }
3418 
3419 // returns error
3420 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
3421     int err;
3422     switch (power_mode){
3423         case HCI_POWER_ON:
3424             err = hci_power_control_on();
3425             if (err != 0) {
3426                 log_error("hci_power_control_on() error %d", err);
3427                 return err;
3428             }
3429             hci_power_transition_to_initializing();
3430             break;
3431         case HCI_POWER_OFF:
3432             // do nothing
3433             break;
3434         case HCI_POWER_SLEEP:
3435             // do nothing (with SLEEP == OFF)
3436             break;
3437         default:
3438             btstack_assert(false);
3439             break;
3440     }
3441     return ERROR_CODE_SUCCESS;
3442 }
3443 
3444 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
3445     switch (power_mode){
3446         case HCI_POWER_ON:
3447             // do nothing
3448             break;
3449         case HCI_POWER_OFF:
3450             // no connections yet, just turn it off
3451             hci_power_control_off();
3452             break;
3453         case HCI_POWER_SLEEP:
3454             // no connections yet, just turn it off
3455             hci_power_control_sleep();
3456             break;
3457         default:
3458             btstack_assert(false);
3459             break;
3460     }
3461     return ERROR_CODE_SUCCESS;
3462 }
3463 
3464 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
3465     switch (power_mode){
3466         case HCI_POWER_ON:
3467             // do nothing
3468             break;
3469         case HCI_POWER_OFF:
3470             // see hci_run
3471             hci_stack->state = HCI_STATE_HALTING;
3472             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3473             break;
3474         case HCI_POWER_SLEEP:
3475             // see hci_run
3476             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3477             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3478             break;
3479         default:
3480             btstack_assert(false);
3481             break;
3482     }
3483     return ERROR_CODE_SUCCESS;
3484 }
3485 
3486 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
3487     switch (power_mode){
3488         case HCI_POWER_ON:
3489             hci_power_transition_to_initializing();
3490             break;
3491         case HCI_POWER_OFF:
3492             // do nothing
3493             break;
3494         case HCI_POWER_SLEEP:
3495             // see hci_run
3496             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3497             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3498             break;
3499         default:
3500             btstack_assert(false);
3501             break;
3502     }
3503     return ERROR_CODE_SUCCESS;
3504 }
3505 
3506 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
3507     switch (power_mode){
3508         case HCI_POWER_ON:
3509 
3510 #ifdef HAVE_PLATFORM_IPHONE_OS
3511             // nothing to do, if H4 supports power management
3512                     if (btstack_control_iphone_power_management_enabled()){
3513                         hci_stack->state = HCI_STATE_INITIALIZING;
3514                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
3515                         break;
3516                     }
3517 #endif
3518             hci_power_transition_to_initializing();
3519             break;
3520         case HCI_POWER_OFF:
3521             // see hci_run
3522             hci_stack->state = HCI_STATE_HALTING;
3523             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3524             break;
3525         case HCI_POWER_SLEEP:
3526             // do nothing
3527             break;
3528         default:
3529             btstack_assert(false);
3530             break;
3531     }
3532     return ERROR_CODE_SUCCESS;
3533 }
3534 
3535 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
3536     int err;
3537     switch (power_mode){
3538         case HCI_POWER_ON:
3539 #ifdef HAVE_PLATFORM_IPHONE_OS
3540             // nothing to do, if H4 supports power management
3541                     if (btstack_control_iphone_power_management_enabled()){
3542                         hci_stack->state = HCI_STATE_INITIALIZING;
3543                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3544                         hci_update_scan_enable();
3545                         break;
3546                     }
3547 #endif
3548             err = hci_power_control_wake();
3549             if (err) return err;
3550             hci_power_transition_to_initializing();
3551             break;
3552         case HCI_POWER_OFF:
3553             hci_stack->state = HCI_STATE_HALTING;
3554             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3555             break;
3556         case HCI_POWER_SLEEP:
3557             // do nothing
3558             break;
3559         default:
3560             btstack_assert(false);
3561             break;
3562     }
3563     return ERROR_CODE_SUCCESS;
3564 }
3565 
3566 int hci_power_control(HCI_POWER_MODE power_mode){
3567     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
3568     int err = 0;
3569     switch (hci_stack->state){
3570         case HCI_STATE_OFF:
3571             err = hci_power_control_state_off(power_mode);
3572             break;
3573         case HCI_STATE_INITIALIZING:
3574             err = hci_power_control_state_initializing(power_mode);
3575             break;
3576         case HCI_STATE_WORKING:
3577             err = hci_power_control_state_working(power_mode);
3578             break;
3579         case HCI_STATE_HALTING:
3580             err = hci_power_control_state_halting(power_mode);
3581             break;
3582         case HCI_STATE_FALLING_ASLEEP:
3583             err = hci_power_control_state_falling_asleep(power_mode);
3584             break;
3585         case HCI_STATE_SLEEPING:
3586             err = hci_power_control_state_sleeping(power_mode);
3587             break;
3588         default:
3589             btstack_assert(false);
3590             break;
3591     }
3592     if (err != 0){
3593         return err;
3594     }
3595 
3596     // create internal event
3597 	hci_emit_state();
3598 
3599 	// trigger next/first action
3600 	hci_run();
3601 
3602     return 0;
3603 }
3604 
3605 
3606 #ifdef ENABLE_CLASSIC
3607 
3608 static void hci_update_scan_enable(void){
3609     // 2 = page scan, 1 = inq scan
3610     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
3611     hci_run();
3612 }
3613 
3614 void gap_discoverable_control(uint8_t enable){
3615     if (enable) enable = 1; // normalize argument
3616 
3617     if (hci_stack->discoverable == enable){
3618         hci_emit_discoverable_enabled(hci_stack->discoverable);
3619         return;
3620     }
3621 
3622     hci_stack->discoverable = enable;
3623     hci_update_scan_enable();
3624 }
3625 
3626 void gap_connectable_control(uint8_t enable){
3627     if (enable) enable = 1; // normalize argument
3628 
3629     // don't emit event
3630     if (hci_stack->connectable == enable) return;
3631 
3632     hci_stack->connectable = enable;
3633     hci_update_scan_enable();
3634 }
3635 #endif
3636 
3637 void gap_local_bd_addr(bd_addr_t address_buffer){
3638     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3639 }
3640 
3641 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3642 static void hci_host_num_completed_packets(void){
3643 
3644     // create packet manually as arrays are not supported and num_commands should not get reduced
3645     hci_reserve_packet_buffer();
3646     uint8_t * packet = hci_get_outgoing_packet_buffer();
3647 
3648     uint16_t size = 0;
3649     uint16_t num_handles = 0;
3650     packet[size++] = 0x35;
3651     packet[size++] = 0x0c;
3652     size++;  // skip param len
3653     size++;  // skip num handles
3654 
3655     // add { handle, packets } entries
3656     btstack_linked_item_t * it;
3657     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3658         hci_connection_t * connection = (hci_connection_t *) it;
3659         if (connection->num_packets_completed){
3660             little_endian_store_16(packet, size, connection->con_handle);
3661             size += 2;
3662             little_endian_store_16(packet, size, connection->num_packets_completed);
3663             size += 2;
3664             //
3665             num_handles++;
3666             connection->num_packets_completed = 0;
3667         }
3668     }
3669 
3670     packet[2] = size - 3;
3671     packet[3] = num_handles;
3672 
3673     hci_stack->host_completed_packets = 0;
3674 
3675     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3676     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3677 
3678     // release packet buffer for synchronous transport implementations
3679     if (hci_transport_synchronous()){
3680         hci_release_packet_buffer();
3681         hci_emit_transport_packet_sent();
3682     }
3683 }
3684 #endif
3685 
3686 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
3687     UNUSED(ds);
3688     hci_stack->substate = HCI_HALTING_CLOSE;
3689     // allow packet handlers to defer final shutdown
3690     hci_emit_state();
3691     hci_run();
3692 }
3693 
3694 static bool hci_run_acl_fragments(void){
3695     if (hci_stack->acl_fragmentation_total_size > 0u) {
3696         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3697         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3698         if (connection) {
3699             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3700                 hci_send_acl_packet_fragments(connection);
3701                 return true;
3702             }
3703         } else {
3704             // connection gone -> discard further fragments
3705             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3706             hci_stack->acl_fragmentation_total_size = 0;
3707             hci_stack->acl_fragmentation_pos = 0;
3708         }
3709     }
3710     return false;
3711 }
3712 
3713 #ifdef ENABLE_CLASSIC
3714 static bool hci_run_general_gap_classic(void){
3715 
3716     // decline incoming connections
3717     if (hci_stack->decline_reason){
3718         uint8_t reason = hci_stack->decline_reason;
3719         hci_stack->decline_reason = 0;
3720         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3721         return true;
3722     }
3723     // send scan enable
3724     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_scan_enable_value != 0xff) && hci_classic_supported()){
3725         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
3726         hci_stack->new_scan_enable_value = 0xff;
3727         return true;
3728     }
3729     // start/stop inquiry
3730     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
3731         uint8_t duration = hci_stack->inquiry_state;
3732         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3733         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3734         return true;
3735     }
3736     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3737         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3738         hci_send_cmd(&hci_inquiry_cancel);
3739         return true;
3740     }
3741     // remote name request
3742     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3743         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3744         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3745                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3746         return true;
3747     }
3748 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3749     // Local OOB data
3750     if ((hci_stack->state == HCI_STATE_WORKING) && hci_stack->classic_read_local_oob_data){
3751         hci_stack->classic_read_local_oob_data = false;
3752         if (hci_stack->local_supported_commands[1] & 0x10u){
3753             hci_send_cmd(&hci_read_local_extended_oob_data);
3754         } else {
3755             hci_send_cmd(&hci_read_local_oob_data);
3756         }
3757     }
3758 #endif
3759     // pairing
3760     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
3761         uint8_t state = hci_stack->gap_pairing_state;
3762         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3763         switch (state){
3764             case GAP_PAIRING_STATE_SEND_PIN:
3765                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, hci_stack->gap_pairing_input.gap_pairing_pin);
3766                 break;
3767             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
3768                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
3769                 break;
3770             case GAP_PAIRING_STATE_SEND_PASSKEY:
3771                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
3772                 break;
3773             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
3774                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
3775                 break;
3776             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
3777                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
3778                 break;
3779             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
3780                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
3781                 break;
3782             default:
3783                 break;
3784         }
3785         return true;
3786     }
3787     return false;
3788 }
3789 #endif
3790 
3791 #ifdef ENABLE_BLE
3792 static bool hci_run_general_gap_le(void){
3793 
3794     // advertisements, active scanning, and creating connections requires random address to be set if using private address
3795 
3796     if (hci_stack->state != HCI_STATE_WORKING) return false;
3797     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
3798 
3799 
3800     // Phase 1: collect what to stop
3801 
3802     bool scanning_stop = false;
3803     bool connecting_stop = false;
3804     bool advertising_stop = false;
3805 
3806 #ifndef ENABLE_LE_CENTRAL
3807     UNUSED(scanning_stop);
3808     UNUSED(connecting_stop);
3809 #endif
3810 #ifndef ENABLE_LE_PERIPHERAL
3811     UNUSED(advertising_stop);
3812 #endif
3813 
3814     // check if whitelist needs modification
3815     bool whitelist_modification_pending = false;
3816     btstack_linked_list_iterator_t lit;
3817     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3818     while (btstack_linked_list_iterator_has_next(&lit)){
3819         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3820         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3821             whitelist_modification_pending = true;
3822             break;
3823         }
3824     }
3825     // check if resolving list needs modification
3826     bool resolving_list_modification_pending = false;
3827 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
3828     bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0;
3829 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
3830         resolving_list_modification_pending = true;
3831     }
3832 #endif
3833 
3834 #ifdef ENABLE_LE_CENTRAL
3835     // scanning control
3836     if (hci_stack->le_scanning_active) {
3837         // stop if:
3838         // - parameter change required
3839         // - it's disabled
3840         // - whitelist change required but used for scanning
3841         // - resolving list modified
3842         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
3843         if ((hci_stack->le_scanning_param_update) ||
3844             !hci_stack->le_scanning_enabled ||
3845             scanning_uses_whitelist ||
3846             resolving_list_modification_pending){
3847 
3848             scanning_stop = true;
3849         }
3850     }
3851 #endif
3852 
3853 #ifdef ENABLE_LE_CENTRAL
3854     // connecting control
3855     bool connecting_with_whitelist;
3856     switch (hci_stack->le_connecting_state){
3857         case LE_CONNECTING_DIRECT:
3858         case LE_CONNECTING_WHITELIST:
3859             // stop connecting if:
3860             // - connecting uses white and whitelist modification pending
3861             // - if it got disabled
3862             // - resolving list modified
3863             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
3864             if ((connecting_with_whitelist && whitelist_modification_pending) ||
3865                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
3866                 resolving_list_modification_pending) {
3867 
3868                 connecting_stop = true;
3869             }
3870             break;
3871         default:
3872             break;
3873     }
3874 #endif
3875 
3876 #ifdef ENABLE_LE_PERIPHERAL
3877     // le advertisement control
3878     if (hci_stack->le_advertisements_active){
3879         // stop if:
3880         // - parameter change required
3881         // - it's disabled
3882         // - whitelist change required but used for advertisement filter policy
3883         // - resolving list modified
3884         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy > 0;
3885         if ((hci_stack->le_advertisements_todo != 0) ||
3886             !hci_stack->le_advertisements_enabled_for_current_roles ||
3887             (advertising_uses_whitelist & whitelist_modification_pending) ||
3888             resolving_list_modification_pending) {
3889 
3890             advertising_stop = true;
3891         }
3892     }
3893 #endif
3894 
3895 
3896     // Phase 2: stop everything that should be off during modifications
3897 
3898 #ifdef ENABLE_LE_CENTRAL
3899     if (scanning_stop){
3900         hci_stack->le_scanning_active = false;
3901         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
3902         return true;
3903     }
3904 #endif
3905 
3906 #ifdef ENABLE_LE_CENTRAL
3907     if (connecting_stop){
3908         hci_send_cmd(&hci_le_create_connection_cancel);
3909         return true;
3910     }
3911 #endif
3912 
3913 #ifdef ENABLE_LE_PERIPHERAL
3914     if (advertising_stop){
3915         hci_stack->le_advertisements_active = false;
3916         hci_send_cmd(&hci_le_set_advertise_enable, 0);
3917         return true;
3918     }
3919 #endif
3920 
3921     // Phase 3: modify
3922 
3923 #ifdef ENABLE_LE_CENTRAL
3924     if (hci_stack->le_scanning_param_update){
3925         hci_stack->le_scanning_param_update = false;
3926         hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
3927                      hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
3928         return true;
3929     }
3930 #endif
3931 
3932 #ifdef ENABLE_LE_PERIPHERAL
3933     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3934         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3935         hci_send_cmd(&hci_le_set_advertising_parameters,
3936                      hci_stack->le_advertisements_interval_min,
3937                      hci_stack->le_advertisements_interval_max,
3938                      hci_stack->le_advertisements_type,
3939                      hci_stack->le_own_addr_type,
3940                      hci_stack->le_advertisements_direct_address_type,
3941                      hci_stack->le_advertisements_direct_address,
3942                      hci_stack->le_advertisements_channel_map,
3943                      hci_stack->le_advertisements_filter_policy);
3944         return true;
3945     }
3946     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3947         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3948         uint8_t adv_data_clean[31];
3949         memset(adv_data_clean, 0, sizeof(adv_data_clean));
3950         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
3951                      hci_stack->le_advertisements_data_len);
3952         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
3953         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3954         return true;
3955     }
3956     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3957         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3958         uint8_t scan_data_clean[31];
3959         memset(scan_data_clean, 0, sizeof(scan_data_clean));
3960         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
3961                      hci_stack->le_scan_response_data_len);
3962         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
3963         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
3964         return true;
3965     }
3966 #endif
3967 
3968 
3969 #ifdef ENABLE_LE_CENTRAL
3970     // if connect with whitelist was active and is not cancelled yet, wait until next time
3971     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
3972 #endif
3973 
3974     // LE Whitelist Management
3975     if (whitelist_modification_pending){
3976         // add/remove entries
3977         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3978         while (btstack_linked_list_iterator_has_next(&lit)){
3979             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3980 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3981 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3982 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
3983 				return true;
3984 			}
3985             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3986 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
3987                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
3988                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3989                 return true;
3990             }
3991             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
3992 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3993 				btstack_memory_whitelist_entry_free(entry);
3994             }
3995         }
3996     }
3997 
3998 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
3999     // LE Resolving List Management
4000     if (resolving_list_supported) {
4001 		uint16_t i;
4002 		switch (hci_stack->le_resolving_list_state) {
4003 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
4004 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
4005 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
4006 				return true;
4007 			case LE_RESOLVING_LIST_READ_SIZE:
4008 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
4009 				hci_send_cmd(&hci_le_read_resolving_list_size);
4010 				return true;
4011 			case LE_RESOLVING_LIST_SEND_CLEAR:
4012 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
4013 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
4014 							  sizeof(hci_stack->le_resolving_list_add_entries));
4015 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
4016 							  sizeof(hci_stack->le_resolving_list_remove_entries));
4017 				hci_send_cmd(&hci_le_clear_resolving_list);
4018 				return true;
4019 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
4020 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4021 					uint8_t offset = i >> 3;
4022 					uint8_t mask = 1 << (i & 7);
4023 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
4024 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
4025 					bd_addr_t peer_identity_addreses;
4026 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4027 					sm_key_t peer_irk;
4028 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4029 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4030 
4031 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
4032 					// trigger whitelist entry 'update' (work around for controller bug)
4033 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4034 					while (btstack_linked_list_iterator_has_next(&lit)) {
4035 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
4036 						if (entry->address_type != peer_identity_addr_type) continue;
4037 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
4038 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
4039 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
4040 					}
4041 #endif
4042 
4043 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
4044 								 peer_identity_addreses);
4045 					return true;
4046 				}
4047 
4048 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
4049 
4050 				/* fall through */
4051 
4052 			case LE_RESOLVING_LIST_ADD_ENTRIES:
4053 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4054 					uint8_t offset = i >> 3;
4055 					uint8_t mask = 1 << (i & 7);
4056 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
4057 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
4058 					bd_addr_t peer_identity_addreses;
4059 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4060 					sm_key_t peer_irk;
4061 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4062 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4063 					const uint8_t *local_irk = gap_get_persistent_irk();
4064 					// command uses format specifier 'P' that stores 16-byte value without flip
4065 					uint8_t local_irk_flipped[16];
4066 					uint8_t peer_irk_flipped[16];
4067 					reverse_128(local_irk, local_irk_flipped);
4068 					reverse_128(peer_irk, peer_irk_flipped);
4069 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
4070 								 peer_irk_flipped, local_irk_flipped);
4071 					return true;
4072 				}
4073 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4074 				break;
4075 
4076 			default:
4077 				break;
4078 		}
4079 	}
4080     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4081 #endif
4082 
4083     // Phase 4: restore state
4084 
4085 #ifdef ENABLE_LE_CENTRAL
4086     // re-start scanning
4087     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
4088         hci_stack->le_scanning_active = true;
4089         hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
4090         return true;
4091     }
4092 #endif
4093 
4094 #ifdef ENABLE_LE_CENTRAL
4095     // re-start connecting
4096     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
4097         bd_addr_t null_addr;
4098         memset(null_addr, 0, 6);
4099         hci_send_cmd(&hci_le_create_connection,
4100                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
4101                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
4102                      1,         // use whitelist
4103                      0,         // peer address type
4104                      null_addr, // peer bd addr
4105                      hci_stack->le_own_addr_type, // our addr type:
4106                      hci_stack->le_connection_interval_min,    // conn interval min
4107                      hci_stack->le_connection_interval_max,    // conn interval max
4108                      hci_stack->le_connection_latency,         // conn latency
4109                      hci_stack->le_supervision_timeout,        // conn latency
4110                      hci_stack->le_minimum_ce_length,          // min ce length
4111                      hci_stack->le_maximum_ce_length           // max ce length
4112         );
4113         return true;
4114     }
4115 #endif
4116 
4117 #ifdef ENABLE_LE_PERIPHERAL
4118     // re-start advertising
4119     if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){
4120         // check if advertisements should be enabled given
4121         hci_stack->le_advertisements_active = true;
4122         hci_send_cmd(&hci_le_set_advertise_enable, 1);
4123         return true;
4124     }
4125 #endif
4126 
4127     return false;
4128 }
4129 #endif
4130 
4131 static bool hci_run_general_pending_commands(void){
4132     btstack_linked_item_t * it;
4133     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
4134         hci_connection_t * connection = (hci_connection_t *) it;
4135 
4136         switch(connection->state){
4137             case SEND_CREATE_CONNECTION:
4138                 switch(connection->address_type){
4139 #ifdef ENABLE_CLASSIC
4140                     case BD_ADDR_TYPE_ACL:
4141                         log_info("sending hci_create_connection");
4142                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
4143                         break;
4144 #endif
4145                     default:
4146 #ifdef ENABLE_BLE
4147 #ifdef ENABLE_LE_CENTRAL
4148                         log_info("sending hci_le_create_connection");
4149                         hci_send_cmd(&hci_le_create_connection,
4150                                      hci_stack->le_connection_scan_interval,    // conn scan interval
4151                                      hci_stack->le_connection_scan_window,      // conn scan windows
4152                                      0,         // don't use whitelist
4153                                      connection->address_type, // peer address type
4154                                      connection->address,      // peer bd addr
4155                                      hci_stack->le_own_addr_type, // our addr type:
4156                                      hci_stack->le_connection_interval_min,    // conn interval min
4157                                      hci_stack->le_connection_interval_max,    // conn interval max
4158                                      hci_stack->le_connection_latency,         // conn latency
4159                                      hci_stack->le_supervision_timeout,        // conn latency
4160                                      hci_stack->le_minimum_ce_length,          // min ce length
4161                                      hci_stack->le_maximum_ce_length          // max ce length
4162                         );
4163                         connection->state = SENT_CREATE_CONNECTION;
4164 #endif
4165 #endif
4166                         break;
4167                 }
4168                 return true;
4169 
4170 #ifdef ENABLE_CLASSIC
4171             case RECEIVED_CONNECTION_REQUEST:
4172                 connection->role  = HCI_ROLE_SLAVE;
4173                 if (connection->address_type == BD_ADDR_TYPE_ACL){
4174                     log_info("sending hci_accept_connection_request");
4175                     connection->state = ACCEPTED_CONNECTION_REQUEST;
4176                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
4177                 }
4178                 return true;
4179 #endif
4180 
4181 #ifdef ENABLE_BLE
4182 #ifdef ENABLE_LE_CENTRAL
4183             case SEND_CANCEL_CONNECTION:
4184                 connection->state = SENT_CANCEL_CONNECTION;
4185                 hci_send_cmd(&hci_le_create_connection_cancel);
4186                 return true;
4187 #endif
4188 #endif
4189             case SEND_DISCONNECT:
4190                 connection->state = SENT_DISCONNECT;
4191                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4192                 return true;
4193 
4194             default:
4195                 break;
4196         }
4197 
4198         // no further commands if connection is about to get shut down
4199         if (connection->state == SENT_DISCONNECT) continue;
4200 
4201         if (connection->authentication_flags & READ_RSSI){
4202             connectionClearAuthenticationFlags(connection, READ_RSSI);
4203             hci_send_cmd(&hci_read_rssi, connection->con_handle);
4204             return true;
4205         }
4206 
4207 #ifdef ENABLE_CLASSIC
4208 
4209         if (connection->authentication_flags & WRITE_SUPERVISION_TIMEOUT){
4210             connectionClearAuthenticationFlags(connection, WRITE_SUPERVISION_TIMEOUT);
4211             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
4212             return true;
4213         }
4214 
4215         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
4216             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
4217             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
4218 
4219             link_key_t link_key;
4220             link_key_type_t link_key_type;
4221             bool have_link_key = hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type);
4222 
4223             const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
4224             bool sc_enabled_remote = (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
4225             bool sc_downgrade = have_link_key && (gap_secure_connection_for_link_key_type(link_key_type) == 1) && !sc_enabled_remote;
4226             if (sc_downgrade){
4227                 log_info("Link key based on SC, but remote does not support SC -> disconnect");
4228                 connection->state = SENT_DISCONNECT;
4229                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4230                 return true;
4231             }
4232 
4233             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level);
4234             if (have_link_key && security_level_sufficient){
4235                 connection->link_key_type = link_key_type;
4236                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
4237             } else {
4238                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
4239             }
4240             return true;
4241         }
4242 
4243         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
4244             log_info("denying to pin request");
4245             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
4246             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
4247             return true;
4248         }
4249 
4250         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
4251             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
4252             // tweak authentication requirements
4253             uint8_t authreq = hci_stack->ssp_authentication_requirement;
4254             if (connection->bonding_flags & BONDING_DEDICATED){
4255                 authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4256             }
4257             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
4258                 authreq |= 1;
4259             }
4260             uint8_t have_oob_data = 0;
4261 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4262             if (connection->classic_oob_c_192 != NULL){
4263                     have_oob_data |= 1;
4264             }
4265             if (connection->classic_oob_c_256 != NULL){
4266                 have_oob_data |= 2;
4267             }
4268 #endif
4269             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
4270             return true;
4271         }
4272 
4273         if (connection->authentication_flags & SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
4274             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
4275             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
4276             return true;
4277         }
4278 
4279 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4280         if (connection->authentication_flags & SEND_REMOTE_OOB_DATA_REPLY){
4281             connectionClearAuthenticationFlags(connection, SEND_REMOTE_OOB_DATA_REPLY);
4282             const uint8_t zero[16] = { 0 };
4283             const uint8_t * r_192 = zero;
4284             const uint8_t * c_192 = zero;
4285             const uint8_t * r_256 = zero;
4286             const uint8_t * c_256 = zero;
4287             // verify P-256 OOB
4288             if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) {
4289                 c_256 = connection->classic_oob_c_256;
4290                 if (connection->classic_oob_r_256 != NULL) {
4291                     r_256 = connection->classic_oob_r_256;
4292                 }
4293             }
4294             // verify P-192 OOB
4295             if ((connection->classic_oob_c_192 != NULL)) {
4296                 c_192 = connection->classic_oob_c_192;
4297                 if (connection->classic_oob_r_192 != NULL) {
4298                     r_192 = connection->classic_oob_r_192;
4299                 }
4300             }
4301             // Reply
4302             if (c_256 != zero) {
4303                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
4304             } else if (c_192 != zero){
4305                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
4306             } else {
4307                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
4308             }
4309             return true;
4310         }
4311 #endif
4312 
4313         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
4314             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
4315             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
4316             return true;
4317         }
4318 
4319         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
4320             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
4321             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
4322             return true;
4323         }
4324 
4325         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
4326             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
4327             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
4328             return true;
4329         }
4330 
4331         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
4332             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
4333             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
4334             return true;
4335         }
4336 
4337         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
4338             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
4339             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
4340             return true;
4341         }
4342 
4343         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
4344             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
4345             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
4346             connection->state = SENT_DISCONNECT;
4347             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4348             return true;
4349         }
4350 
4351         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
4352             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
4353             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
4354             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
4355             return true;
4356         }
4357 
4358         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
4359             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
4360             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
4361             return true;
4362         }
4363         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
4364             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4365             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
4366             return true;
4367         }
4368 #endif
4369 
4370         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
4371             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
4372             if (connection->state != SENT_DISCONNECT){
4373                 connection->state = SENT_DISCONNECT;
4374                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4375                 return true;
4376             }
4377         }
4378 
4379 #ifdef ENABLE_CLASSIC
4380         uint16_t sniff_min_interval;
4381         switch (connection->sniff_min_interval){
4382             case 0:
4383                 break;
4384             case 0xffff:
4385                 connection->sniff_min_interval = 0;
4386                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
4387                 return true;
4388             default:
4389                 sniff_min_interval = connection->sniff_min_interval;
4390                 connection->sniff_min_interval = 0;
4391                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
4392                 return true;
4393         }
4394 
4395         if (connection->request_role != HCI_ROLE_INVALID){
4396             hci_role_t  role = connection->request_role;
4397             connection->request_role = HCI_ROLE_INVALID;
4398             hci_send_cmd(&hci_switch_role_command, connection->address, role);
4399             return true;
4400         }
4401 #endif
4402 
4403 #ifdef ENABLE_BLE
4404         switch (connection->le_con_parameter_update_state){
4405             // response to L2CAP CON PARAMETER UPDATE REQUEST
4406             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
4407                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4408                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
4409                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4410                              0x0000, 0xffff);
4411                 return true;
4412             case CON_PARAMETER_UPDATE_REPLY:
4413                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4414                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
4415                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4416                              0x0000, 0xffff);
4417                 return true;
4418             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
4419                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4420                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
4421                 return true;
4422             default:
4423                 break;
4424         }
4425         if (connection->le_phy_update_all_phys != 0xffu){
4426             uint8_t all_phys = connection->le_phy_update_all_phys;
4427             connection->le_phy_update_all_phys = 0xff;
4428             hci_send_cmd(&hci_le_set_phy, connection->con_handle, all_phys, connection->le_phy_update_tx_phys, connection->le_phy_update_rx_phys, connection->le_phy_update_phy_options);
4429             return true;
4430         }
4431 #endif
4432     }
4433     return false;
4434 }
4435 
4436 static void hci_run(void){
4437 
4438     bool done;
4439 
4440     // send continuation fragments first, as they block the prepared packet buffer
4441     done = hci_run_acl_fragments();
4442     if (done) return;
4443 
4444 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4445     // send host num completed packets next as they don't require num_cmd_packets > 0
4446     if (!hci_can_send_comand_packet_transport()) return;
4447     if (hci_stack->host_completed_packets){
4448         hci_host_num_completed_packets();
4449         return;
4450     }
4451 #endif
4452 
4453     if (!hci_can_send_command_packet_now()) return;
4454 
4455     // global/non-connection oriented commands
4456 
4457 
4458 #ifdef ENABLE_CLASSIC
4459     // general gap classic
4460     done = hci_run_general_gap_classic();
4461     if (done) return;
4462 #endif
4463 
4464 #ifdef ENABLE_BLE
4465     // general gap le
4466     done = hci_run_general_gap_le();
4467     if (done) return;
4468 #endif
4469 
4470     // send pending HCI commands
4471     done = hci_run_general_pending_commands();
4472     if (done) return;
4473 
4474     // stack state sub statemachines
4475     hci_connection_t * connection;
4476     switch (hci_stack->state){
4477         case HCI_STATE_INITIALIZING:
4478             hci_initializing_run();
4479             break;
4480 
4481         case HCI_STATE_HALTING:
4482 
4483             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4484             switch (hci_stack->substate){
4485                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
4486                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
4487 
4488 #ifdef ENABLE_BLE
4489 #ifdef ENABLE_LE_CENTRAL
4490                     // free whitelist entries
4491                     {
4492                         btstack_linked_list_iterator_t lit;
4493                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4494                         while (btstack_linked_list_iterator_has_next(&lit)){
4495                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4496                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
4497                             btstack_memory_whitelist_entry_free(entry);
4498                         }
4499                     }
4500 #endif
4501 #endif
4502                     // close all open connections
4503                     connection =  (hci_connection_t *) hci_stack->connections;
4504                     if (connection){
4505                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4506                         if (!hci_can_send_command_packet_now()) return;
4507 
4508                         // check state
4509                         if (connection->state == SENT_DISCONNECT) return;
4510                         connection->state = SENT_DISCONNECT;
4511 
4512                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4513 
4514                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
4515                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
4516 
4517                         // ... which would be ignored anyway as we shutdown (free) the connection now
4518                         hci_shutdown_connection(connection);
4519 
4520                         // finally, send the disconnect command
4521                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4522                         return;
4523                     }
4524 
4525                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
4526                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4527                         log_info("HCI_STATE_HALTING: wait 50 ms");
4528                         hci_stack->substate = HCI_HALTING_W4_TIMER;
4529                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
4530                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4531                         btstack_run_loop_add_timer(&hci_stack->timeout);
4532                         break;
4533                     }
4534 
4535                     /* fall through */
4536 
4537                 case HCI_HALTING_CLOSE:
4538                     log_info("HCI_STATE_HALTING, calling off");
4539 
4540                     // switch mode
4541                     hci_power_control_off();
4542 
4543                     log_info("HCI_STATE_HALTING, emitting state");
4544                     hci_emit_state();
4545                     log_info("HCI_STATE_HALTING, done");
4546                     break;
4547 
4548                 case HCI_HALTING_W4_TIMER:
4549                     // keep waiting
4550 
4551                     break;
4552                 default:
4553                     break;
4554             }
4555 
4556             break;
4557 
4558         case HCI_STATE_FALLING_ASLEEP:
4559             switch(hci_stack->substate) {
4560                 case HCI_FALLING_ASLEEP_DISCONNECT:
4561                     log_info("HCI_STATE_FALLING_ASLEEP");
4562                     // close all open connections
4563                     connection =  (hci_connection_t *) hci_stack->connections;
4564 
4565 #ifdef HAVE_PLATFORM_IPHONE_OS
4566                     // don't close connections, if H4 supports power management
4567                     if (btstack_control_iphone_power_management_enabled()){
4568                         connection = NULL;
4569                     }
4570 #endif
4571                     if (connection){
4572 
4573                         // send disconnect
4574                         if (!hci_can_send_command_packet_now()) return;
4575 
4576                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
4577                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4578 
4579                         // send disconnected event right away - causes higher layer connections to get closed, too.
4580                         hci_shutdown_connection(connection);
4581                         return;
4582                     }
4583 
4584                     if (hci_classic_supported()){
4585                         // disable page and inquiry scan
4586                         if (!hci_can_send_command_packet_now()) return;
4587 
4588                         log_info("HCI_STATE_HALTING, disabling inq scans");
4589                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
4590 
4591                         // continue in next sub state
4592                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
4593                         break;
4594                     }
4595 
4596                     /* fall through */
4597 
4598                 case HCI_FALLING_ASLEEP_COMPLETE:
4599                     log_info("HCI_STATE_HALTING, calling sleep");
4600 #ifdef HAVE_PLATFORM_IPHONE_OS
4601                     // don't actually go to sleep, if H4 supports power management
4602                     if (btstack_control_iphone_power_management_enabled()){
4603                         // SLEEP MODE reached
4604                         hci_stack->state = HCI_STATE_SLEEPING;
4605                         hci_emit_state();
4606                         break;
4607                     }
4608 #endif
4609                     // switch mode
4610                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
4611                     hci_emit_state();
4612                     break;
4613 
4614                 default:
4615                     break;
4616             }
4617             break;
4618 
4619         default:
4620             break;
4621     }
4622 }
4623 
4624 int hci_send_cmd_packet(uint8_t *packet, int size){
4625     // house-keeping
4626 
4627 #ifdef ENABLE_CLASSIC
4628     bd_addr_t addr;
4629     hci_connection_t * conn;
4630 #endif
4631 #ifdef ENABLE_LE_CENTRAL
4632     uint8_t initiator_filter_policy;
4633 #endif
4634 
4635     uint16_t opcode = little_endian_read_16(packet, 0);
4636     switch (opcode) {
4637         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
4638             hci_stack->loopback_mode = packet[3];
4639             break;
4640 
4641 #ifdef ENABLE_CLASSIC
4642         case HCI_OPCODE_HCI_CREATE_CONNECTION:
4643             reverse_bd_addr(&packet[3], addr);
4644             log_info("Create_connection to %s", bd_addr_to_str(addr));
4645 
4646             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4647             if (!conn) {
4648                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4649                 if (!conn) {
4650                     // notify client that alloc failed
4651                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4652                     return -1; // packet not sent to controller
4653                 }
4654                 conn->state = SEND_CREATE_CONNECTION;
4655                 conn->role  = HCI_ROLE_MASTER;
4656             }
4657             log_info("conn state %u", conn->state);
4658             switch (conn->state) {
4659                 // if connection active exists
4660                 case OPEN:
4661                     // and OPEN, emit connection complete command
4662                     hci_emit_connection_complete(addr, conn->con_handle, 0);
4663                     return -1; // packet not sent to controller
4664                 case RECEIVED_DISCONNECTION_COMPLETE:
4665                     // create connection triggered in disconnect complete event, let's do it now
4666                     break;
4667                 case SEND_CREATE_CONNECTION:
4668                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
4669                     break;
4670                 default:
4671                     // otherwise, just ignore as it is already in the open process
4672                     return -1; // packet not sent to controller
4673             }
4674             conn->state = SENT_CREATE_CONNECTION;
4675 
4676             // track outgoing connection
4677             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
4678             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
4679             break;
4680         case HCI_OPCODE_HCI_LINK_KEY_REQUEST_REPLY:
4681             hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
4682             break;
4683         case HCI_OPCODE_HCI_LINK_KEY_REQUEST_NEGATIVE_REPLY:
4684             hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
4685             break;
4686         case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY:
4687             if (hci_stack->link_key_db) {
4688                 reverse_bd_addr(&packet[3], addr);
4689                 hci_stack->link_key_db->delete_link_key(addr);
4690             }
4691             break;
4692         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
4693         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_REPLY:
4694             reverse_bd_addr(&packet[3], addr);
4695             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4696             if (conn) {
4697                 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
4698             }
4699             break;
4700         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
4701         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_REPLY:
4702         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
4703         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_REPLY:
4704             reverse_bd_addr(&packet[3], addr);
4705             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4706             if (conn) {
4707                 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
4708             }
4709             break;
4710 
4711 #ifdef ENABLE_SCO_OVER_HCI
4712         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
4713             // setup_synchronous_connection? Voice setting at offset 22
4714             // TODO: compare to current setting if sco connection already active
4715             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
4716             break;
4717         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
4718             // accept_synchronus_connection? Voice setting at offset 18
4719             // TODO: compare to current setting if sco connection already active
4720             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
4721             break;
4722 #endif
4723 #endif
4724 
4725 #ifdef ENABLE_BLE
4726         case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS:
4727             hci_stack->le_random_address_set = 1;
4728             reverse_bd_addr(&packet[3], hci_stack->le_random_address);
4729             break;
4730 #ifdef ENABLE_LE_PERIPHERAL
4731         case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE:
4732             hci_stack->le_advertisements_active = packet[3] != 0;
4733             break;
4734 #endif
4735 #ifdef ENABLE_LE_CENTRAL
4736         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
4737             // white list used?
4738             initiator_filter_policy = packet[7];
4739             switch (initiator_filter_policy) {
4740                 case 0:
4741                     // whitelist not used
4742                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
4743                     break;
4744                 case 1:
4745                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
4746                     break;
4747                 default:
4748                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
4749                     break;
4750             }
4751             // track outgoing connection
4752             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
4753             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
4754             break;
4755         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
4756             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
4757             break;
4758 #endif
4759 #endif
4760         default:
4761             break;
4762     }
4763 
4764     hci_stack->num_cmd_packets--;
4765 
4766     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4767     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
4768 }
4769 
4770 // disconnect because of security block
4771 void hci_disconnect_security_block(hci_con_handle_t con_handle){
4772     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4773     if (!connection) return;
4774     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
4775 }
4776 
4777 
4778 // Configure Secure Simple Pairing
4779 
4780 #ifdef ENABLE_CLASSIC
4781 
4782 // enable will enable SSP during init
4783 void gap_ssp_set_enable(int enable){
4784     hci_stack->ssp_enable = enable;
4785 }
4786 
4787 static int hci_local_ssp_activated(void){
4788     return gap_ssp_supported() && hci_stack->ssp_enable;
4789 }
4790 
4791 // if set, BTstack will respond to io capability request using authentication requirement
4792 void gap_ssp_set_io_capability(int io_capability){
4793     hci_stack->ssp_io_capability = io_capability;
4794 }
4795 void gap_ssp_set_authentication_requirement(int authentication_requirement){
4796     hci_stack->ssp_authentication_requirement = authentication_requirement;
4797 }
4798 
4799 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
4800 void gap_ssp_set_auto_accept(int auto_accept){
4801     hci_stack->ssp_auto_accept = auto_accept;
4802 }
4803 
4804 void gap_secure_connections_enable(bool enable){
4805     hci_stack->secure_connections_enable = enable;
4806 }
4807 
4808 #endif
4809 
4810 // va_list part of hci_send_cmd
4811 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
4812     if (!hci_can_send_command_packet_now()){
4813         log_error("hci_send_cmd called but cannot send packet now");
4814         return 0;
4815     }
4816 
4817     // for HCI INITIALIZATION
4818     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
4819     hci_stack->last_cmd_opcode = cmd->opcode;
4820 
4821     hci_reserve_packet_buffer();
4822     uint8_t * packet = hci_stack->hci_packet_buffer;
4823     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
4824     int err = hci_send_cmd_packet(packet, size);
4825 
4826     // release packet buffer on error or for synchronous transport implementations
4827     if ((err < 0) || hci_transport_synchronous()){
4828         hci_release_packet_buffer();
4829         hci_emit_transport_packet_sent();
4830     }
4831 
4832     return err;
4833 }
4834 
4835 /**
4836  * pre: numcmds >= 0 - it's allowed to send a command to the controller
4837  */
4838 int hci_send_cmd(const hci_cmd_t *cmd, ...){
4839     va_list argptr;
4840     va_start(argptr, cmd);
4841     int res = hci_send_cmd_va_arg(cmd, argptr);
4842     va_end(argptr);
4843     return res;
4844 }
4845 
4846 // Create various non-HCI events.
4847 // TODO: generalize, use table similar to hci_create_command
4848 
4849 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
4850     // dump packet
4851     if (dump) {
4852         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
4853     }
4854 
4855     // dispatch to all event handlers
4856     btstack_linked_list_iterator_t it;
4857     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
4858     while (btstack_linked_list_iterator_has_next(&it)){
4859         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
4860         entry->callback(HCI_EVENT_PACKET, 0, event, size);
4861     }
4862 }
4863 
4864 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
4865     if (!hci_stack->acl_packet_handler) return;
4866     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
4867 }
4868 
4869 #ifdef ENABLE_CLASSIC
4870 static void hci_notify_if_sco_can_send_now(void){
4871     // notify SCO sender if waiting
4872     if (!hci_stack->sco_waiting_for_can_send_now) return;
4873     if (hci_can_send_sco_packet_now()){
4874         hci_stack->sco_waiting_for_can_send_now = 0;
4875         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
4876         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
4877         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
4878     }
4879 }
4880 
4881 // parsing end emitting has been merged to reduce code size
4882 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
4883     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
4884 
4885     uint8_t * eir_data;
4886     ad_context_t context;
4887     const uint8_t * name;
4888     uint8_t         name_len;
4889 
4890     if (size < 3) return;
4891 
4892     int event_type = hci_event_packet_get_type(packet);
4893     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
4894     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
4895 
4896     switch (event_type){
4897         case HCI_EVENT_INQUIRY_RESULT:
4898         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4899             if (size != (3 + (num_responses * 14))) return;
4900             break;
4901         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4902             if (size != 257) return;
4903             if (num_responses != 1) return;
4904             break;
4905         default:
4906             return;
4907     }
4908 
4909     // event[1] is set at the end
4910     int i;
4911     for (i=0; i<num_responses;i++){
4912         memset(event, 0, sizeof(event));
4913         event[0] = GAP_EVENT_INQUIRY_RESULT;
4914         uint8_t event_size = 18;    // if name is not set by EIR
4915 
4916         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
4917         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
4918         (void)memcpy(&event[9],
4919                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
4920                      3); // class of device
4921         (void)memcpy(&event[12],
4922                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
4923                      2); // clock offset
4924 
4925         switch (event_type){
4926             case HCI_EVENT_INQUIRY_RESULT:
4927                 // 14,15,16,17 = 0, size 18
4928                 break;
4929             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4930                 event[14] = 1;
4931                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
4932                 // 16,17 = 0, size 18
4933                 break;
4934             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4935                 event[14] = 1;
4936                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
4937                 // EIR packets only contain a single inquiry response
4938                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
4939                 name = NULL;
4940                 // Iterate over EIR data
4941                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
4942                     uint8_t data_type    = ad_iterator_get_data_type(&context);
4943                     uint8_t data_size    = ad_iterator_get_data_len(&context);
4944                     const uint8_t * data = ad_iterator_get_data(&context);
4945                     // Prefer Complete Local Name over Shortend Local Name
4946                     switch (data_type){
4947                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
4948                             if (name) continue;
4949                             /* fall through */
4950                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
4951                             name = data;
4952                             name_len = data_size;
4953                             break;
4954                         default:
4955                             break;
4956                     }
4957                 }
4958                 if (name){
4959                     event[16] = 1;
4960                     // truncate name if needed
4961                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
4962                     event[17] = len;
4963                     (void)memcpy(&event[18], name, len);
4964                     event_size += len;
4965                 }
4966                 break;
4967             default:
4968                 return;
4969         }
4970         event[1] = event_size - 2;
4971         hci_emit_event(event, event_size, 1);
4972     }
4973 }
4974 #endif
4975 
4976 void hci_emit_state(void){
4977     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
4978     uint8_t event[3];
4979     event[0] = BTSTACK_EVENT_STATE;
4980     event[1] = sizeof(event) - 2u;
4981     event[2] = hci_stack->state;
4982     hci_emit_event(event, sizeof(event), 1);
4983 }
4984 
4985 #ifdef ENABLE_CLASSIC
4986 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
4987     uint8_t event[13];
4988     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
4989     event[1] = sizeof(event) - 2;
4990     event[2] = status;
4991     little_endian_store_16(event, 3, con_handle);
4992     reverse_bd_addr(address, &event[5]);
4993     event[11] = 1; // ACL connection
4994     event[12] = 0; // encryption disabled
4995     hci_emit_event(event, sizeof(event), 1);
4996 }
4997 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
4998     if (disable_l2cap_timeouts) return;
4999     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
5000     uint8_t event[4];
5001     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
5002     event[1] = sizeof(event) - 2;
5003     little_endian_store_16(event, 2, conn->con_handle);
5004     hci_emit_event(event, sizeof(event), 1);
5005 }
5006 #endif
5007 
5008 #ifdef ENABLE_BLE
5009 #ifdef ENABLE_LE_CENTRAL
5010 static void hci_emit_le_connection_complete(uint8_t address_type, const bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5011     uint8_t event[21];
5012     event[0] = HCI_EVENT_LE_META;
5013     event[1] = sizeof(event) - 2u;
5014     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
5015     event[3] = status;
5016     little_endian_store_16(event, 4, con_handle);
5017     event[6] = 0; // TODO: role
5018     event[7] = address_type;
5019     reverse_bd_addr(address, &event[8]);
5020     little_endian_store_16(event, 14, 0); // interval
5021     little_endian_store_16(event, 16, 0); // latency
5022     little_endian_store_16(event, 18, 0); // supervision timeout
5023     event[20] = 0; // master clock accuracy
5024     hci_emit_event(event, sizeof(event), 1);
5025 }
5026 #endif
5027 #endif
5028 
5029 static void hci_emit_transport_packet_sent(void){
5030     // notify upper stack that it might be possible to send again
5031     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
5032     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
5033 }
5034 
5035 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
5036     uint8_t event[6];
5037     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
5038     event[1] = sizeof(event) - 2u;
5039     event[2] = 0; // status = OK
5040     little_endian_store_16(event, 3, con_handle);
5041     event[5] = reason;
5042     hci_emit_event(event, sizeof(event), 1);
5043 }
5044 
5045 static void hci_emit_nr_connections_changed(void){
5046     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
5047     uint8_t event[3];
5048     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
5049     event[1] = sizeof(event) - 2u;
5050     event[2] = nr_hci_connections();
5051     hci_emit_event(event, sizeof(event), 1);
5052 }
5053 
5054 static void hci_emit_hci_open_failed(void){
5055     log_info("BTSTACK_EVENT_POWERON_FAILED");
5056     uint8_t event[2];
5057     event[0] = BTSTACK_EVENT_POWERON_FAILED;
5058     event[1] = sizeof(event) - 2u;
5059     hci_emit_event(event, sizeof(event), 1);
5060 }
5061 
5062 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
5063     log_info("hci_emit_dedicated_bonding_result %u ", status);
5064     uint8_t event[9];
5065     int pos = 0;
5066     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
5067     event[pos++] = sizeof(event) - 2u;
5068     event[pos++] = status;
5069     reverse_bd_addr(address, &event[pos]);
5070     hci_emit_event(event, sizeof(event), 1);
5071 }
5072 
5073 
5074 #ifdef ENABLE_CLASSIC
5075 
5076 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
5077     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
5078     uint8_t event[5];
5079     int pos = 0;
5080     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
5081     event[pos++] = sizeof(event) - 2;
5082     little_endian_store_16(event, 2, con_handle);
5083     pos += 2;
5084     event[pos++] = level;
5085     hci_emit_event(event, sizeof(event), 1);
5086 }
5087 
5088 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
5089     if (!connection) return LEVEL_0;
5090     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
5091     if ((connection->authentication_flags & CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
5092     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
5093     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
5094     // LEVEL 4 always requires 128 bit encrytion key size
5095     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
5096         security_level = LEVEL_3;
5097     }
5098     return security_level;
5099 }
5100 
5101 static void hci_emit_discoverable_enabled(uint8_t enabled){
5102     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
5103     uint8_t event[3];
5104     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
5105     event[1] = sizeof(event) - 2;
5106     event[2] = enabled;
5107     hci_emit_event(event, sizeof(event), 1);
5108 }
5109 
5110 // query if remote side supports eSCO
5111 int hci_remote_esco_supported(hci_con_handle_t con_handle){
5112     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5113     if (!connection) return 0;
5114     return (connection->remote_supported_features[0] & 1) != 0;
5115 }
5116 
5117 static bool hci_ssp_supported(hci_connection_t * connection){
5118     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
5119     return (connection->bonding_flags & mask) == mask;
5120 }
5121 
5122 // query if remote side supports SSP
5123 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
5124     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5125     if (!connection) return 0;
5126     return hci_ssp_supported(connection) ? 1 : 0;
5127 }
5128 
5129 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
5130     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
5131 }
5132 
5133 // GAP API
5134 /**
5135  * @bbrief enable/disable bonding. default is enabled
5136  * @praram enabled
5137  */
5138 void gap_set_bondable_mode(int enable){
5139     hci_stack->bondable = enable ? 1 : 0;
5140 }
5141 /**
5142  * @brief Get bondable mode.
5143  * @return 1 if bondable
5144  */
5145 int gap_get_bondable_mode(void){
5146     return hci_stack->bondable;
5147 }
5148 
5149 /**
5150  * @brief map link keys to security levels
5151  */
5152 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
5153     switch (link_key_type){
5154         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5155             return LEVEL_4;
5156         case COMBINATION_KEY:
5157         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5158             return LEVEL_3;
5159         default:
5160             return LEVEL_2;
5161     }
5162 }
5163 
5164 /**
5165  * @brief map link keys to secure connection yes/no
5166  */
5167 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
5168     switch (link_key_type){
5169         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5170         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5171             return 1;
5172         default:
5173             return 0;
5174     }
5175 }
5176 
5177 /**
5178  * @brief map link keys to authenticated
5179  */
5180 int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
5181     switch (link_key_type){
5182         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5183         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5184             return 1;
5185         default:
5186             return 0;
5187     }
5188 }
5189 
5190 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
5191     log_info("gap_mitm_protection_required_for_security_level %u", level);
5192     return level > LEVEL_2;
5193 }
5194 
5195 /**
5196  * @brief get current security level
5197  */
5198 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
5199     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5200     if (!connection) return LEVEL_0;
5201     return gap_security_level_for_connection(connection);
5202 }
5203 
5204 /**
5205  * @brief request connection to device to
5206  * @result GAP_AUTHENTICATION_RESULT
5207  */
5208 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
5209     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5210     if (!connection){
5211         hci_emit_security_level(con_handle, LEVEL_0);
5212         return;
5213     }
5214 
5215     btstack_assert(hci_is_le_connection(connection) == false);
5216 
5217     gap_security_level_t current_level = gap_security_level(con_handle);
5218     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
5219         requested_level, connection->requested_security_level, current_level);
5220 
5221     // assumption: earlier requested security higher than current level => security request is active
5222     if (current_level < connection->requested_security_level){
5223         if (connection->requested_security_level < requested_level){
5224             // increase requested level as new level is higher
5225 
5226             // TODO: handle re-authentication when done
5227 
5228             connection->requested_security_level = requested_level;
5229         }
5230         return;
5231     }
5232 
5233     // no request active, notify if security sufficient
5234     if (requested_level <= current_level){
5235         hci_emit_security_level(con_handle, current_level);
5236         return;
5237     }
5238 
5239     // store request
5240     connection->requested_security_level = requested_level;
5241 
5242     // start to authenticate connection if authentication not already active
5243     if ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
5244     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
5245     hci_run();
5246 }
5247 
5248 /**
5249  * @brief start dedicated bonding with device. disconnect after bonding
5250  * @param device
5251  * @param request MITM protection
5252  * @result GAP_DEDICATED_BONDING_COMPLETE
5253  */
5254 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
5255 
5256     // create connection state machine
5257     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
5258 
5259     if (!connection){
5260         return BTSTACK_MEMORY_ALLOC_FAILED;
5261     }
5262 
5263     // delete linkn key
5264     gap_drop_link_key_for_bd_addr(device);
5265 
5266     // configure LEVEL_2/3, dedicated bonding
5267     connection->state = SEND_CREATE_CONNECTION;
5268     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
5269     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
5270     connection->bonding_flags = BONDING_DEDICATED;
5271 
5272     // wait for GAP Security Result and send GAP Dedicated Bonding complete
5273 
5274     // handle: connnection failure (connection complete != ok)
5275     // handle: authentication failure
5276     // handle: disconnect on done
5277 
5278     hci_run();
5279 
5280     return 0;
5281 }
5282 #endif
5283 
5284 void gap_set_local_name(const char * local_name){
5285     hci_stack->local_name = local_name;
5286 }
5287 
5288 
5289 #ifdef ENABLE_BLE
5290 
5291 #ifdef ENABLE_LE_CENTRAL
5292 void gap_start_scan(void){
5293     hci_stack->le_scanning_enabled = true;
5294     hci_run();
5295 }
5296 
5297 void gap_stop_scan(void){
5298     hci_stack->le_scanning_enabled = false;
5299     hci_run();
5300 }
5301 
5302 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
5303     hci_stack->le_scan_type          = scan_type;
5304     hci_stack->le_scan_filter_policy = scanning_filter_policy;
5305     hci_stack->le_scan_interval      = scan_interval;
5306     hci_stack->le_scan_window        = scan_window;
5307     hci_stack->le_scanning_param_update = true;
5308     hci_run();
5309 }
5310 
5311 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
5312     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
5313 }
5314 
5315 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
5316     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
5317     if (!conn){
5318         // disallow if le connection is already outgoing
5319         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5320             log_error("le connection already active");
5321             return ERROR_CODE_COMMAND_DISALLOWED;
5322         }
5323 
5324         log_info("gap_connect: no connection exists yet, creating context");
5325         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
5326         if (!conn){
5327             // notify client that alloc failed
5328             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5329             log_info("gap_connect: failed to alloc hci_connection_t");
5330             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
5331         }
5332 
5333         // set le connecting state
5334         if (hci_is_le_connection_type(addr_type)){
5335             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
5336         }
5337 
5338         conn->state = SEND_CREATE_CONNECTION;
5339         log_info("gap_connect: send create connection next");
5340         hci_run();
5341         return ERROR_CODE_SUCCESS;
5342     }
5343 
5344     if (!hci_is_le_connection(conn) ||
5345         (conn->state == SEND_CREATE_CONNECTION) ||
5346         (conn->state == SENT_CREATE_CONNECTION)) {
5347         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
5348         log_error("gap_connect: classic connection or connect is already being created");
5349         return GATT_CLIENT_IN_WRONG_STATE;
5350     }
5351 
5352     // check if connection was just disconnected
5353     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5354         log_info("gap_connect: send create connection (again)");
5355         conn->state = SEND_CREATE_CONNECTION;
5356         hci_run();
5357         return ERROR_CODE_SUCCESS;
5358     }
5359 
5360     log_info("gap_connect: context exists with state %u", conn->state);
5361     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
5362     hci_run();
5363     return ERROR_CODE_SUCCESS;
5364 }
5365 
5366 // @assumption: only a single outgoing LE Connection exists
5367 static hci_connection_t * gap_get_outgoing_connection(void){
5368     btstack_linked_item_t *it;
5369     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5370         hci_connection_t * conn = (hci_connection_t *) it;
5371         if (!hci_is_le_connection(conn)) continue;
5372         switch (conn->state){
5373             case SEND_CREATE_CONNECTION:
5374             case SENT_CREATE_CONNECTION:
5375             case SENT_CANCEL_CONNECTION:
5376                 return conn;
5377             default:
5378                 break;
5379         };
5380     }
5381     return NULL;
5382 }
5383 
5384 uint8_t gap_connect_cancel(void){
5385     hci_connection_t * conn = gap_get_outgoing_connection();
5386     if (!conn) return 0;
5387     switch (conn->state){
5388         case SEND_CREATE_CONNECTION:
5389             // skip sending create connection and emit event instead
5390             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
5391             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
5392             btstack_memory_hci_connection_free( conn );
5393             break;
5394         case SENT_CREATE_CONNECTION:
5395             // request to send cancel connection
5396             conn->state = SEND_CANCEL_CONNECTION;
5397             hci_run();
5398             break;
5399         default:
5400             break;
5401     }
5402     return 0;
5403 }
5404 #endif
5405 
5406 #ifdef ENABLE_LE_CENTRAL
5407 /**
5408  * @brief Set connection parameters for outgoing connections
5409  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
5410  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
5411  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
5412  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
5413  * @param conn_latency, default: 4
5414  * @param supervision_timeout (unit: 10ms), default: 720 ms
5415  * @param min_ce_length (unit: 0.625ms), default: 10 ms
5416  * @param max_ce_length (unit: 0.625ms), default: 30 ms
5417  */
5418 
5419 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
5420     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
5421     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
5422     hci_stack->le_connection_scan_interval = conn_scan_interval;
5423     hci_stack->le_connection_scan_window = conn_scan_window;
5424     hci_stack->le_connection_interval_min = conn_interval_min;
5425     hci_stack->le_connection_interval_max = conn_interval_max;
5426     hci_stack->le_connection_latency = conn_latency;
5427     hci_stack->le_supervision_timeout = supervision_timeout;
5428     hci_stack->le_minimum_ce_length = min_ce_length;
5429     hci_stack->le_maximum_ce_length = max_ce_length;
5430 }
5431 #endif
5432 
5433 /**
5434  * @brief Updates the connection parameters for a given LE connection
5435  * @param handle
5436  * @param conn_interval_min (unit: 1.25ms)
5437  * @param conn_interval_max (unit: 1.25ms)
5438  * @param conn_latency
5439  * @param supervision_timeout (unit: 10ms)
5440  * @returns 0 if ok
5441  */
5442 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5443     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5444     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5445     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5446     connection->le_conn_interval_min = conn_interval_min;
5447     connection->le_conn_interval_max = conn_interval_max;
5448     connection->le_conn_latency = conn_latency;
5449     connection->le_supervision_timeout = supervision_timeout;
5450     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
5451     hci_run();
5452     return 0;
5453 }
5454 
5455 /**
5456  * @brief Request an update of the connection parameter for a given LE connection
5457  * @param handle
5458  * @param conn_interval_min (unit: 1.25ms)
5459  * @param conn_interval_max (unit: 1.25ms)
5460  * @param conn_latency
5461  * @param supervision_timeout (unit: 10ms)
5462  * @returns 0 if ok
5463  */
5464 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5465     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5466     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5467     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5468     connection->le_conn_interval_min = conn_interval_min;
5469     connection->le_conn_interval_max = conn_interval_max;
5470     connection->le_conn_latency = conn_latency;
5471     connection->le_supervision_timeout = supervision_timeout;
5472     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
5473     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
5474     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
5475     return 0;
5476 }
5477 
5478 #ifdef ENABLE_LE_PERIPHERAL
5479 
5480 /**
5481  * @brief Set Advertisement Data
5482  * @param advertising_data_length
5483  * @param advertising_data (max 31 octets)
5484  * @note data is not copied, pointer has to stay valid
5485  */
5486 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
5487     hci_stack->le_advertisements_data_len = advertising_data_length;
5488     hci_stack->le_advertisements_data = advertising_data;
5489     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5490     hci_run();
5491 }
5492 
5493 /**
5494  * @brief Set Scan Response Data
5495  * @param advertising_data_length
5496  * @param advertising_data (max 31 octets)
5497  * @note data is not copied, pointer has to stay valid
5498  */
5499 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
5500     hci_stack->le_scan_response_data_len = scan_response_data_length;
5501     hci_stack->le_scan_response_data = scan_response_data;
5502     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5503     hci_run();
5504 }
5505 
5506 /**
5507  * @brief Set Advertisement Parameters
5508  * @param adv_int_min
5509  * @param adv_int_max
5510  * @param adv_type
5511  * @param direct_address_type
5512  * @param direct_address
5513  * @param channel_map
5514  * @param filter_policy
5515  *
5516  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
5517  */
5518  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
5519     uint8_t direct_address_typ, bd_addr_t direct_address,
5520     uint8_t channel_map, uint8_t filter_policy) {
5521 
5522     hci_stack->le_advertisements_interval_min = adv_int_min;
5523     hci_stack->le_advertisements_interval_max = adv_int_max;
5524     hci_stack->le_advertisements_type = adv_type;
5525     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
5526     hci_stack->le_advertisements_channel_map = channel_map;
5527     hci_stack->le_advertisements_filter_policy = filter_policy;
5528     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
5529                  6);
5530 
5531     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5532     hci_run();
5533  }
5534 
5535 /**
5536  * @brief Enable/Disable Advertisements
5537  * @param enabled
5538  */
5539 void gap_advertisements_enable(int enabled){
5540     hci_stack->le_advertisements_enabled = enabled != 0;
5541     hci_update_advertisements_enabled_for_current_roles();
5542     hci_run();
5543 }
5544 
5545 #endif
5546 
5547 void hci_le_set_own_address_type(uint8_t own_address_type){
5548     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
5549     if (own_address_type == hci_stack->le_own_addr_type) return;
5550     hci_stack->le_own_addr_type = own_address_type;
5551 
5552 #ifdef ENABLE_LE_PERIPHERAL
5553     // update advertisement parameters, too
5554     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5555     hci_run();
5556 #endif
5557 #ifdef ENABLE_LE_CENTRAL
5558     // note: we don't update scan parameters or modify ongoing connection attempts
5559 #endif
5560 }
5561 
5562 #endif
5563 
5564 uint8_t gap_disconnect(hci_con_handle_t handle){
5565     hci_connection_t * conn = hci_connection_for_handle(handle);
5566     if (!conn){
5567         hci_emit_disconnection_complete(handle, 0);
5568         return 0;
5569     }
5570     // ignore if already disconnected
5571     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5572         return 0;
5573     }
5574     conn->state = SEND_DISCONNECT;
5575     hci_run();
5576     return 0;
5577 }
5578 
5579 int gap_read_rssi(hci_con_handle_t con_handle){
5580     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5581     if (hci_connection == NULL) return 0;
5582     connectionSetAuthenticationFlags(hci_connection, READ_RSSI);
5583     hci_run();
5584     return 1;
5585 }
5586 
5587 /**
5588  * @brief Get connection type
5589  * @param con_handle
5590  * @result connection_type
5591  */
5592 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
5593     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5594     if (!conn) return GAP_CONNECTION_INVALID;
5595     switch (conn->address_type){
5596         case BD_ADDR_TYPE_LE_PUBLIC:
5597         case BD_ADDR_TYPE_LE_RANDOM:
5598             return GAP_CONNECTION_LE;
5599         case BD_ADDR_TYPE_SCO:
5600             return GAP_CONNECTION_SCO;
5601         case BD_ADDR_TYPE_ACL:
5602             return GAP_CONNECTION_ACL;
5603         default:
5604             return GAP_CONNECTION_INVALID;
5605     }
5606 }
5607 
5608 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
5609     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5610     if (!conn) return HCI_ROLE_INVALID;
5611     return (hci_role_t) conn->role;
5612 }
5613 
5614 
5615 #ifdef ENABLE_CLASSIC
5616 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
5617     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5618     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5619     conn->request_role = role;
5620     hci_run();
5621     return ERROR_CODE_SUCCESS;
5622 }
5623 #endif
5624 
5625 #ifdef ENABLE_BLE
5626 
5627 uint8_t gap_le_set_phy(hci_con_handle_t connection_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){
5628     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5629     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5630 
5631     conn->le_phy_update_all_phys    = all_phys;
5632     conn->le_phy_update_tx_phys     = tx_phys;
5633     conn->le_phy_update_rx_phys     = rx_phys;
5634     conn->le_phy_update_phy_options = phy_options;
5635 
5636     hci_run();
5637 
5638     return 0;
5639 }
5640 
5641 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
5642     // check if already in list
5643     btstack_linked_list_iterator_t it;
5644     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5645     while (btstack_linked_list_iterator_has_next(&it)) {
5646         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
5647         if (entry->address_type != address_type) {
5648             continue;
5649         }
5650         if (memcmp(entry->address, address, 6) != 0) {
5651             continue;
5652         }
5653 		// disallow if already scheduled to add
5654 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
5655 			return ERROR_CODE_COMMAND_DISALLOWED;
5656 		}
5657 		// still on controller, but scheduled to remove -> re-add
5658 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
5659 		return ERROR_CODE_SUCCESS;
5660     }
5661     // alloc and add to list
5662     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
5663     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
5664     entry->address_type = address_type;
5665     (void)memcpy(entry->address, address, 6);
5666     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5667     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
5668     return ERROR_CODE_SUCCESS;
5669 }
5670 
5671 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
5672     btstack_linked_list_iterator_t it;
5673     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5674     while (btstack_linked_list_iterator_has_next(&it)){
5675         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5676         if (entry->address_type != address_type) {
5677             continue;
5678         }
5679         if (memcmp(entry->address, address, 6) != 0) {
5680             continue;
5681         }
5682         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
5683             // remove from controller if already present
5684             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5685         }  else {
5686             // directly remove entry from whitelist
5687             btstack_linked_list_iterator_remove(&it);
5688             btstack_memory_whitelist_entry_free(entry);
5689         }
5690         return ERROR_CODE_SUCCESS;
5691     }
5692     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5693 }
5694 
5695 static void hci_whitelist_clear(void){
5696     btstack_linked_list_iterator_t it;
5697     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5698     while (btstack_linked_list_iterator_has_next(&it)){
5699         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5700         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
5701             // remove from controller if already present
5702             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5703             continue;
5704         }
5705         // directly remove entry from whitelist
5706         btstack_linked_list_iterator_remove(&it);
5707         btstack_memory_whitelist_entry_free(entry);
5708     }
5709 }
5710 
5711 /**
5712  * @brief Clear Whitelist
5713  * @returns 0 if ok
5714  */
5715 uint8_t gap_whitelist_clear(void){
5716     hci_whitelist_clear();
5717     hci_run();
5718     return ERROR_CODE_SUCCESS;
5719 }
5720 
5721 /**
5722  * @brief Add Device to Whitelist
5723  * @param address_typ
5724  * @param address
5725  * @returns 0 if ok
5726  */
5727 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
5728     uint8_t status = hci_whitelist_add(address_type, address);
5729     if (status){
5730         return status;
5731     }
5732     hci_run();
5733     return ERROR_CODE_SUCCESS;
5734 }
5735 
5736 /**
5737  * @brief Remove Device from Whitelist
5738  * @param address_typ
5739  * @param address
5740  * @returns 0 if ok
5741  */
5742 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
5743     uint8_t status = hci_whitelist_remove(address_type, address);
5744     if (status){
5745         return status;
5746     }
5747     hci_run();
5748     return ERROR_CODE_SUCCESS;
5749 }
5750 
5751 #ifdef ENABLE_LE_CENTRAL
5752 /**
5753  *  @brief Connect with Whitelist
5754  *  @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
5755  *  @returns - if ok
5756  */
5757 uint8_t gap_connect_with_whitelist(void){
5758     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5759         return ERROR_CODE_COMMAND_DISALLOWED;
5760     }
5761     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
5762     hci_run();
5763     return ERROR_CODE_SUCCESS;
5764 }
5765 
5766 /**
5767  * @brief Auto Connection Establishment - Start Connecting to device
5768  * @param address_typ
5769  * @param address
5770  * @returns 0 if ok
5771  */
5772 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
5773     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
5774         return ERROR_CODE_COMMAND_DISALLOWED;
5775     }
5776 
5777     uint8_t status = hci_whitelist_add(address_type, address);
5778     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
5779         return status;
5780     }
5781 
5782     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
5783 
5784     hci_run();
5785     return ERROR_CODE_SUCCESS;
5786 }
5787 
5788 /**
5789  * @brief Auto Connection Establishment - Stop Connecting to device
5790  * @param address_typ
5791  * @param address
5792  * @returns 0 if ok
5793  */
5794 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
5795     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
5796         return ERROR_CODE_COMMAND_DISALLOWED;
5797     }
5798 
5799     hci_whitelist_remove(address_type, address);
5800     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
5801         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
5802     }
5803     hci_run();
5804     return 0;
5805 }
5806 
5807 /**
5808  * @brief Auto Connection Establishment - Stop everything
5809  * @note  Convenience function to stop all active auto connection attempts
5810  */
5811 uint8_t gap_auto_connection_stop_all(void){
5812     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
5813         return ERROR_CODE_COMMAND_DISALLOWED;
5814     }
5815     hci_whitelist_clear();
5816     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
5817     hci_run();
5818     return ERROR_CODE_SUCCESS;
5819 }
5820 
5821 uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){
5822     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5823     if (!conn) return 0;
5824     return conn->le_connection_interval;
5825 }
5826 #endif
5827 #endif
5828 
5829 #ifdef ENABLE_CLASSIC
5830 /**
5831  * @brief Set Extended Inquiry Response data
5832  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
5833  * @note has to be done before stack starts up
5834  */
5835 void gap_set_extended_inquiry_response(const uint8_t * data){
5836     hci_stack->eir_data = data;
5837 }
5838 
5839 /**
5840  * @brief Start GAP Classic Inquiry
5841  * @param duration in 1.28s units
5842  * @return 0 if ok
5843  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
5844  */
5845 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
5846     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
5847     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5848     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
5849         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
5850     }
5851     hci_stack->inquiry_state = duration_in_1280ms_units;
5852     hci_run();
5853     return 0;
5854 }
5855 
5856 /**
5857  * @brief Stop GAP Classic Inquiry
5858  * @returns 0 if ok
5859  */
5860 int gap_inquiry_stop(void){
5861     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
5862         // emit inquiry complete event, before it even started
5863         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
5864         hci_emit_event(event, sizeof(event), 1);
5865         return 0;
5866     }
5867     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
5868     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
5869     hci_run();
5870     return 0;
5871 }
5872 
5873 
5874 /**
5875  * @brief Remote Name Request
5876  * @param addr
5877  * @param page_scan_repetition_mode
5878  * @param clock_offset only used when bit 15 is set
5879  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
5880  */
5881 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
5882     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5883     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
5884     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
5885     hci_stack->remote_name_clock_offset = clock_offset;
5886     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
5887     hci_run();
5888     return 0;
5889 }
5890 
5891 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
5892     hci_stack->gap_pairing_state = state;
5893     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
5894     hci_run();
5895     return 0;
5896 }
5897 
5898 /**
5899  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
5900  * @param addr
5901  * @param pin_data
5902  * @param pin_len
5903  * @return 0 if ok
5904  */
5905 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
5906     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5907     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
5908     hci_stack->gap_pairing_pin_len = pin_len;
5909     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
5910 }
5911 
5912 /**
5913  * @brief Legacy Pairing Pin Code Response
5914  * @param addr
5915  * @param pin
5916  * @return 0 if ok
5917  */
5918 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
5919     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
5920 }
5921 
5922 /**
5923  * @brief Abort Legacy Pairing
5924  * @param addr
5925  * @param pin
5926  * @return 0 if ok
5927  */
5928 int gap_pin_code_negative(bd_addr_t addr){
5929     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5930     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
5931 }
5932 
5933 /**
5934  * @brief SSP Passkey Response
5935  * @param addr
5936  * @param passkey
5937  * @return 0 if ok
5938  */
5939 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
5940     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5941     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
5942     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
5943 }
5944 
5945 /**
5946  * @brief Abort SSP Passkey Entry/Pairing
5947  * @param addr
5948  * @param pin
5949  * @return 0 if ok
5950  */
5951 int gap_ssp_passkey_negative(const bd_addr_t addr){
5952     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5953     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
5954 }
5955 
5956 /**
5957  * @brief Accept SSP Numeric Comparison
5958  * @param addr
5959  * @param passkey
5960  * @return 0 if ok
5961  */
5962 int gap_ssp_confirmation_response(const bd_addr_t addr){
5963     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5964     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
5965 }
5966 
5967 /**
5968  * @brief Abort SSP Numeric Comparison/Pairing
5969  * @param addr
5970  * @param pin
5971  * @return 0 if ok
5972  */
5973 int gap_ssp_confirmation_negative(const bd_addr_t addr){
5974     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5975     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
5976 }
5977 
5978 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
5979 
5980 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
5981     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5982     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5983     connectionSetAuthenticationFlags(conn, flag);
5984     hci_run();
5985     return ERROR_CODE_SUCCESS;
5986 }
5987 
5988 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
5989     return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_REPLY);
5990 }
5991 
5992 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
5993     return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
5994 }
5995 #endif
5996 
5997 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5998 /**
5999  * @brief Report Remote OOB Data
6000  * @param bd_addr
6001  * @param c_192 Simple Pairing Hash C derived from P-192 public key
6002  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
6003  * @param c_256 Simple Pairing Hash C derived from P-256 public key
6004  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
6005  */
6006 uint8_t gap_ssp_remote_oob_data(const bd_addr_t addr, const uint8_t * c_192, const uint8_t * r_192, const uint8_t * c_256, const uint8_t * r_256){
6007     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6008     if (connection == NULL) {
6009         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6010     }
6011     connection->classic_oob_c_192 = c_192;
6012     connection->classic_oob_r_192 = r_192;
6013     connection->classic_oob_c_256 = c_256;
6014     connection->classic_oob_r_256 = r_256;
6015     return ERROR_CODE_SUCCESS;
6016 }
6017 /**
6018  * @brief Generate new OOB data
6019  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
6020  */
6021 void gap_ssp_generate_oob_data(void){
6022     hci_stack->classic_read_local_oob_data = true;
6023     hci_run();
6024 }
6025 
6026 #endif
6027 
6028 /**
6029  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
6030  * @param inquiry_mode see bluetooth_defines.h
6031  */
6032 void hci_set_inquiry_mode(inquiry_mode_t mode){
6033     hci_stack->inquiry_mode = mode;
6034 }
6035 
6036 /**
6037  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
6038  */
6039 void hci_set_sco_voice_setting(uint16_t voice_setting){
6040     hci_stack->sco_voice_setting = voice_setting;
6041 }
6042 
6043 /**
6044  * @brief Get SCO Voice Setting
6045  * @return current voice setting
6046  */
6047 uint16_t hci_get_sco_voice_setting(void){
6048     return hci_stack->sco_voice_setting;
6049 }
6050 
6051 static int hci_have_usb_transport(void){
6052     if (!hci_stack->hci_transport) return 0;
6053     const char * transport_name = hci_stack->hci_transport->name;
6054     if (!transport_name) return 0;
6055     return (transport_name[0] == 'H') && (transport_name[1] == '2');
6056 }
6057 
6058 /** @brief Get SCO packet length for current SCO Voice setting
6059  *  @note  Using SCO packets of the exact length is required for USB transfer
6060  *  @return Length of SCO packets in bytes (not audio frames)
6061  */
6062 int hci_get_sco_packet_length(void){
6063     int sco_packet_length = 0;
6064 
6065 #ifdef ENABLE_SCO_OVER_HCI
6066 
6067     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6068     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6069 
6070     if (hci_have_usb_transport()){
6071         // see Core Spec for H2 USB Transfer.
6072         // 3 byte SCO header + 24 bytes per connection
6073         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
6074         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
6075     } else {
6076         // 3 byte SCO header + SCO packet size over the air (60 bytes)
6077         sco_packet_length = 3 + 60 * multiplier;
6078         // assert that it still fits inside an SCO buffer
6079         if (sco_packet_length > hci_stack->sco_data_packet_length){
6080             sco_packet_length = 3 + 60;
6081         }
6082     }
6083 #endif
6084     return sco_packet_length;
6085 }
6086 
6087 /**
6088 * @brief Sets the master/slave policy
6089 * @param policy (0: attempt to become master, 1: let connecting device decide)
6090 */
6091 void hci_set_master_slave_policy(uint8_t policy){
6092     hci_stack->master_slave_policy = policy;
6093 }
6094 
6095 #endif
6096 
6097 HCI_STATE hci_get_state(void){
6098     return hci_stack->state;
6099 }
6100 
6101 #ifdef ENABLE_CLASSIC
6102 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
6103     hci_stack->gap_classic_accept_callback = accept_callback;
6104 }
6105 #endif
6106 
6107 /**
6108  * @brief Set callback for Bluetooth Hardware Error
6109  */
6110 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
6111     hci_stack->hardware_error_callback = fn;
6112 }
6113 
6114 void hci_disconnect_all(void){
6115     btstack_linked_list_iterator_t it;
6116     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6117     while (btstack_linked_list_iterator_has_next(&it)){
6118         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6119         if (con->state == SENT_DISCONNECT) continue;
6120         con->state = SEND_DISCONNECT;
6121     }
6122     hci_run();
6123 }
6124 
6125 uint16_t hci_get_manufacturer(void){
6126     return hci_stack->manufacturer;
6127 }
6128 
6129 #ifdef ENABLE_BLE
6130 
6131 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
6132     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
6133     if (!hci_con) return NULL;
6134     return &hci_con->sm_connection;
6135 }
6136 
6137 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
6138 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
6139 
6140 int gap_encryption_key_size(hci_con_handle_t con_handle){
6141     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6142     if (hci_connection == NULL) return 0;
6143     if (hci_is_le_connection(hci_connection)){
6144         sm_connection_t * sm_conn = &hci_connection->sm_connection;
6145         if (sm_conn->sm_connection_encrypted) {
6146             return sm_conn->sm_actual_encryption_key_size;
6147         }
6148     }
6149 #ifdef ENABLE_CLASSIC
6150     else {
6151         if ((hci_connection->authentication_flags & CONNECTION_ENCRYPTED)){
6152             return hci_connection->encryption_key_size;
6153         }
6154     }
6155 #endif
6156     return 0;
6157 }
6158 
6159 int gap_authenticated(hci_con_handle_t con_handle){
6160     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6161     if (hci_connection == NULL) return 0;
6162 
6163     switch (hci_connection->address_type){
6164         case BD_ADDR_TYPE_LE_PUBLIC:
6165         case BD_ADDR_TYPE_LE_RANDOM:
6166             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6167             return hci_connection->sm_connection.sm_connection_authenticated;
6168 #ifdef ENABLE_CLASSIC
6169         case BD_ADDR_TYPE_SCO:
6170         case BD_ADDR_TYPE_ACL:
6171             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
6172 #endif
6173         default:
6174             return 0;
6175     }
6176 }
6177 
6178 int gap_secure_connection(hci_con_handle_t con_handle){
6179     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6180     if (hci_connection == NULL) return 0;
6181 
6182     switch (hci_connection->address_type){
6183         case BD_ADDR_TYPE_LE_PUBLIC:
6184         case BD_ADDR_TYPE_LE_RANDOM:
6185             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6186             return hci_connection->sm_connection.sm_connection_sc;
6187 #ifdef ENABLE_CLASSIC
6188         case BD_ADDR_TYPE_SCO:
6189         case BD_ADDR_TYPE_ACL:
6190             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
6191 #endif
6192         default:
6193             return 0;
6194     }
6195 }
6196 
6197 bool gap_bonded(hci_con_handle_t con_handle){
6198 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6199 	if (hci_connection == NULL) return 0;
6200 
6201 #ifdef ENABLE_CLASSIC
6202 	link_key_t link_key;
6203 	link_key_type_t link_key_type;
6204 #endif
6205 	switch (hci_connection->address_type){
6206 		case BD_ADDR_TYPE_LE_PUBLIC:
6207 		case BD_ADDR_TYPE_LE_RANDOM:
6208 			return hci_connection->sm_connection.sm_le_db_index >= 0;
6209 #ifdef ENABLE_CLASSIC
6210 		case BD_ADDR_TYPE_SCO:
6211 		case BD_ADDR_TYPE_ACL:
6212 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
6213 #endif
6214 		default:
6215 			return false;
6216 	}
6217 }
6218 
6219 
6220 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
6221     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
6222     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
6223     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
6224     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
6225     return sm_conn->sm_connection_authorization_state;
6226 }
6227 #endif
6228 
6229 #ifdef ENABLE_CLASSIC
6230 uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){
6231     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6232     if (!conn) return GAP_CONNECTION_INVALID;
6233     conn->sniff_min_interval = sniff_min_interval;
6234     conn->sniff_max_interval = sniff_max_interval;
6235     conn->sniff_attempt = sniff_attempt;
6236     conn->sniff_timeout = sniff_timeout;
6237     hci_run();
6238     return 0;
6239 }
6240 
6241 /**
6242  * @brief Exit Sniff mode
6243  * @param con_handle
6244  @ @return 0 if ok
6245  */
6246 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
6247     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6248     if (!conn) return GAP_CONNECTION_INVALID;
6249     conn->sniff_min_interval = 0xffff;
6250     hci_run();
6251     return 0;
6252 }
6253 #endif
6254 
6255 void hci_halting_defer(void){
6256     if (hci_stack->state != HCI_STATE_HALTING) return;
6257     switch (hci_stack->substate){
6258         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
6259         case HCI_HALTING_CLOSE:
6260             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
6261             break;
6262         default:
6263             break;
6264     }
6265 }
6266 
6267 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6268 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
6269     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6270     if (le_device_db_index >= le_device_db_max_count()) return;
6271     uint8_t offset = le_device_db_index >> 3;
6272     uint8_t mask = 1 << (le_device_db_index & 7);
6273     hci_stack->le_resolving_list_add_entries[offset] |= mask;
6274     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6275     	// note: go back to remove entries, otherwise, a remove + add will skip the add
6276         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6277     }
6278 }
6279 
6280 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
6281 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6282 	if (le_device_db_index >= le_device_db_max_count()) return;
6283 	uint8_t offset = le_device_db_index >> 3;
6284 	uint8_t mask = 1 << (le_device_db_index & 7);
6285 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
6286 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6287 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6288 	}
6289 }
6290 
6291 uint8_t gap_load_resolving_list_from_le_device_db(void){
6292 	if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) {
6293 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
6294 	}
6295 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
6296 		// restart le resolving list update
6297 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6298 	}
6299 	return ERROR_CODE_SUCCESS;
6300 }
6301 #endif
6302 
6303 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
6304 void hci_setup_test_connections_fuzz(void){
6305     hci_connection_t * conn;
6306 
6307     // default address: 66:55:44:33:00:01
6308     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
6309 
6310     // setup Controller info
6311     hci_stack->num_cmd_packets = 255;
6312     hci_stack->acl_packets_total_num = 255;
6313 
6314     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
6315     addr[5] = 0x01;
6316     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6317     conn->con_handle = addr[5];
6318     conn->role  = HCI_ROLE_SLAVE;
6319     conn->state = RECEIVED_CONNECTION_REQUEST;
6320     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6321 
6322     // setup incoming Classic SCO connection with con handle 0x0002
6323     addr[5] = 0x02;
6324     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6325     conn->con_handle = addr[5];
6326     conn->role  = HCI_ROLE_SLAVE;
6327     conn->state = RECEIVED_CONNECTION_REQUEST;
6328     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6329 
6330     // setup ready Classic ACL connection with con handle 0x0003
6331     addr[5] = 0x03;
6332     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6333     conn->con_handle = addr[5];
6334     conn->role  = HCI_ROLE_SLAVE;
6335     conn->state = OPEN;
6336     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6337 
6338     // setup ready Classic SCO connection with con handle 0x0004
6339     addr[5] = 0x04;
6340     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6341     conn->con_handle = addr[5];
6342     conn->role  = HCI_ROLE_SLAVE;
6343     conn->state = OPEN;
6344     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6345 
6346     // setup ready LE ACL connection with con handle 0x005 and public address
6347     addr[5] = 0x05;
6348     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
6349     conn->con_handle = addr[5];
6350     conn->role  = HCI_ROLE_SLAVE;
6351     conn->state = OPEN;
6352     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6353 }
6354 
6355 void hci_free_connections_fuzz(void){
6356     btstack_linked_list_iterator_t it;
6357     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6358     while (btstack_linked_list_iterator_has_next(&it)){
6359         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6360         btstack_linked_list_iterator_remove(&it);
6361         btstack_memory_hci_connection_free(con);
6362     }
6363 }
6364 void hci_simulate_working_fuzz(void){
6365     hci_init_done();
6366     hci_stack->num_cmd_packets = 255;
6367 }
6368 #endif
6369