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