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