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