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