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