xref: /btstack/src/hci.c (revision 5999ee11ac6e1ae965ccccaa44efcd2dc55113d0)
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 
2334     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
2335         conn->requested_security_level = LEVEL_0;
2336         hci_emit_security_level(conn->con_handle, gap_security_level_for_connection(conn));
2337         return;
2338     }
2339 
2340     // Request remote features if not already done
2341     hci_trigger_remote_features_for_connection(conn);
2342 
2343     // Request Authentication if not already done
2344     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
2345     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2346 }
2347 #endif
2348 
2349 static void hci_store_local_supported_commands(const uint8_t * packet){
2350     // create mapping table
2351 #define X(name, offset, bit) { offset, bit },
2352     static struct {
2353         uint8_t byte_offset;
2354         uint8_t bit_position;
2355     } supported_hci_commands_map [] = {
2356         SUPPORTED_HCI_COMMANDS
2357     };
2358 #undef X
2359 
2360     // create names for debug purposes
2361 #ifdef ENABLE_LOG_DEBUG
2362 #define X(name, offset, bit) #name,
2363     static const char * command_names[] = {
2364         SUPPORTED_HCI_COMMANDS
2365     };
2366 #undef X
2367 #endif
2368 
2369     hci_stack->local_supported_commands = 0;
2370     const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1];
2371     uint16_t i;
2372     for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){
2373         if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){
2374 #ifdef ENABLE_LOG_DEBUG
2375             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);
2376 #else
2377             log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
2378 #endif
2379             hci_stack->local_supported_commands |= (1LU << i);
2380         }
2381     }
2382     log_info("Local supported commands summary %04x", hci_stack->local_supported_commands);
2383 }
2384 
2385 static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2386     UNUSED(size);
2387 
2388     uint16_t manufacturer;
2389 #ifdef ENABLE_CLASSIC
2390     hci_con_handle_t handle;
2391     hci_connection_t * conn;
2392     uint8_t status;
2393 #endif
2394     // get num cmd packets - limit to 1 to reduce complexity
2395     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
2396 
2397     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2398     switch (opcode){
2399         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2400             if (packet[5]) break;
2401             // terminate, name 248 chars
2402             packet[6+248] = 0;
2403             log_info("local name: %s", &packet[6]);
2404             break;
2405         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
2406             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2407             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2408                 uint16_t acl_len = little_endian_read_16(packet, 6);
2409                 uint16_t sco_len = packet[8];
2410 
2411                 // determine usable ACL/SCO payload size
2412                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2413                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2414 
2415                 hci_stack->acl_packets_total_num = little_endian_read_16(packet, 9);
2416                 hci_stack->sco_packets_total_num = little_endian_read_16(packet, 11);
2417 
2418                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2419                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
2420                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2421             }
2422             break;
2423         case HCI_OPCODE_HCI_READ_RSSI:
2424             if (packet[5] == ERROR_CODE_SUCCESS){
2425                 uint8_t event[5];
2426                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2427                 event[1] = 3;
2428                 (void)memcpy(&event[2], &packet[6], 3);
2429                 hci_emit_event(event, sizeof(event), 1);
2430             }
2431             break;
2432 #ifdef ENABLE_BLE
2433         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2:
2434             hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9);
2435             hci_stack->le_iso_packets_total_num = packet[11];
2436             log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u",
2437                      hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num);
2438 
2439             /* fall through */
2440 
2441         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2442             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2443             hci_stack->le_acl_packets_total_num = packet[8];
2444             // determine usable ACL payload size
2445             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
2446                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
2447             }
2448             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);
2449             break;
2450 #endif
2451 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2452         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2453             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2454             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2455             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);
2456             break;
2457 #endif
2458 #ifdef ENABLE_LE_CENTRAL
2459         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2460             hci_stack->le_whitelist_capacity = packet[6];
2461             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2462             break;
2463 #endif
2464 #ifdef ENABLE_LE_PERIPHERAL
2465 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
2466         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH:
2467             hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6);
2468             break;
2469         case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS:
2470             if (hci_stack->le_advertising_set_in_current_command != 0) {
2471                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2472                 hci_stack->le_advertising_set_in_current_command = 0;
2473                 if (advertising_set == NULL) break;
2474                 uint8_t adv_status = packet[6];
2475                 uint8_t tx_power   = packet[7];
2476                 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 };
2477                 if (adv_status == 0){
2478                     advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
2479                 }
2480                 hci_emit_event(event, sizeof(event), 1);
2481             }
2482             break;
2483         case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET:
2484             if (hci_stack->le_advertising_set_in_current_command != 0) {
2485                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2486                 hci_stack->le_advertising_set_in_current_command = 0;
2487                 if (advertising_set == NULL) break;
2488                 uint8_t adv_status = packet[5];
2489                 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, adv_status };
2490                 if (adv_status == 0){
2491                     btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set);
2492                 }
2493                 hci_emit_event(event, sizeof(event), 1);
2494             }
2495             break;
2496 #endif
2497 #endif
2498         case HCI_OPCODE_HCI_READ_BD_ADDR:
2499             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2500             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));
2501 #ifdef ENABLE_CLASSIC
2502             if (hci_stack->link_key_db){
2503                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
2504             }
2505 #endif
2506             break;
2507 #ifdef ENABLE_CLASSIC
2508         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
2509             hci_emit_discoverable_enabled(hci_stack->discoverable);
2510             break;
2511         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2512             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2513                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2514                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2515                 hci_emit_event(event, sizeof(event), 1);
2516             }
2517             break;
2518 #endif
2519         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
2520             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
2521 
2522 #ifdef ENABLE_CLASSIC
2523             // determine usable ACL packet types based on host buffer size and supported features
2524             hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
2525             log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
2526 #endif
2527             // Classic/LE
2528             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2529             break;
2530         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2531             manufacturer = little_endian_read_16(packet, 10);
2532             // map Cypress to Broadcom
2533             if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2534                 log_info("Treat Cypress as Broadcom");
2535                 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2536                 little_endian_store_16(packet, 10, manufacturer);
2537             }
2538             hci_stack->manufacturer = manufacturer;
2539             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2540             break;
2541         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2542             hci_store_local_supported_commands(packet);
2543             break;
2544 #ifdef ENABLE_CLASSIC
2545         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2546             if (packet[5]) return;
2547             hci_stack->synchronous_flow_control_enabled = 1;
2548             break;
2549         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2550             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2551             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2552             conn   = hci_connection_for_handle(handle);
2553             if (conn != NULL) {
2554                 uint8_t key_size = 0;
2555                 if (status == 0){
2556                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
2557                     log_info("Handle %04x key Size: %u", handle, key_size);
2558                 } else {
2559                     key_size = 1;
2560                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2561                 }
2562                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2563             }
2564             break;
2565         // assert pairing complete event is emitted.
2566         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
2567         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
2568         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
2569         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
2570             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2571             // lookup connection by gap pairing addr
2572             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
2573             if (conn == NULL) break;
2574             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2575             break;
2576 
2577 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2578         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
2579         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
2580             uint8_t event[67];
2581             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
2582             event[1] = 65;
2583             (void)memset(&event[2], 0, 65);
2584             if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){
2585                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
2586                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
2587                     event[2] = 3;
2588                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
2589                 } else {
2590                     event[2] = 1;
2591                 }
2592             }
2593             hci_emit_event(event, sizeof(event), 0);
2594             break;
2595         }
2596 
2597         // note: only needed if user does not provide OOB data
2598         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
2599             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
2600             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
2601             if (conn == NULL) break;
2602             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2603             break;
2604 #endif
2605 #endif
2606         default:
2607             break;
2608     }
2609 }
2610 
2611 #ifdef ENABLE_BLE
2612 static void event_handle_le_connection_complete(const uint8_t * packet){
2613 	bd_addr_t addr;
2614 	bd_addr_type_t addr_type;
2615 	hci_connection_t * conn;
2616 
2617 	// Connection management
2618 	reverse_bd_addr(&packet[8], addr);
2619 	addr_type = (bd_addr_type_t)packet[7];
2620 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2621 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2622 
2623 #ifdef ENABLE_LE_CENTRAL
2624 	// handle error: error is reported only to the initiator -> outgoing connection
2625 	if (packet[3]){
2626 
2627 		// handle cancelled outgoing connection
2628 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2629 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2630 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2631 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2632 		    // reset state
2633             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2634             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2635 			// get outgoing connection conn struct for direct connect
2636 			conn = gap_get_outgoing_connection();
2637 		}
2638 
2639 		// outgoing le connection establishment is done
2640 		if (conn){
2641 			// remove entry
2642 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2643 			btstack_memory_hci_connection_free( conn );
2644 		}
2645 		return;
2646 	}
2647 #endif
2648 
2649 	// on success, both hosts receive connection complete event
2650 	if (packet[6] == HCI_ROLE_MASTER){
2651 #ifdef ENABLE_LE_CENTRAL
2652 		// if we're master on an le connection, it was an outgoing connection and we're done with it
2653 		// note: no hci_connection_t object exists yet for connect with whitelist
2654 		if (hci_is_le_connection_type(addr_type)){
2655 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2656 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2657 		}
2658 #endif
2659 	} else {
2660 #ifdef ENABLE_LE_PERIPHERAL
2661 		// if we're slave, it was an incoming connection, advertisements have stopped
2662         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
2663 #endif
2664 	}
2665 
2666 	// LE connections are auto-accepted, so just create a connection if there isn't one already
2667 	if (!conn){
2668 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2669 	}
2670 
2671 	// no memory, sorry.
2672 	if (!conn){
2673 		return;
2674 	}
2675 
2676 	conn->state = OPEN;
2677 	conn->role  = packet[6];
2678 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
2679 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
2680 
2681 #ifdef ENABLE_LE_PERIPHERAL
2682 	if (packet[6] == HCI_ROLE_SLAVE){
2683 		hci_update_advertisements_enabled_for_current_roles();
2684 	}
2685 #endif
2686 
2687     // init unenhanced att bearer mtu
2688     conn->att_connection.mtu = ATT_DEFAULT_MTU;
2689     conn->att_connection.mtu_exchanged = false;
2690 
2691     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2692 
2693 	// restart timer
2694 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2695 	// btstack_run_loop_add_timer(&conn->timeout);
2696 
2697 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2698 
2699 	hci_emit_nr_connections_changed();
2700 }
2701 #endif
2702 
2703 #ifdef ENABLE_CLASSIC
2704 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){
2705     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
2706     // LEVEL_4 is tested by l2cap
2707     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
2708     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
2709     if (level >= LEVEL_3){
2710         // MITM not possible without keyboard or display
2711         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
2712         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
2713 
2714         // MITM possible if one side has keyboard and the other has keyboard or display
2715         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
2716         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
2717 
2718         // MITM not possible if one side has only display and other side has no keyboard
2719         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
2720         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
2721     }
2722     // LEVEL 2 requires SSP, which is a given
2723     return true;
2724 }
2725 
2726 static bool btstack_is_null(uint8_t * data, uint16_t size){
2727     uint16_t i;
2728     for (i=0; i < size ; i++){
2729         if (data[i] != 0) {
2730             return false;
2731         }
2732     }
2733     return true;
2734 }
2735 
2736 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
2737     // get requested security level
2738     gap_security_level_t requested_security_level = conn->requested_security_level;
2739     if (hci_stack->gap_secure_connections_only_mode){
2740         requested_security_level = LEVEL_4;
2741     }
2742 
2743     // assess security: LEVEL 4 requires SC
2744     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
2745     if ((requested_security_level == LEVEL_4) &&
2746         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
2747         !hci_remote_sc_enabled(conn)){
2748         log_info("Level 4 required, but SC not supported -> abort");
2749         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2750         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2751         return;
2752     }
2753 
2754     // assess security based on io capabilities
2755     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
2756         // responder: fully validate io caps of both sides as well as OOB data
2757         bool security_possible = false;
2758         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
2759 
2760 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2761         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
2762         // so we merge the OOB data availability
2763         uint8_t have_oob_data = conn->io_cap_response_oob_data;
2764         if (conn->classic_oob_c_192 != NULL){
2765             have_oob_data |= 1;
2766         }
2767         if (conn->classic_oob_c_256 != NULL){
2768             have_oob_data |= 2;
2769         }
2770         // for up to Level 3, either P-192 as well as P-256 will do
2771         // 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
2772         // if remote does not SC, we should not receive P-256 data either
2773         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
2774             security_possible = true;
2775         }
2776         // for Level 4, P-256 is needed
2777         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
2778             security_possible = true;
2779         }
2780 #endif
2781 
2782         if (security_possible == false){
2783             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
2784             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2785             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2786             return;
2787         }
2788     } else {
2789         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
2790 #ifndef ENABLE_CLASSIC_PAIRING_OOB
2791 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
2792         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
2793             log_info("Level 3+ required, but no input/output -> abort");
2794             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2795             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2796             return;
2797         }
2798 #endif
2799 #endif
2800     }
2801 
2802 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
2803     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
2804         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
2805     } else {
2806         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
2807     }
2808 #endif
2809 }
2810 
2811 #endif
2812 
2813 static void event_handler(uint8_t *packet, uint16_t size){
2814 
2815     uint16_t event_length = packet[1];
2816 
2817     // assert packet is complete
2818     if (size != (event_length + 2u)){
2819         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
2820         return;
2821     }
2822 
2823     bd_addr_type_t addr_type;
2824     hci_con_handle_t handle;
2825     hci_connection_t * conn;
2826     int i;
2827     int create_connection_cmd;
2828 
2829 #ifdef ENABLE_CLASSIC
2830     hci_link_type_t link_type;
2831     bd_addr_t addr;
2832 #endif
2833 
2834     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
2835 
2836     switch (hci_event_packet_get_type(packet)) {
2837 
2838         case HCI_EVENT_COMMAND_COMPLETE:
2839             handle_command_complete_event(packet, size);
2840             break;
2841 
2842         case HCI_EVENT_COMMAND_STATUS:
2843             // get num cmd packets - limit to 1 to reduce complexity
2844             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2845 
2846             // check command status to detected failed outgoing connections
2847             create_connection_cmd = 0;
2848 #ifdef ENABLE_CLASSIC
2849             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2850                 create_connection_cmd = 1;
2851             }
2852             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_accept_synchronous_connection)){
2853                 create_connection_cmd = 1;
2854             }
2855 #endif
2856 #ifdef ENABLE_LE_CENTRAL
2857             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
2858                 create_connection_cmd = 1;
2859             }
2860 #endif
2861             if (create_connection_cmd) {
2862                 uint8_t status = hci_event_command_status_get_status(packet);
2863                 addr_type = hci_stack->outgoing_addr_type;
2864                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
2865                 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);
2866 
2867                 // reset outgoing address info
2868                 memset(hci_stack->outgoing_addr, 0, 6);
2869                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2870 
2871                 // on error
2872                 if (status != ERROR_CODE_SUCCESS){
2873 #ifdef ENABLE_LE_CENTRAL
2874                     if (hci_is_le_connection_type(addr_type)){
2875                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2876                         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2877                     }
2878 #endif
2879                     // error => outgoing connection failed
2880                     if (conn != NULL){
2881                         hci_handle_connection_failed(conn, status);
2882                     }
2883                 }
2884             }
2885 
2886 #ifdef ENABLE_CLASSIC
2887             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_inquiry)) {
2888                 uint8_t status = hci_event_command_status_get_status(packet);
2889                 log_info("command status (inquiry), status %x", status);
2890                 if (status == ERROR_CODE_SUCCESS) {
2891                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2892                 } else {
2893                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2894                 }
2895             }
2896 #endif
2897             break;
2898 
2899         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
2900             if (size < 3) return;
2901             uint16_t num_handles = packet[2];
2902             if (size != (3u + num_handles * 4u)) return;
2903             uint16_t offset = 3;
2904             for (i=0; i<num_handles;i++){
2905                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
2906                 offset += 2u;
2907                 uint16_t num_packets = little_endian_read_16(packet, offset);
2908                 offset += 2u;
2909 
2910                 conn = hci_connection_for_handle(handle);
2911                 if (!conn){
2912                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
2913                     continue;
2914                 }
2915 
2916                 if (conn->num_packets_sent >= num_packets){
2917                     conn->num_packets_sent -= num_packets;
2918                 } else {
2919                     log_error("hci_number_completed_packets, more packet slots freed then sent.");
2920                     conn->num_packets_sent = 0;
2921                 }
2922                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
2923 
2924 #ifdef ENABLE_CLASSIC
2925                 // For SCO, we do the can_send_now_check here
2926                 hci_notify_if_sco_can_send_now();
2927 #endif
2928             }
2929             break;
2930         }
2931 
2932 #ifdef ENABLE_CLASSIC
2933         case HCI_EVENT_FLUSH_OCCURRED:
2934             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
2935             handle = hci_event_flush_occurred_get_handle(packet);
2936             conn = hci_connection_for_handle(handle);
2937             if (conn) {
2938                 log_info("Flush occurred, disconnect 0x%04x", handle);
2939                 conn->state = SEND_DISCONNECT;
2940             }
2941             break;
2942 
2943         case HCI_EVENT_INQUIRY_COMPLETE:
2944             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2945                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2946                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2947                 hci_emit_event(event, sizeof(event), 1);
2948             }
2949             break;
2950         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2951             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2952                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2953             }
2954             break;
2955         case HCI_EVENT_CONNECTION_REQUEST:
2956             reverse_bd_addr(&packet[2], addr);
2957             link_type = (hci_link_type_t) packet[11];
2958 
2959             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
2960             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
2961                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
2962                 bd_addr_copy(hci_stack->decline_addr, addr);
2963                 break;
2964             }
2965 
2966             if (hci_stack->gap_classic_accept_callback != NULL){
2967                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
2968                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
2969                     bd_addr_copy(hci_stack->decline_addr, addr);
2970                     break;
2971                 }
2972             }
2973 
2974             // TODO: eval COD 8-10
2975             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
2976             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
2977             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2978             if (!conn) {
2979                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2980             }
2981             if (!conn) {
2982                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
2983                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
2984                 bd_addr_copy(hci_stack->decline_addr, addr);
2985                 hci_run();
2986                 // avoid event to higher layer
2987                 return;
2988             }
2989             conn->role  = HCI_ROLE_SLAVE;
2990             conn->state = RECEIVED_CONNECTION_REQUEST;
2991             // store info about eSCO
2992             if (link_type == HCI_LINK_TYPE_ESCO){
2993                 conn->remote_supported_features[0] |= 1;
2994             }
2995             hci_run();
2996             break;
2997 
2998         case HCI_EVENT_CONNECTION_COMPLETE:
2999             // Connection management
3000             reverse_bd_addr(&packet[5], addr);
3001             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3002             addr_type = BD_ADDR_TYPE_ACL;
3003             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3004             if (conn) {
3005                 if (!packet[2]){
3006                     conn->state = OPEN;
3007                     conn->con_handle = little_endian_read_16(packet, 3);
3008 
3009                     // trigger write supervision timeout if we're master
3010                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
3011                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
3012                     }
3013 
3014                     // trigger write automatic flush timeout
3015                     if (hci_stack->automatic_flush_timeout != 0){
3016                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
3017                     }
3018 
3019                     // restart timer
3020                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3021                     btstack_run_loop_add_timer(&conn->timeout);
3022 
3023                     // trigger remote features for dedicated bonding
3024                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3025                         hci_trigger_remote_features_for_connection(conn);
3026                     }
3027 
3028                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3029 
3030                     hci_emit_nr_connections_changed();
3031                 } else {
3032                     // connection failed
3033                     hci_handle_connection_failed(conn, packet[2]);
3034                 }
3035             }
3036             break;
3037 
3038         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3039             reverse_bd_addr(&packet[5], addr);
3040             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3041             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3042             if (packet[2]){
3043                 // connection failed
3044                 if (conn){
3045                     hci_handle_connection_failed(conn, packet[2]);
3046                 }
3047                 break;
3048             }
3049             if (!conn) {
3050                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3051             }
3052             if (!conn) {
3053                 break;
3054             }
3055             conn->state = OPEN;
3056             conn->con_handle = little_endian_read_16(packet, 3);
3057 
3058 #ifdef ENABLE_SCO_OVER_HCI
3059             // update SCO
3060             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3061                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3062             }
3063             // trigger can send now
3064             if (hci_have_usb_transport()){
3065                 hci_stack->sco_can_send_now = true;
3066             }
3067 #endif
3068 #ifdef HAVE_SCO_TRANSPORT
3069             // configure sco transport
3070             if (hci_stack->sco_transport != NULL){
3071                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3072                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3073             }
3074 #endif
3075             break;
3076 
3077         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3078             handle = little_endian_read_16(packet, 3);
3079             conn = hci_connection_for_handle(handle);
3080             if (!conn) break;
3081             if (!packet[2]){
3082                 const uint8_t * features = &packet[5];
3083                 hci_handle_remote_features_page_0(conn, features);
3084 
3085                 // read extended features if possible
3086                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
3087                 && ((conn->remote_supported_features[0] & 2) != 0)) {
3088                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
3089                     break;
3090                 }
3091             }
3092             hci_handle_remote_features_received(conn);
3093             break;
3094 
3095         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3096             handle = little_endian_read_16(packet, 3);
3097             conn = hci_connection_for_handle(handle);
3098             if (!conn) break;
3099             // status = ok, page = 1
3100             if (!packet[2]) {
3101                 uint8_t page_number = packet[5];
3102                 uint8_t maximum_page_number = packet[6];
3103                 const uint8_t * features = &packet[7];
3104                 bool done = false;
3105                 switch (page_number){
3106                     case 1:
3107                         hci_handle_remote_features_page_1(conn, features);
3108                         if (maximum_page_number >= 2){
3109                             // get Secure Connections (Controller) from Page 2 if available
3110                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
3111                         } else {
3112                             // otherwise, assume SC (Controller) == SC (Host)
3113                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
3114                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
3115                             }
3116                             done = true;
3117                         }
3118                         break;
3119                     case 2:
3120                         hci_handle_remote_features_page_2(conn, features);
3121                         done = true;
3122                         break;
3123                     default:
3124                         break;
3125                 }
3126                 if (!done) break;
3127             }
3128             hci_handle_remote_features_received(conn);
3129             break;
3130 
3131         case HCI_EVENT_LINK_KEY_REQUEST:
3132 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
3133             hci_event_link_key_request_get_bd_addr(packet, addr);
3134             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3135             if (!conn) break;
3136 
3137             // lookup link key in db if not cached
3138             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
3139                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
3140             }
3141 
3142             // response sent by hci_run()
3143             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
3144 #endif
3145             break;
3146 
3147         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
3148             hci_event_link_key_request_get_bd_addr(packet, addr);
3149             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3150             if (!conn) break;
3151 
3152             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
3153 
3154             // CVE-2020-26555: ignore NULL link key
3155             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
3156             if (btstack_is_null(&packet[8], 16)) break;
3157 
3158             link_key_type_t link_key_type = (link_key_type_t)packet[24];
3159             // Change Connection Encryption keeps link key type
3160             if (link_key_type != CHANGED_COMBINATION_KEY){
3161                 conn->link_key_type = link_key_type;
3162             }
3163 
3164             // cache link key. link keys stored in little-endian format for legacy reasons
3165             memcpy(&conn->link_key, &packet[8], 16);
3166 
3167             // only store link key:
3168             // - if bondable enabled
3169             if (hci_stack->bondable == false) break;
3170             // - if security level sufficient
3171             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
3172             // - for SSP, also check if remote side requested bonding as well
3173             if (conn->link_key_type != COMBINATION_KEY){
3174                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3175                 if (!remote_bonding){
3176                     break;
3177                 }
3178             }
3179             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
3180             break;
3181         }
3182 
3183         case HCI_EVENT_PIN_CODE_REQUEST:
3184             hci_event_pin_code_request_get_bd_addr(packet, addr);
3185             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3186             if (!conn) break;
3187 
3188             hci_pairing_started(conn, false);
3189             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
3190             if (!hci_stack->bondable ){
3191                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3192                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3193                 hci_run();
3194                 return;
3195             }
3196             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3197             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3198                 log_info("Level 4 required, but SC not supported -> abort");
3199                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3200                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3201                 hci_run();
3202                 return;
3203             }
3204             break;
3205 
3206         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
3207             hci_event_io_capability_response_get_bd_addr(packet, addr);
3208             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3209             if (!conn) break;
3210 
3211             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
3212             hci_pairing_started(conn, true);
3213             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3214             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3215 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3216             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3217 #endif
3218             break;
3219 
3220         case HCI_EVENT_IO_CAPABILITY_REQUEST:
3221             hci_event_io_capability_response_get_bd_addr(packet, addr);
3222             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3223             if (!conn) break;
3224 
3225             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
3226             hci_connection_timestamp(conn);
3227             hci_pairing_started(conn, true);
3228             break;
3229 
3230 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3231         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
3232             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
3233             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3234             if (!conn) break;
3235 
3236             hci_connection_timestamp(conn);
3237 
3238             hci_pairing_started(conn, true);
3239 
3240             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
3241             break;
3242 #endif
3243 
3244         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
3245             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
3246             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3247             if (!conn) break;
3248             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
3249                 if (hci_stack->ssp_auto_accept){
3250                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
3251                 };
3252             } else {
3253                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3254                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
3255                 // don't forward event to app
3256                 hci_run();
3257                 return;
3258             }
3259             break;
3260 
3261         case HCI_EVENT_USER_PASSKEY_REQUEST:
3262             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
3263             if (hci_stack->ssp_auto_accept){
3264                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
3265             };
3266             break;
3267 
3268         case HCI_EVENT_MODE_CHANGE:
3269             handle = hci_event_mode_change_get_handle(packet);
3270             conn = hci_connection_for_handle(handle);
3271             if (!conn) break;
3272             conn->connection_mode = hci_event_mode_change_get_mode(packet);
3273             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
3274             break;
3275 #endif
3276 
3277         case HCI_EVENT_ENCRYPTION_CHANGE:
3278         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
3279             handle = hci_event_encryption_change_get_connection_handle(packet);
3280             conn = hci_connection_for_handle(handle);
3281             if (!conn) break;
3282             if (hci_event_encryption_change_get_status(packet) == 0u) {
3283                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
3284                 if (encryption_enabled){
3285                     if (hci_is_le_connection(conn)){
3286                         // For LE, we accept connection as encrypted
3287                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
3288                     }
3289 #ifdef ENABLE_CLASSIC
3290                     else {
3291 
3292                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
3293                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
3294                         bool connected_uses_aes_ccm = encryption_enabled == 2;
3295                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
3296                             log_info("SC during pairing, but only E0 now -> abort");
3297                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3298                             break;
3299                         }
3300 
3301                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
3302                         if (connected_uses_aes_ccm){
3303                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3304                         }
3305 
3306 #ifdef ENABLE_TESTING_SUPPORT
3307                         // work around for issue with PTS dongle
3308                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3309 #endif
3310                         // validate encryption key size
3311                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
3312                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
3313                             // already got encryption key size
3314                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
3315                         } else {
3316                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
3317                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
3318                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
3319                             } else {
3320                                 // if not, pretend everything is perfect
3321                                 hci_handle_read_encryption_key_size_complete(conn, 16);
3322                             }
3323                         }
3324                     }
3325 #endif
3326                 } else {
3327                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
3328                 }
3329             } else {
3330                 uint8_t status = hci_event_encryption_change_get_status(packet);
3331                 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3332                     conn->bonding_flags &= ~BONDING_DEDICATED;
3333                     conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
3334                     conn->bonding_status = status;
3335                 }
3336             }
3337 
3338             break;
3339 
3340 #ifdef ENABLE_CLASSIC
3341         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
3342             handle = hci_event_authentication_complete_get_connection_handle(packet);
3343             conn = hci_connection_for_handle(handle);
3344             if (!conn) break;
3345 
3346             // clear authentication active flag
3347             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
3348             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
3349 
3350             // authenticated only if auth status == 0
3351             if (hci_event_authentication_complete_get_status(packet) == 0){
3352                 // authenticated
3353                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3354 
3355                 // If not already encrypted, start encryption
3356                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
3357                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3358                     break;
3359                 }
3360             }
3361 
3362             // emit updated security level
3363             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
3364             break;
3365 
3366         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3367             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3368             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3369             if (!conn) break;
3370 
3371             // treat successfully paired connection as authenticated
3372             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
3373                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3374             }
3375 
3376             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
3377             break;
3378 #endif
3379 
3380         // HCI_EVENT_DISCONNECTION_COMPLETE
3381         // has been split, to first notify stack before shutting connection down
3382         // see end of function, too.
3383         case HCI_EVENT_DISCONNECTION_COMPLETE:
3384             if (packet[2]) break;   // status != 0
3385             handle = little_endian_read_16(packet, 3);
3386             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
3387             if (hci_stack->acl_fragmentation_total_size > 0u) {
3388                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3389                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
3390                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
3391                     hci_stack->acl_fragmentation_total_size = 0;
3392                     hci_stack->acl_fragmentation_pos = 0;
3393                     if (release_buffer){
3394                         hci_release_packet_buffer();
3395                     }
3396                 }
3397             }
3398 
3399             conn = hci_connection_for_handle(handle);
3400             if (!conn) break;
3401 #ifdef ENABLE_CLASSIC
3402             // pairing failed if it was ongoing
3403             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
3404 #endif
3405 
3406             // emit dedicatd bonding event
3407             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3408                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3409             }
3410 
3411             // mark connection for shutdown, stop timers, reset state
3412             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3413             hci_connection_stop_timer(conn);
3414             hci_connection_init(conn);
3415 
3416 #ifdef ENABLE_BLE
3417 #ifdef ENABLE_LE_PERIPHERAL
3418             // re-enable advertisements for le connections if active
3419             if (hci_is_le_connection(conn)){
3420                 hci_update_advertisements_enabled_for_current_roles();
3421             }
3422 #endif
3423 #endif
3424             break;
3425 
3426         case HCI_EVENT_HARDWARE_ERROR:
3427             log_error("Hardware Error: 0x%02x", packet[2]);
3428             if (hci_stack->hardware_error_callback){
3429                 (*hci_stack->hardware_error_callback)(packet[2]);
3430             } else {
3431                 // if no special requests, just reboot stack
3432                 hci_power_control_off();
3433                 hci_power_control_on();
3434             }
3435             break;
3436 
3437 #ifdef ENABLE_CLASSIC
3438         case HCI_EVENT_ROLE_CHANGE:
3439             if (packet[2]) break;   // status != 0
3440             reverse_bd_addr(&packet[3], addr);
3441             addr_type = BD_ADDR_TYPE_ACL;
3442             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3443             if (!conn) break;
3444             conn->role = packet[9];
3445             break;
3446 #endif
3447 
3448         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3449             // release packet buffer only for asynchronous transport and if there are not further fragements
3450             if (hci_transport_synchronous()) {
3451                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
3452                 return; // instead of break: to avoid re-entering hci_run()
3453             }
3454             hci_stack->acl_fragmentation_tx_active = 0;
3455             if (hci_stack->acl_fragmentation_total_size) break;
3456             hci_release_packet_buffer();
3457 
3458             // L2CAP receives this event via the hci_emit_event below
3459 
3460 #ifdef ENABLE_CLASSIC
3461             // For SCO, we do the can_send_now_check here
3462             hci_notify_if_sco_can_send_now();
3463 #endif
3464             break;
3465 
3466 #ifdef ENABLE_CLASSIC
3467         case HCI_EVENT_SCO_CAN_SEND_NOW:
3468             // For SCO, we do the can_send_now_check here
3469             hci_stack->sco_can_send_now = true;
3470             hci_notify_if_sco_can_send_now();
3471             return;
3472 
3473         // explode inquriy results for easier consumption
3474         case HCI_EVENT_INQUIRY_RESULT:
3475         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3476         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3477             gap_inquiry_explode(packet, size);
3478             break;
3479 #endif
3480 
3481 #ifdef ENABLE_BLE
3482         case HCI_EVENT_LE_META:
3483             switch (packet[2]){
3484 #ifdef ENABLE_LE_CENTRAL
3485                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
3486                     if (!hci_stack->le_scanning_enabled) break;
3487                     le_handle_advertisement_report(packet, size);
3488                     break;
3489 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3490                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
3491                     if (!hci_stack->le_scanning_enabled) break;
3492                     le_handle_extended_advertisement_report(packet, size);
3493                     break;
3494 #endif
3495 #endif
3496                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3497 					event_handle_le_connection_complete(packet);
3498                     break;
3499 
3500                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3501                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3502                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3503                     conn = hci_connection_for_handle(handle);
3504                     if (!conn) break;
3505                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3506                     break;
3507 
3508                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
3509                     // connection
3510                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
3511                     conn = hci_connection_for_handle(handle);
3512                     if (conn) {
3513                         // read arguments
3514                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
3515                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
3516                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
3517                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
3518 
3519                         // validate against current connection parameter range
3520                         le_connection_parameter_range_t existing_range;
3521                         gap_get_connection_parameter_range(&existing_range);
3522                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3523                         if (update_parameter){
3524                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
3525                             conn->le_conn_interval_min = le_conn_interval_min;
3526                             conn->le_conn_interval_max = le_conn_interval_max;
3527                             conn->le_conn_latency = le_conn_latency;
3528                             conn->le_supervision_timeout = le_supervision_timeout;
3529                         } else {
3530                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
3531                         }
3532                     }
3533                     break;
3534 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3535                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
3536                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
3537                     conn = hci_connection_for_handle(handle);
3538                     if (conn) {
3539                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
3540                     }
3541                     break;
3542 #endif
3543                 default:
3544                     break;
3545             }
3546             break;
3547 #endif
3548         case HCI_EVENT_VENDOR_SPECIFIC:
3549             // Vendor specific commands often create vendor specific event instead of num completed packets
3550             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
3551             switch (hci_stack->manufacturer){
3552                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
3553                     hci_stack->num_cmd_packets = 1;
3554                     break;
3555                 default:
3556                     break;
3557             }
3558             break;
3559         default:
3560             break;
3561     }
3562 
3563     handle_event_for_current_stack_state(packet, size);
3564 
3565     // notify upper stack
3566 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
3567 
3568     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
3569     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
3570 		handle = little_endian_read_16(packet, 3);
3571 		hci_connection_t * aConn = hci_connection_for_handle(handle);
3572 		// discard connection if app did not trigger a reconnect in the event handler
3573 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
3574 			hci_shutdown_connection(aConn);
3575 		}
3576     }
3577 
3578 	// execute main loop
3579 	hci_run();
3580 }
3581 
3582 #ifdef ENABLE_CLASSIC
3583 
3584 #ifdef ENABLE_SCO_OVER_HCI
3585 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
3586 static void sco_schedule_tx(hci_connection_t * conn);
3587 
3588 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
3589     log_debug("SCO TX Timeout");
3590     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
3591     hci_connection_t * conn = hci_connection_for_handle(con_handle);
3592     if (!conn) return;
3593 
3594     // trigger send
3595     conn->sco_tx_ready = 1;
3596     // extra packet if CVSD but SCO buffer is too short
3597     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
3598         conn->sco_tx_ready++;
3599     }
3600     hci_notify_if_sco_can_send_now();
3601 }
3602 
3603 
3604 #define SCO_TX_AFTER_RX_MS (6)
3605 
3606 static void sco_schedule_tx(hci_connection_t * conn){
3607 
3608     uint32_t now = btstack_run_loop_get_time_ms();
3609     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
3610     int time_delta_ms = sco_tx_ms - now;
3611 
3612     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
3613 
3614     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
3615     btstack_run_loop_remove_timer(timer);
3616     btstack_run_loop_set_timer(timer, time_delta_ms);
3617     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
3618     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
3619     btstack_run_loop_add_timer(timer);
3620 }
3621 #endif
3622 
3623 static void sco_handler(uint8_t * packet, uint16_t size){
3624     // lookup connection struct
3625     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
3626     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
3627     if (!conn) return;
3628 
3629 #ifdef ENABLE_SCO_OVER_HCI
3630     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
3631     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
3632         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
3633             packet[2] = 0x3c;
3634             memmove(&packet[3], &packet[23], 63);
3635             size = 63;
3636         }
3637     }
3638 
3639     if (hci_have_usb_transport()){
3640         // Nothing to do
3641     } else {
3642         // 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);
3643         if (hci_stack->synchronous_flow_control_enabled == 0){
3644             uint32_t now = btstack_run_loop_get_time_ms();
3645 
3646             if (!conn->sco_rx_valid){
3647                 // ignore first 10 packets
3648                 conn->sco_rx_count++;
3649                 // log_debug("sco rx count %u", conn->sco_rx_count);
3650                 if (conn->sco_rx_count == 10) {
3651                     // use first timestamp as is and pretent it just started
3652                     conn->sco_rx_ms = now;
3653                     conn->sco_rx_valid = 1;
3654                     conn->sco_rx_count = 0;
3655                     sco_schedule_tx(conn);
3656                 }
3657             } else {
3658                 // track expected arrival timme
3659                 conn->sco_rx_count++;
3660                 conn->sco_rx_ms += 7;
3661                 int delta = (int32_t) (now - conn->sco_rx_ms);
3662                 if (delta > 0){
3663                     conn->sco_rx_ms++;
3664                 }
3665                 // log_debug("sco rx %u", conn->sco_rx_ms);
3666                 sco_schedule_tx(conn);
3667             }
3668         }
3669     }
3670 #endif
3671 
3672     // deliver to app
3673     if (hci_stack->sco_packet_handler) {
3674         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
3675     }
3676 
3677 #ifdef HAVE_SCO_TRANSPORT
3678     // We can send one packet for each received packet
3679     conn->sco_tx_ready++;
3680     hci_notify_if_sco_can_send_now();
3681 #endif
3682 
3683 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3684     conn->num_packets_completed++;
3685     hci_stack->host_completed_packets = 1;
3686     hci_run();
3687 #endif
3688 }
3689 #endif
3690 
3691 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
3692     hci_dump_packet(packet_type, 1, packet, size);
3693     switch (packet_type) {
3694         case HCI_EVENT_PACKET:
3695             event_handler(packet, size);
3696             break;
3697         case HCI_ACL_DATA_PACKET:
3698             acl_handler(packet, size);
3699             break;
3700 #ifdef ENABLE_CLASSIC
3701         case HCI_SCO_DATA_PACKET:
3702             sco_handler(packet, size);
3703             break;
3704 #endif
3705         default:
3706             break;
3707     }
3708 }
3709 
3710 /**
3711  * @brief Add event packet handler.
3712  */
3713 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3714     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3715 }
3716 
3717 /**
3718  * @brief Remove event packet handler.
3719  */
3720 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
3721     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3722 }
3723 
3724 /** Register HCI packet handlers */
3725 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3726     hci_stack->acl_packet_handler = handler;
3727 }
3728 
3729 #ifdef ENABLE_CLASSIC
3730 /**
3731  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
3732  */
3733 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
3734     hci_stack->sco_packet_handler = handler;
3735 }
3736 #endif
3737 
3738 static void hci_state_reset(void){
3739     // no connections yet
3740     hci_stack->connections = NULL;
3741 
3742     // keep discoverable/connectable as this has been requested by the client(s)
3743     // hci_stack->discoverable = 0;
3744     // hci_stack->connectable = 0;
3745     // hci_stack->bondable = 1;
3746     // hci_stack->own_addr_type = 0;
3747 
3748     // buffer is free
3749     hci_stack->hci_packet_buffer_reserved = false;
3750 
3751     // no pending cmds
3752     hci_stack->decline_reason = 0;
3753 
3754     hci_stack->secure_connections_active = false;
3755 
3756 #ifdef ENABLE_CLASSIC
3757     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
3758     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
3759 
3760     hci_stack->gap_tasks_classic =
3761             GAP_TASK_SET_DEFAULT_LINK_POLICY |
3762             GAP_TASK_SET_CLASS_OF_DEVICE |
3763             GAP_TASK_SET_LOCAL_NAME |
3764             GAP_TASK_SET_EIR_DATA |
3765             GAP_TASK_WRITE_SCAN_ENABLE |
3766             GAP_TASK_WRITE_PAGE_TIMEOUT;
3767 #endif
3768 
3769 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3770     hci_stack->classic_read_local_oob_data = false;
3771     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
3772 #endif
3773 
3774     // LE
3775 #ifdef ENABLE_BLE
3776     memset(hci_stack->le_random_address, 0, 6);
3777     hci_stack->le_random_address_set = 0;
3778 #endif
3779 #ifdef ENABLE_LE_CENTRAL
3780     hci_stack->le_scanning_active  = false;
3781     hci_stack->le_scanning_param_update = true;
3782     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3783     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3784     hci_stack->le_whitelist_capacity = 0;
3785 #endif
3786 #ifdef ENABLE_LE_PERIPHERAL
3787     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
3788     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
3789         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3790     }
3791     if (hci_stack->le_advertisements_data != NULL){
3792         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3793     }
3794 #endif
3795 }
3796 
3797 #ifdef ENABLE_CLASSIC
3798 /**
3799  * @brief Configure Bluetooth hardware control. Has to be called before power on.
3800  */
3801 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
3802     // store and open remote device db
3803     hci_stack->link_key_db = link_key_db;
3804     if (hci_stack->link_key_db) {
3805         hci_stack->link_key_db->open();
3806     }
3807 }
3808 #endif
3809 
3810 void hci_init(const hci_transport_t *transport, const void *config){
3811 
3812 #ifdef HAVE_MALLOC
3813     if (!hci_stack) {
3814         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
3815     }
3816 #else
3817     hci_stack = &hci_stack_static;
3818 #endif
3819     memset(hci_stack, 0, sizeof(hci_stack_t));
3820 
3821     // reference to use transport layer implementation
3822     hci_stack->hci_transport = transport;
3823 
3824     // reference to used config
3825     hci_stack->config = config;
3826 
3827     // setup pointer for outgoing packet buffer
3828     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
3829 
3830     // max acl payload size defined in config.h
3831     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
3832 
3833     // register packet handlers with transport
3834     transport->register_packet_handler(&packet_handler);
3835 
3836     hci_stack->state = HCI_STATE_OFF;
3837 
3838     // class of device
3839     hci_stack->class_of_device = 0x007a020c; // Smartphone
3840 
3841     // bondable by default
3842     hci_stack->bondable = 1;
3843 
3844 #ifdef ENABLE_CLASSIC
3845     // classic name
3846     hci_stack->local_name = default_classic_name;
3847 
3848     // Master slave policy
3849     hci_stack->master_slave_policy = 1;
3850 
3851     // Allow Role Switch
3852     hci_stack->allow_role_switch = 1;
3853 
3854     // Default / minimum security level = 2
3855     hci_stack->gap_security_level = LEVEL_2;
3856 
3857     // Default Security Mode 4
3858     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
3859 
3860     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3861     hci_stack->gap_required_encyrption_key_size = 7;
3862 
3863     // Link Supervision Timeout
3864     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
3865 
3866 #endif
3867 
3868     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
3869     hci_stack->ssp_enable = 1;
3870     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
3871     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
3872     hci_stack->ssp_auto_accept = 1;
3873 
3874     // Secure Connections: enable (requires support from Controller)
3875     hci_stack->secure_connections_enable = true;
3876 
3877     // voice setting - signed 16 bit pcm data with CVSD over the air
3878     hci_stack->sco_voice_setting = 0x60;
3879 
3880 #ifdef ENABLE_LE_CENTRAL
3881     // connection parameter to use for outgoing connections
3882     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3883     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3884     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3885     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3886     hci_stack->le_connection_latency      = 4;         // 4
3887     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3888     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3889     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
3890 
3891     // default LE Scanning
3892     hci_stack->le_scan_type     =   0x1; // active
3893     hci_stack->le_scan_interval = 0x1e0; // 300 ms
3894     hci_stack->le_scan_window   =  0x30; //  30 ms
3895 #endif
3896 
3897 #ifdef ENABLE_LE_PERIPHERAL
3898     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
3899 #endif
3900 
3901     // connection parameter range used to answer connection parameter update requests in l2cap
3902     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3903     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3904     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3905     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3906     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3907     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3908 
3909     hci_state_reset();
3910 }
3911 
3912 void hci_deinit(void){
3913     btstack_run_loop_remove_timer(&hci_stack->timeout);
3914 #ifdef HAVE_MALLOC
3915     if (hci_stack) {
3916         free(hci_stack);
3917     }
3918 #endif
3919     hci_stack = NULL;
3920 
3921 #ifdef ENABLE_CLASSIC
3922     disable_l2cap_timeouts = 0;
3923 #endif
3924 }
3925 
3926 /**
3927  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
3928  */
3929 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
3930     hci_stack->chipset = chipset_driver;
3931 
3932     // reset chipset driver - init is also called on power_up
3933     if (hci_stack->chipset && hci_stack->chipset->init){
3934         hci_stack->chipset->init(hci_stack->config);
3935     }
3936 }
3937 
3938 /**
3939  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3940  */
3941 void hci_set_control(const btstack_control_t *hardware_control){
3942     // references to used control implementation
3943     hci_stack->control = hardware_control;
3944     // init with transport config
3945     hardware_control->init(hci_stack->config);
3946 }
3947 
3948 static void hci_discard_connections(void){
3949     btstack_linked_list_iterator_t lit;
3950     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
3951     while (btstack_linked_list_iterator_has_next(&lit)){
3952         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
3953         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
3954         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
3955         hci_shutdown_connection(connection);
3956     }
3957 }
3958 
3959 void hci_close(void){
3960 
3961 #ifdef ENABLE_CLASSIC
3962     // close remote device db
3963     if (hci_stack->link_key_db) {
3964         hci_stack->link_key_db->close();
3965     }
3966 #endif
3967 
3968     hci_discard_connections();
3969 
3970     hci_power_control(HCI_POWER_OFF);
3971 
3972 #ifdef HAVE_MALLOC
3973     free(hci_stack);
3974 #endif
3975     hci_stack = NULL;
3976 }
3977 
3978 #ifdef HAVE_SCO_TRANSPORT
3979 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3980     hci_stack->sco_transport = sco_transport;
3981     sco_transport->register_packet_handler(&packet_handler);
3982 }
3983 #endif
3984 
3985 #ifdef ENABLE_CLASSIC
3986 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3987     // validate ranage and set
3988     if (encryption_key_size < 7)  return;
3989     if (encryption_key_size > 16) return;
3990     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3991 }
3992 
3993 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
3994     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
3995         hci_stack->gap_security_mode = security_mode;
3996         return ERROR_CODE_SUCCESS;
3997     } else {
3998         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3999     }
4000 }
4001 
4002 gap_security_mode_t gap_get_security_mode(void){
4003     return hci_stack->gap_security_mode;
4004 }
4005 
4006 void gap_set_security_level(gap_security_level_t security_level){
4007     hci_stack->gap_security_level = security_level;
4008 }
4009 
4010 gap_security_level_t gap_get_security_level(void){
4011     if (hci_stack->gap_secure_connections_only_mode){
4012         return LEVEL_4;
4013     }
4014     return hci_stack->gap_security_level;
4015 }
4016 
4017 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
4018     hci_stack->gap_minimal_service_security_level = security_level;
4019 }
4020 
4021 void gap_set_secure_connections_only_mode(bool enable){
4022     hci_stack->gap_secure_connections_only_mode = enable;
4023 }
4024 
4025 bool gap_get_secure_connections_only_mode(void){
4026     return hci_stack->gap_secure_connections_only_mode;
4027 }
4028 #endif
4029 
4030 #ifdef ENABLE_CLASSIC
4031 void gap_set_class_of_device(uint32_t class_of_device){
4032     hci_stack->class_of_device = class_of_device;
4033     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
4034     hci_run();
4035 }
4036 
4037 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4038     hci_stack->default_link_policy_settings = default_link_policy_settings;
4039     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
4040     hci_run();
4041 }
4042 
4043 void gap_set_allow_role_switch(bool allow_role_switch){
4044     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4045 }
4046 
4047 uint8_t hci_get_allow_role_switch(void){
4048     return  hci_stack->allow_role_switch;
4049 }
4050 
4051 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
4052     hci_stack->link_supervision_timeout = link_supervision_timeout;
4053 }
4054 
4055 void gap_enable_link_watchdog(uint16_t timeout_ms){
4056     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
4057 }
4058 
4059 uint16_t hci_automatic_flush_timeout(void){
4060     return hci_stack->automatic_flush_timeout;
4061 }
4062 
4063 void hci_disable_l2cap_timeout_check(void){
4064     disable_l2cap_timeouts = 1;
4065 }
4066 #endif
4067 
4068 #ifndef HAVE_HOST_CONTROLLER_API
4069 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4070 void hci_set_bd_addr(bd_addr_t addr){
4071     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4072     hci_stack->custom_bd_addr_set = 1;
4073 }
4074 #endif
4075 
4076 // State-Module-Driver overview
4077 // state                    module  low-level
4078 // HCI_STATE_OFF             off      close
4079 // HCI_STATE_INITIALIZING,   on       open
4080 // HCI_STATE_WORKING,        on       open
4081 // HCI_STATE_HALTING,        on       open
4082 // HCI_STATE_SLEEPING,    off/sleep   close
4083 // HCI_STATE_FALLING_ASLEEP  on       open
4084 
4085 static int hci_power_control_on(void){
4086 
4087     // power on
4088     int err = 0;
4089     if (hci_stack->control && hci_stack->control->on){
4090         err = (*hci_stack->control->on)();
4091     }
4092     if (err){
4093         log_error( "POWER_ON failed");
4094         hci_emit_hci_open_failed();
4095         return err;
4096     }
4097 
4098     // int chipset driver
4099     if (hci_stack->chipset && hci_stack->chipset->init){
4100         hci_stack->chipset->init(hci_stack->config);
4101     }
4102 
4103     // init transport
4104     if (hci_stack->hci_transport->init){
4105         hci_stack->hci_transport->init(hci_stack->config);
4106     }
4107 
4108     // open transport
4109     err = hci_stack->hci_transport->open();
4110     if (err){
4111         log_error( "HCI_INIT failed, turning Bluetooth off again");
4112         if (hci_stack->control && hci_stack->control->off){
4113             (*hci_stack->control->off)();
4114         }
4115         hci_emit_hci_open_failed();
4116         return err;
4117     }
4118     return 0;
4119 }
4120 
4121 static void hci_power_control_off(void){
4122 
4123     log_info("hci_power_control_off");
4124 
4125     // close low-level device
4126     hci_stack->hci_transport->close();
4127 
4128     log_info("hci_power_control_off - hci_transport closed");
4129 
4130     // power off
4131     if (hci_stack->control && hci_stack->control->off){
4132         (*hci_stack->control->off)();
4133     }
4134 
4135     log_info("hci_power_control_off - control closed");
4136 
4137     hci_stack->state = HCI_STATE_OFF;
4138 }
4139 
4140 static void hci_power_control_sleep(void){
4141 
4142     log_info("hci_power_control_sleep");
4143 
4144 #if 0
4145     // don't close serial port during sleep
4146 
4147     // close low-level device
4148     hci_stack->hci_transport->close(hci_stack->config);
4149 #endif
4150 
4151     // sleep mode
4152     if (hci_stack->control && hci_stack->control->sleep){
4153         (*hci_stack->control->sleep)();
4154     }
4155 
4156     hci_stack->state = HCI_STATE_SLEEPING;
4157 }
4158 
4159 static int hci_power_control_wake(void){
4160 
4161     log_info("hci_power_control_wake");
4162 
4163     // wake on
4164     if (hci_stack->control && hci_stack->control->wake){
4165         (*hci_stack->control->wake)();
4166     }
4167 
4168 #if 0
4169     // open low-level device
4170     int err = hci_stack->hci_transport->open(hci_stack->config);
4171     if (err){
4172         log_error( "HCI_INIT failed, turning Bluetooth off again");
4173         if (hci_stack->control && hci_stack->control->off){
4174             (*hci_stack->control->off)();
4175         }
4176         hci_emit_hci_open_failed();
4177         return err;
4178     }
4179 #endif
4180 
4181     return 0;
4182 }
4183 
4184 static void hci_power_enter_initializing_state(void){
4185     // set up state machine
4186     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
4187     hci_stack->hci_packet_buffer_reserved = false;
4188     hci_stack->state = HCI_STATE_INITIALIZING;
4189     hci_stack->substate = HCI_INIT_SEND_RESET;
4190 }
4191 
4192 static void hci_power_enter_halting_state(void){
4193 #ifdef ENABLE_BLE
4194     hci_whitelist_free();
4195 #endif
4196     // see hci_run
4197     hci_stack->state = HCI_STATE_HALTING;
4198     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
4199     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
4200     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
4201     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4202     btstack_run_loop_add_timer(&hci_stack->timeout);
4203 }
4204 
4205 // returns error
4206 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
4207     int err;
4208     switch (power_mode){
4209         case HCI_POWER_ON:
4210             err = hci_power_control_on();
4211             if (err != 0) {
4212                 log_error("hci_power_control_on() error %d", err);
4213                 return err;
4214             }
4215             hci_power_enter_initializing_state();
4216             break;
4217         case HCI_POWER_OFF:
4218             // do nothing
4219             break;
4220         case HCI_POWER_SLEEP:
4221             // do nothing (with SLEEP == OFF)
4222             break;
4223         default:
4224             btstack_assert(false);
4225             break;
4226     }
4227     return ERROR_CODE_SUCCESS;
4228 }
4229 
4230 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
4231     switch (power_mode){
4232         case HCI_POWER_ON:
4233             // do nothing
4234             break;
4235         case HCI_POWER_OFF:
4236             // no connections yet, just turn it off
4237             hci_power_control_off();
4238             break;
4239         case HCI_POWER_SLEEP:
4240             // no connections yet, just turn it off
4241             hci_power_control_sleep();
4242             break;
4243         default:
4244             btstack_assert(false);
4245             break;
4246     }
4247     return ERROR_CODE_SUCCESS;
4248 }
4249 
4250 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
4251     switch (power_mode){
4252         case HCI_POWER_ON:
4253             // do nothing
4254             break;
4255         case HCI_POWER_OFF:
4256             hci_power_enter_halting_state();
4257             break;
4258         case HCI_POWER_SLEEP:
4259             // see hci_run
4260             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4261             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4262             break;
4263         default:
4264             btstack_assert(false);
4265             break;
4266     }
4267     return ERROR_CODE_SUCCESS;
4268 }
4269 
4270 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
4271     switch (power_mode){
4272         case HCI_POWER_ON:
4273             hci_power_enter_initializing_state();
4274             break;
4275         case HCI_POWER_OFF:
4276             // do nothing
4277             break;
4278         case HCI_POWER_SLEEP:
4279             // see hci_run
4280             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4281             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4282             break;
4283         default:
4284             btstack_assert(false);
4285             break;
4286     }
4287     return ERROR_CODE_SUCCESS;
4288 }
4289 
4290 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
4291     switch (power_mode){
4292         case HCI_POWER_ON:
4293             hci_power_enter_initializing_state();
4294             break;
4295         case HCI_POWER_OFF:
4296             hci_power_enter_halting_state();
4297             break;
4298         case HCI_POWER_SLEEP:
4299             // do nothing
4300             break;
4301         default:
4302             btstack_assert(false);
4303             break;
4304     }
4305     return ERROR_CODE_SUCCESS;
4306 }
4307 
4308 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
4309     int err;
4310     switch (power_mode){
4311         case HCI_POWER_ON:
4312             err = hci_power_control_wake();
4313             if (err) return err;
4314             hci_power_enter_initializing_state();
4315             break;
4316         case HCI_POWER_OFF:
4317             hci_power_enter_halting_state();
4318             break;
4319         case HCI_POWER_SLEEP:
4320             // do nothing
4321             break;
4322         default:
4323             btstack_assert(false);
4324             break;
4325     }
4326     return ERROR_CODE_SUCCESS;
4327 }
4328 
4329 int hci_power_control(HCI_POWER_MODE power_mode){
4330     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
4331     int err = 0;
4332     switch (hci_stack->state){
4333         case HCI_STATE_OFF:
4334             err = hci_power_control_state_off(power_mode);
4335             break;
4336         case HCI_STATE_INITIALIZING:
4337             err = hci_power_control_state_initializing(power_mode);
4338             break;
4339         case HCI_STATE_WORKING:
4340             err = hci_power_control_state_working(power_mode);
4341             break;
4342         case HCI_STATE_HALTING:
4343             err = hci_power_control_state_halting(power_mode);
4344             break;
4345         case HCI_STATE_FALLING_ASLEEP:
4346             err = hci_power_control_state_falling_asleep(power_mode);
4347             break;
4348         case HCI_STATE_SLEEPING:
4349             err = hci_power_control_state_sleeping(power_mode);
4350             break;
4351         default:
4352             btstack_assert(false);
4353             break;
4354     }
4355     if (err != 0){
4356         return err;
4357     }
4358 
4359     // create internal event
4360 	hci_emit_state();
4361 
4362 	// trigger next/first action
4363 	hci_run();
4364 
4365     return 0;
4366 }
4367 
4368 
4369 static void hci_halting_run(void) {
4370 
4371     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4372 
4373     hci_connection_t *connection;
4374 #ifdef ENABLE_BLE
4375 #ifdef ENABLE_LE_PERIPHERAL
4376     bool stop_advertismenets;
4377 #endif
4378 #endif
4379 
4380     switch (hci_stack->substate) {
4381         case HCI_HALTING_CLASSIC_STOP:
4382 #ifdef ENABLE_CLASSIC
4383             if (!hci_can_send_command_packet_now()) return;
4384 
4385             if (hci_stack->connectable || hci_stack->discoverable){
4386                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4387                 hci_send_cmd(&hci_write_scan_enable, 0);
4388                 return;
4389             }
4390 #endif
4391             /* fall through */
4392 
4393         case HCI_HALTING_LE_ADV_STOP:
4394             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4395 
4396 #ifdef ENABLE_BLE
4397 #ifdef ENABLE_LE_PERIPHERAL
4398             if (!hci_can_send_command_packet_now()) return;
4399 
4400             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
4401 
4402 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4403             if (hci_extended_advertising_supported()){
4404                 btstack_linked_list_iterator_t it;
4405                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4406                 // stop all periodic advertisements and check if an extended set is active
4407                 while (btstack_linked_list_iterator_has_next(&it)){
4408                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4409                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
4410                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
4411                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
4412                         return;
4413                     }
4414                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
4415                         stop_advertismenets = true;
4416                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4417                     }
4418                 }
4419                 if (stop_advertismenets){
4420                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4421                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
4422                     return;
4423                 }
4424             }
4425             else
4426 #else
4427             {
4428                 if (stop_advertismenets) {
4429                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4430                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
4431                     return;
4432                 }
4433             }
4434 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
4435 #endif  /* ENABLE_LE_PERIPHERAL */
4436 #endif  /* ENABLE_BLE */
4437 
4438             /* fall through */
4439 
4440         case HCI_HALTING_LE_SCAN_STOP:
4441             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
4442             if (!hci_can_send_command_packet_now()) return;
4443 
4444 #ifdef ENABLE_BLE
4445 #ifdef ENABLE_LE_CENTRAL
4446             if (hci_stack->le_scanning_active){
4447                 hci_le_scan_stop();
4448                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4449                 return;
4450             }
4451 #endif
4452 #endif
4453 
4454             /* fall through */
4455 
4456         case HCI_HALTING_DISCONNECT_ALL:
4457             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4458             if (!hci_can_send_command_packet_now()) return;
4459 
4460             // close all open connections
4461             connection = (hci_connection_t *) hci_stack->connections;
4462             if (connection) {
4463                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4464 
4465                 // check state
4466                 if (connection->state == SENT_DISCONNECT) return;
4467                 connection->state = SENT_DISCONNECT;
4468 
4469                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4470 
4471                 // finally, send the disconnect command
4472                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4473                 return;
4474             }
4475 
4476             btstack_run_loop_remove_timer(&hci_stack->timeout);
4477 
4478             hci_stack->substate = HCI_HALTING_READY_FOR_CLOSE;
4479 
4480             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4481             log_info("HCI_STATE_HALTING: wait 50 ms");
4482             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
4483             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
4484             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4485             btstack_run_loop_add_timer(&hci_stack->timeout);
4486             break;
4487 
4488         case HCI_HALTING_CLOSE:
4489             // close left over connections (that had not been properly closed before)
4490             hci_discard_connections();
4491 
4492             log_info("HCI_STATE_HALTING, calling off");
4493 
4494             // switch mode
4495             hci_power_control_off();
4496 
4497             log_info("HCI_STATE_HALTING, emitting state");
4498             hci_emit_state();
4499             log_info("HCI_STATE_HALTING, done");
4500             break;
4501 
4502         case HCI_HALTING_W4_CLOSE_TIMER:
4503             // keep waiting
4504 
4505             break;
4506         default:
4507             break;
4508     }
4509 };
4510 
4511 static void hci_falling_asleep_run(void){
4512     hci_connection_t * connection;
4513     switch(hci_stack->substate) {
4514         case HCI_FALLING_ASLEEP_DISCONNECT:
4515             log_info("HCI_STATE_FALLING_ASLEEP");
4516             // close all open connections
4517             connection =  (hci_connection_t *) hci_stack->connections;
4518             if (connection){
4519 
4520                 // send disconnect
4521                 if (!hci_can_send_command_packet_now()) return;
4522 
4523                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
4524                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4525 
4526                 // send disconnected event right away - causes higher layer connections to get closed, too.
4527                 hci_shutdown_connection(connection);
4528                 return;
4529             }
4530 
4531             if (hci_classic_supported()){
4532                 // disable page and inquiry scan
4533                 if (!hci_can_send_command_packet_now()) return;
4534 
4535                 log_info("HCI_STATE_HALTING, disabling inq scans");
4536                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
4537 
4538                 // continue in next sub state
4539                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
4540                 break;
4541             }
4542 
4543             /* fall through */
4544 
4545             case HCI_FALLING_ASLEEP_COMPLETE:
4546                 log_info("HCI_STATE_HALTING, calling sleep");
4547                 // switch mode
4548                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
4549                 hci_emit_state();
4550                 break;
4551 
4552                 default:
4553                     break;
4554     }
4555 }
4556 
4557 #ifdef ENABLE_CLASSIC
4558 
4559 static void hci_update_scan_enable(void){
4560     // 2 = page scan, 1 = inq scan
4561     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
4562     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
4563     hci_run();
4564 }
4565 
4566 void gap_discoverable_control(uint8_t enable){
4567     if (enable) enable = 1; // normalize argument
4568 
4569     if (hci_stack->discoverable == enable){
4570         hci_emit_discoverable_enabled(hci_stack->discoverable);
4571         return;
4572     }
4573 
4574     hci_stack->discoverable = enable;
4575     hci_update_scan_enable();
4576 }
4577 
4578 void gap_connectable_control(uint8_t enable){
4579     if (enable) enable = 1; // normalize argument
4580 
4581     // don't emit event
4582     if (hci_stack->connectable == enable) return;
4583 
4584     hci_stack->connectable = enable;
4585     hci_update_scan_enable();
4586 }
4587 #endif
4588 
4589 void gap_local_bd_addr(bd_addr_t address_buffer){
4590     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
4591 }
4592 
4593 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4594 static void hci_host_num_completed_packets(void){
4595 
4596     // create packet manually as arrays are not supported and num_commands should not get reduced
4597     hci_reserve_packet_buffer();
4598     uint8_t * packet = hci_get_outgoing_packet_buffer();
4599 
4600     uint16_t size = 0;
4601     uint16_t num_handles = 0;
4602     packet[size++] = 0x35;
4603     packet[size++] = 0x0c;
4604     size++;  // skip param len
4605     size++;  // skip num handles
4606 
4607     // add { handle, packets } entries
4608     btstack_linked_item_t * it;
4609     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4610         hci_connection_t * connection = (hci_connection_t *) it;
4611         if (connection->num_packets_completed){
4612             little_endian_store_16(packet, size, connection->con_handle);
4613             size += 2;
4614             little_endian_store_16(packet, size, connection->num_packets_completed);
4615             size += 2;
4616             //
4617             num_handles++;
4618             connection->num_packets_completed = 0;
4619         }
4620     }
4621 
4622     packet[2] = size - 3;
4623     packet[3] = num_handles;
4624 
4625     hci_stack->host_completed_packets = 0;
4626 
4627     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4628     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
4629 
4630     // release packet buffer for synchronous transport implementations
4631     if (hci_transport_synchronous()){
4632         hci_release_packet_buffer();
4633         hci_emit_transport_packet_sent();
4634     }
4635 }
4636 #endif
4637 
4638 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
4639     UNUSED(ds);
4640     hci_stack->substate = HCI_HALTING_CLOSE;
4641     // allow packet handlers to defer final shutdown
4642     hci_emit_state();
4643     hci_run();
4644 }
4645 
4646 static bool hci_run_acl_fragments(void){
4647     if (hci_stack->acl_fragmentation_total_size > 0u) {
4648         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
4649         hci_connection_t *connection = hci_connection_for_handle(con_handle);
4650         if (connection) {
4651             if (hci_can_send_prepared_acl_packet_now(con_handle)){
4652                 hci_send_acl_packet_fragments(connection);
4653                 return true;
4654             }
4655         } else {
4656             // connection gone -> discard further fragments
4657             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
4658             hci_stack->acl_fragmentation_total_size = 0;
4659             hci_stack->acl_fragmentation_pos = 0;
4660         }
4661     }
4662     return false;
4663 }
4664 
4665 #ifdef ENABLE_CLASSIC
4666 
4667 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
4668 static bool hci_classic_operation_active(void) {
4669     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
4670         return true;
4671     }
4672     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
4673         return true;
4674     }
4675     btstack_linked_item_t * it;
4676     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
4677         hci_connection_t *connection = (hci_connection_t *) it;
4678         switch (connection->state) {
4679             case SENT_CREATE_CONNECTION:
4680             case SENT_CANCEL_CONNECTION:
4681             case SENT_DISCONNECT:
4682                 return true;
4683             default:
4684                 break;
4685         }
4686     }
4687     return false;
4688 }
4689 #endif
4690 
4691 static bool hci_run_general_gap_classic(void){
4692 
4693     // assert stack is working and classic is active
4694     if (hci_classic_supported() == false)      return false;
4695     if (hci_stack->state != HCI_STATE_WORKING) return false;
4696 
4697     // decline incoming connections
4698     if (hci_stack->decline_reason){
4699         uint8_t reason = hci_stack->decline_reason;
4700         hci_stack->decline_reason = 0;
4701         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
4702         return true;
4703     }
4704 
4705     if (hci_stack->gap_tasks_classic != 0){
4706         hci_run_gap_tasks_classic();
4707         return true;
4708     }
4709 
4710     // start/stop inquiry
4711     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
4712 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
4713         if (hci_classic_operation_active() == false)
4714 #endif
4715         {
4716             uint8_t duration = hci_stack->inquiry_state;
4717             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
4718             hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
4719             return true;
4720         }
4721     }
4722     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
4723         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
4724         hci_send_cmd(&hci_inquiry_cancel);
4725         return true;
4726     }
4727     // remote name request
4728     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
4729 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
4730         if (hci_classic_operation_active() == false)
4731 #endif
4732         {
4733             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
4734             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
4735                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
4736             return true;
4737         }
4738     }
4739 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4740     // Local OOB data
4741     if (hci_stack->classic_read_local_oob_data){
4742         hci_stack->classic_read_local_oob_data = false;
4743         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
4744             hci_send_cmd(&hci_read_local_extended_oob_data);
4745         } else {
4746             hci_send_cmd(&hci_read_local_oob_data);
4747         }
4748     }
4749 #endif
4750     // pairing
4751     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
4752         uint8_t state = hci_stack->gap_pairing_state;
4753         uint8_t pin_code[16];
4754         switch (state){
4755             case GAP_PAIRING_STATE_SEND_PIN:
4756                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4757                 memset(pin_code, 0, 16);
4758                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
4759                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
4760                 break;
4761             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
4762                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4763                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
4764                 break;
4765             case GAP_PAIRING_STATE_SEND_PASSKEY:
4766                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4767                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
4768                 break;
4769             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
4770                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4771                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
4772                 break;
4773             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
4774                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4775                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
4776                 break;
4777             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
4778                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4779                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
4780                 break;
4781             default:
4782                 break;
4783         }
4784         return true;
4785     }
4786     return false;
4787 }
4788 #endif
4789 
4790 #ifdef ENABLE_BLE
4791 
4792 #ifdef ENABLE_LE_CENTRAL
4793 static void hci_le_scan_stop(void){
4794 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4795     if (hci_extended_advertising_supported()) {
4796             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
4797         } else
4798 #endif
4799     {
4800         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
4801     }
4802 }
4803 #endif
4804 
4805 #ifdef ENABLE_LE_PERIPHERAL
4806 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4807 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
4808     uint8_t  operation = 0;
4809     if (pos == 0){
4810         // first fragment or complete data
4811         operation |= 1;
4812     }
4813     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
4814         // last fragment or complete data
4815         operation |= 2;
4816     }
4817     return operation;
4818 }
4819 #endif
4820 #endif
4821 
4822 static bool hci_run_general_gap_le(void){
4823 
4824     // Phase 1: collect what to stop
4825 
4826     bool scanning_stop = false;
4827     bool connecting_stop = false;
4828     bool advertising_stop = false;
4829 
4830 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4831     le_advertising_set_t * advertising_stop_set = NULL;
4832     bool periodic_stop = false;
4833 #endif
4834 
4835 #ifndef ENABLE_LE_CENTRAL
4836     UNUSED(scanning_stop);
4837     UNUSED(connecting_stop);
4838 #endif
4839 #ifndef ENABLE_LE_PERIPHERAL
4840     UNUSED(advertising_stop);
4841 #endif
4842 
4843     // check if own address changes
4844     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
4845 
4846     // check if whitelist needs modification
4847     bool whitelist_modification_pending = false;
4848     btstack_linked_list_iterator_t lit;
4849     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4850     while (btstack_linked_list_iterator_has_next(&lit)){
4851         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4852         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
4853             whitelist_modification_pending = true;
4854             break;
4855         }
4856     }
4857     // check if resolving list needs modification
4858     bool resolving_list_modification_pending = false;
4859 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4860 
4861     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
4862 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
4863         resolving_list_modification_pending = true;
4864     }
4865 #endif
4866 
4867 #ifdef ENABLE_LE_CENTRAL
4868     // scanning control
4869     if (hci_stack->le_scanning_active) {
4870         // stop if:
4871         // - parameter change required
4872         // - it's disabled
4873         // - whitelist change required but used for scanning
4874         // - resolving list modified
4875         // - own address changes
4876         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
4877         if ((hci_stack->le_scanning_param_update) ||
4878             !hci_stack->le_scanning_enabled ||
4879             (scanning_uses_whitelist && whitelist_modification_pending) ||
4880             resolving_list_modification_pending ||
4881             random_address_change){
4882 
4883             scanning_stop = true;
4884         }
4885     }
4886 #endif
4887 
4888 #ifdef ENABLE_LE_CENTRAL
4889     // connecting control
4890     bool connecting_with_whitelist;
4891     switch (hci_stack->le_connecting_state){
4892         case LE_CONNECTING_DIRECT:
4893         case LE_CONNECTING_WHITELIST:
4894             // stop connecting if:
4895             // - connecting uses white and whitelist modification pending
4896             // - if it got disabled
4897             // - resolving list modified
4898             // - own address changes
4899             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
4900             if ((connecting_with_whitelist && whitelist_modification_pending) ||
4901                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
4902                 resolving_list_modification_pending ||
4903                 random_address_change) {
4904 
4905                 connecting_stop = true;
4906             }
4907             break;
4908         default:
4909             break;
4910     }
4911 #endif
4912 
4913 #ifdef ENABLE_LE_PERIPHERAL
4914     // le advertisement control
4915     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
4916         // stop if:
4917         // - parameter change required
4918         // - random address used in advertising and changes
4919         // - it's disabled
4920         // - whitelist change required but used for advertisement filter policy
4921         // - resolving list modified
4922         // - own address changes
4923         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
4924         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
4925         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
4926         if (advertising_change ||
4927             (advertising_uses_random_address && random_address_change) ||
4928             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
4929             (advertising_uses_whitelist && whitelist_modification_pending) ||
4930             resolving_list_modification_pending ||
4931             random_address_change) {
4932 
4933             advertising_stop = true;
4934         }
4935     }
4936 
4937 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4938     if (hci_extended_advertising_supported() && (advertising_stop == false)){
4939         btstack_linked_list_iterator_t it;
4940         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4941         while (btstack_linked_list_iterator_has_next(&it)){
4942             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4943             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
4944                 // stop if:
4945                 // - parameter change required
4946                 // - random address used in connectable advertising and changes
4947                 // - it's disabled
4948                 // - whitelist change required but used for advertisement filter policy
4949                 // - resolving list modified
4950                 // - own address changes
4951                 // - advertisement set will be removed
4952                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
4953                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
4954                 bool advertising_uses_random_address =
4955                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
4956                         advertising_connectable;
4957                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
4958                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
4959                 bool advertising_set_random_address_change =
4960                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
4961                 bool advertising_set_will_be_removed =
4962                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
4963                 if (advertising_parameter_change ||
4964                     (advertising_uses_random_address && advertising_set_random_address_change) ||
4965                     (advertising_enabled == false) ||
4966                     (advertising_uses_whitelist && whitelist_modification_pending) ||
4967                     resolving_list_modification_pending ||
4968                     advertising_set_will_be_removed) {
4969 
4970                     advertising_stop = true;
4971                     advertising_stop_set = advertising_set;
4972                     break;
4973                 }
4974             }
4975             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
4976                 // stop if:
4977                 // - it's disabled
4978                 // - parameter change required
4979                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
4980                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
4981                 if ((periodic_enabled == false) || periodic_parameter_change){
4982                     periodic_stop = true;
4983                     advertising_stop_set = advertising_set;
4984                 }
4985             }
4986         }
4987     }
4988 #endif
4989 
4990 #endif
4991 
4992 
4993     // Phase 2: stop everything that should be off during modifications
4994 
4995 #ifdef ENABLE_LE_CENTRAL
4996     if (scanning_stop){
4997         hci_stack->le_scanning_active = false;
4998         hci_le_scan_stop();
4999         return true;
5000     }
5001 #endif
5002 
5003 #ifdef ENABLE_LE_CENTRAL
5004     if (connecting_stop){
5005         hci_send_cmd(&hci_le_create_connection_cancel);
5006         return true;
5007     }
5008 #endif
5009 
5010 #ifdef ENABLE_LE_PERIPHERAL
5011     if (advertising_stop){
5012 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5013         if (hci_extended_advertising_supported()) {
5014             uint8_t advertising_stop_handle;
5015             if (advertising_stop_set != NULL){
5016                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5017                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5018             } else {
5019                 advertising_stop_handle = 0;
5020                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5021             }
5022             const uint8_t advertising_handles[] = { advertising_stop_handle };
5023             const uint16_t durations[] = { 0 };
5024             const uint16_t max_events[] = { 0 };
5025             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5026         } else
5027 #endif
5028         {
5029             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5030             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5031         }
5032         return true;
5033     }
5034 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5035     if (periodic_stop){
5036         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5037         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
5038         return true;
5039     }
5040 #endif
5041 #endif
5042 
5043     // Phase 3: modify
5044 
5045     if (random_address_change){
5046         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5047 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5048         if (hci_extended_advertising_supported()) {
5049             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5050         }
5051 #endif
5052         {
5053             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5054         }
5055         return true;
5056     }
5057 
5058 #ifdef ENABLE_LE_CENTRAL
5059     if (hci_stack->le_scanning_param_update){
5060         hci_stack->le_scanning_param_update = false;
5061 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5062         if (hci_extended_advertising_supported()){
5063             // prepare arrays for all PHYs
5064             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
5065             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
5066             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
5067             uint8_t  scanning_phys     = 1;  // LE 1M PHY
5068             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
5069                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
5070         } else
5071 #endif
5072         {
5073             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5074                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
5075         }
5076         return true;
5077     }
5078 #endif
5079 
5080 #ifdef ENABLE_LE_PERIPHERAL
5081     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
5082         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5083         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5084 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5085         if (hci_extended_advertising_supported()){
5086             // map advertisment type to advertising event properties
5087             uint16_t adv_event_properties = 0;
5088             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5089             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5090                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5091             }
5092             hci_stack->le_advertising_set_in_current_command = 0;
5093             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5094                          0,
5095                          adv_event_properties,
5096                          hci_stack->le_advertisements_interval_min,
5097                          hci_stack->le_advertisements_interval_max,
5098                          hci_stack->le_advertisements_channel_map,
5099                          hci_stack->le_advertisements_own_addr_type,
5100                          hci_stack->le_advertisements_direct_address_type,
5101                          hci_stack->le_advertisements_direct_address,
5102                          hci_stack->le_advertisements_filter_policy,
5103                          0x7f,  // tx power: no preference
5104                          0x01,  // primary adv phy: LE 1M
5105                          0,     // secondary adv max skip
5106                          0,     // secondary adv phy
5107                          0,     // adv sid
5108                          0      // scan request notification
5109                          );
5110         }
5111 #endif
5112         {
5113             hci_send_cmd(&hci_le_set_advertising_parameters,
5114                          hci_stack->le_advertisements_interval_min,
5115                          hci_stack->le_advertisements_interval_max,
5116                          hci_stack->le_advertisements_type,
5117                          hci_stack->le_advertisements_own_addr_type,
5118                          hci_stack->le_advertisements_direct_address_type,
5119                          hci_stack->le_advertisements_direct_address,
5120                          hci_stack->le_advertisements_channel_map,
5121                          hci_stack->le_advertisements_filter_policy);
5122         }
5123         return true;
5124     }
5125 
5126     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
5127         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5128         uint8_t adv_data_clean[31];
5129         memset(adv_data_clean, 0, sizeof(adv_data_clean));
5130         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
5131                      hci_stack->le_advertisements_data_len);
5132         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
5133 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5134         if (hci_extended_advertising_supported()){
5135             hci_stack->le_advertising_set_in_current_command = 0;
5136             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
5137         } else
5138 #endif
5139         {
5140             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
5141         }
5142         return true;
5143     }
5144 
5145     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
5146         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5147         uint8_t scan_data_clean[31];
5148         memset(scan_data_clean, 0, sizeof(scan_data_clean));
5149         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
5150                      hci_stack->le_scan_response_data_len);
5151         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
5152 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5153         if (hci_extended_advertising_supported()){
5154             hci_stack->le_advertising_set_in_current_command = 0;
5155             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
5156         } else
5157 #endif
5158         {
5159             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
5160         }
5161         return true;
5162     }
5163 
5164 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5165     if (hci_extended_advertising_supported()) {
5166         btstack_linked_list_iterator_t it;
5167         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5168         while (btstack_linked_list_iterator_has_next(&it)){
5169             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5170             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
5171                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
5172                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5173                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
5174                 return true;
5175             }
5176             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
5177                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5178                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
5179                 return true;
5180             }
5181             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
5182                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5183                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5184                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5185                              advertising_set->advertising_handle,
5186                              advertising_set->extended_params.advertising_event_properties,
5187                              advertising_set->extended_params.primary_advertising_interval_min,
5188                              advertising_set->extended_params.primary_advertising_interval_max,
5189                              advertising_set->extended_params.primary_advertising_channel_map,
5190                              advertising_set->extended_params.own_address_type,
5191                              advertising_set->extended_params.peer_address_type,
5192                              advertising_set->extended_params.peer_address,
5193                              advertising_set->extended_params.advertising_filter_policy,
5194                              advertising_set->extended_params.advertising_tx_power,
5195                              advertising_set->extended_params.primary_advertising_phy,
5196                              advertising_set->extended_params.secondary_advertising_max_skip,
5197                              advertising_set->extended_params.secondary_advertising_phy,
5198                              advertising_set->extended_params.advertising_sid,
5199                              advertising_set->extended_params.scan_request_notification_enable
5200                 );
5201                 return true;
5202             }
5203             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
5204                 uint16_t pos = advertising_set->adv_data_pos;
5205                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
5206                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5207                 if ((operation & 0x02) != 0){
5208                     // last fragment or complete data
5209                     operation |= 2;
5210                     advertising_set->adv_data_pos = 0;
5211                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5212                 } else {
5213                     advertising_set->adv_data_pos += data_to_upload;
5214                 }
5215                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5216                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
5217                 return true;
5218             }
5219             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
5220                 uint16_t pos = advertising_set->scan_data_pos;
5221                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
5222                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5223                 if ((operation & 0x02) != 0){
5224                     advertising_set->scan_data_pos = 0;
5225                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5226                 } else {
5227                     advertising_set->scan_data_pos += data_to_upload;
5228                 }
5229                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5230                 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
5231                 return true;
5232             }
5233             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
5234                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
5235                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5236                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
5237                              advertising_set->advertising_handle,
5238                              advertising_set->periodic_params.periodic_advertising_interval_min,
5239                              advertising_set->periodic_params.periodic_advertising_interval_max,
5240                              advertising_set->periodic_params.periodic_advertising_properties);
5241                 return true;
5242             }
5243             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
5244                 uint16_t pos = advertising_set->periodic_data_pos;
5245                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
5246                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5247                 if ((operation & 0x02) != 0){
5248                     // last fragment or complete data
5249                     operation |= 2;
5250                     advertising_set->periodic_data_pos = 0;
5251                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
5252                 } else {
5253                     advertising_set->periodic_data_pos += data_to_upload;
5254                 }
5255                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5256                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
5257                 return true;
5258             }
5259         }
5260     }
5261 #endif
5262 
5263 
5264 #endif
5265 
5266 
5267 #ifdef ENABLE_LE_CENTRAL
5268     // if connect with whitelist was active and is not cancelled yet, wait until next time
5269     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
5270 #endif
5271 
5272     // LE Whitelist Management
5273     if (whitelist_modification_pending){
5274         // add/remove entries
5275         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5276         while (btstack_linked_list_iterator_has_next(&lit)){
5277             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5278 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5279 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5280 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
5281 				return true;
5282 			}
5283             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
5284 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
5285                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
5286                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
5287                 return true;
5288             }
5289             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
5290 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5291 				btstack_memory_whitelist_entry_free(entry);
5292             }
5293         }
5294     }
5295 
5296 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5297     // LE Resolving List Management
5298     if (resolving_list_supported) {
5299 		uint16_t i;
5300 		switch (hci_stack->le_resolving_list_state) {
5301 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
5302 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
5303 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
5304 				return true;
5305 			case LE_RESOLVING_LIST_READ_SIZE:
5306 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
5307 				hci_send_cmd(&hci_le_read_resolving_list_size);
5308 				return true;
5309 			case LE_RESOLVING_LIST_SEND_CLEAR:
5310 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
5311 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
5312 							  sizeof(hci_stack->le_resolving_list_add_entries));
5313 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
5314 							  sizeof(hci_stack->le_resolving_list_remove_entries));
5315 				hci_send_cmd(&hci_le_clear_resolving_list);
5316 				return true;
5317 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
5318 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5319 					uint8_t offset = i >> 3;
5320 					uint8_t mask = 1 << (i & 7);
5321 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
5322 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
5323 					bd_addr_t peer_identity_addreses;
5324 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5325 					sm_key_t peer_irk;
5326 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5327 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5328 
5329 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
5330 					// trigger whitelist entry 'update' (work around for controller bug)
5331 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5332 					while (btstack_linked_list_iterator_has_next(&lit)) {
5333 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
5334 						if (entry->address_type != peer_identity_addr_type) continue;
5335 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
5336 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
5337 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
5338 					}
5339 #endif
5340 
5341 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
5342 								 peer_identity_addreses);
5343 					return true;
5344 				}
5345 
5346 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
5347 
5348 				/* fall through */
5349 
5350 			case LE_RESOLVING_LIST_ADD_ENTRIES:
5351 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5352 					uint8_t offset = i >> 3;
5353 					uint8_t mask = 1 << (i & 7);
5354 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
5355 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
5356 					bd_addr_t peer_identity_addreses;
5357 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5358 					sm_key_t peer_irk;
5359 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5360 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5361 					const uint8_t *local_irk = gap_get_persistent_irk();
5362 					// command uses format specifier 'P' that stores 16-byte value without flip
5363 					uint8_t local_irk_flipped[16];
5364 					uint8_t peer_irk_flipped[16];
5365 					reverse_128(local_irk, local_irk_flipped);
5366 					reverse_128(peer_irk, peer_irk_flipped);
5367 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
5368 								 peer_irk_flipped, local_irk_flipped);
5369 					return true;
5370 				}
5371 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5372 				break;
5373 
5374 			default:
5375 				break;
5376 		}
5377 	}
5378     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5379 #endif
5380 
5381     // post-pone all actions until stack is fully working
5382     if (hci_stack->state != HCI_STATE_WORKING) return false;
5383 
5384     // advertisements, active scanning, and creating connections requires random address to be set if using private address
5385     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
5386 
5387     // Phase 4: restore state
5388 
5389 #ifdef ENABLE_LE_CENTRAL
5390     // re-start scanning
5391     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
5392         hci_stack->le_scanning_active = true;
5393 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5394         if (hci_extended_advertising_supported()){
5395             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0);
5396         } else
5397 #endif
5398         {
5399             hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
5400         }
5401         return true;
5402     }
5403 #endif
5404 
5405 #ifdef ENABLE_LE_CENTRAL
5406     // re-start connecting
5407     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
5408         bd_addr_t null_addr;
5409         memset(null_addr, 0, 6);
5410         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
5411         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
5412         hci_send_cmd(&hci_le_create_connection,
5413                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
5414                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
5415                      1,         // use whitelist
5416                      0,         // peer address type
5417                      null_addr, // peer bd addr
5418                      hci_stack->le_connection_own_addr_type,   // our addr type:
5419                      hci_stack->le_connection_interval_min,    // conn interval min
5420                      hci_stack->le_connection_interval_max,    // conn interval max
5421                      hci_stack->le_connection_latency,         // conn latency
5422                      hci_stack->le_supervision_timeout,        // conn latency
5423                      hci_stack->le_minimum_ce_length,          // min ce length
5424                      hci_stack->le_maximum_ce_length           // max ce length
5425         );
5426         return true;
5427     }
5428 #endif
5429 
5430 #ifdef ENABLE_LE_PERIPHERAL
5431     // re-start advertising
5432     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
5433         // check if advertisements should be enabled given
5434         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
5435         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
5436 
5437 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5438         if (hci_extended_advertising_supported()){
5439             const uint8_t advertising_handles[] = { 0 };
5440             const uint16_t durations[] = { 0 };
5441             const uint16_t max_events[] = { 0 };
5442             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
5443         } else
5444 #endif
5445         {
5446             hci_send_cmd(&hci_le_set_advertise_enable, 1);
5447         }
5448         return true;
5449     }
5450 
5451 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5452     if (hci_extended_advertising_supported()) {
5453         btstack_linked_list_iterator_t it;
5454         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5455         while (btstack_linked_list_iterator_has_next(&it)) {
5456             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
5457             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
5458                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
5459                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
5460                 const uint16_t durations[] = { advertising_set->enable_timeout };
5461                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
5462                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
5463                 return true;
5464             }
5465             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
5466                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5467                 uint8_t enable = 1;
5468                 if (advertising_set->periodic_include_adi){
5469                     enable |= 2;
5470                 }
5471                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
5472                 return true;
5473             }
5474         }
5475     }
5476 #endif
5477 #endif
5478 
5479     return false;
5480 }
5481 #endif
5482 
5483 static bool hci_run_general_pending_commands(void){
5484     btstack_linked_item_t * it;
5485     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5486         hci_connection_t * connection = (hci_connection_t *) it;
5487 
5488         switch(connection->state){
5489             case SEND_CREATE_CONNECTION:
5490                 switch(connection->address_type){
5491 #ifdef ENABLE_CLASSIC
5492                     case BD_ADDR_TYPE_ACL:
5493                         log_info("sending hci_create_connection");
5494                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
5495                         break;
5496 #endif
5497                     default:
5498 #ifdef ENABLE_BLE
5499 #ifdef ENABLE_LE_CENTRAL
5500                         log_info("sending hci_le_create_connection");
5501                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
5502                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
5503                         hci_send_cmd(&hci_le_create_connection,
5504                                      hci_stack->le_connection_scan_interval,    // conn scan interval
5505                                      hci_stack->le_connection_scan_window,      // conn scan windows
5506                                      0,         // don't use whitelist
5507                                      connection->address_type, // peer address type
5508                                      connection->address,      // peer bd addr
5509                                      hci_stack->le_connection_own_addr_type,   // our addr type:
5510                                      hci_stack->le_connection_interval_min,    // conn interval min
5511                                      hci_stack->le_connection_interval_max,    // conn interval max
5512                                      hci_stack->le_connection_latency,         // conn latency
5513                                      hci_stack->le_supervision_timeout,        // conn latency
5514                                      hci_stack->le_minimum_ce_length,          // min ce length
5515                                      hci_stack->le_maximum_ce_length          // max ce length
5516                         );
5517                         connection->state = SENT_CREATE_CONNECTION;
5518 #endif
5519 #endif
5520                         break;
5521                 }
5522                 return true;
5523 
5524 #ifdef ENABLE_CLASSIC
5525             case RECEIVED_CONNECTION_REQUEST:
5526                 connection->role  = HCI_ROLE_SLAVE;
5527                 if (connection->address_type == BD_ADDR_TYPE_ACL){
5528                     log_info("sending hci_accept_connection_request");
5529                     connection->state = ACCEPTED_CONNECTION_REQUEST;
5530                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
5531                     return true;
5532                 }
5533                 break;
5534 #endif
5535 
5536 #ifdef ENABLE_BLE
5537 #ifdef ENABLE_LE_CENTRAL
5538             case SEND_CANCEL_CONNECTION:
5539                 connection->state = SENT_CANCEL_CONNECTION;
5540                 hci_send_cmd(&hci_le_create_connection_cancel);
5541                 return true;
5542 #endif
5543 #endif
5544             case SEND_DISCONNECT:
5545                 connection->state = SENT_DISCONNECT;
5546                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5547                 return true;
5548 
5549             default:
5550                 break;
5551         }
5552 
5553         // no further commands if connection is about to get shut down
5554         if (connection->state == SENT_DISCONNECT) continue;
5555 
5556 #ifdef ENABLE_CLASSIC
5557 
5558         // Handling link key request requires remote supported features
5559         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
5560             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
5561             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
5562 
5563             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
5564             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
5565             if (have_link_key && security_level_sufficient){
5566                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
5567             } else {
5568                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
5569             }
5570             return true;
5571         }
5572 
5573         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
5574             log_info("denying to pin request");
5575             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
5576             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
5577             return true;
5578         }
5579 
5580         // security assessment requires remote features
5581         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
5582             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
5583             hci_ssp_assess_security_on_io_cap_request(connection);
5584             // 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
5585         }
5586 
5587         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
5588             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
5589             // set authentication requirements:
5590             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
5591             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
5592             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
5593             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
5594                 authreq |= 1;
5595             }
5596             bool bonding = hci_stack->bondable;
5597             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
5598                 // if we have received IO Cap Response, we're in responder role
5599                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
5600                 if (bonding && !remote_bonding){
5601                     log_info("Remote not bonding, dropping local flag");
5602                     bonding = false;
5603                 }
5604             }
5605             if (bonding){
5606                 if (connection->bonding_flags & BONDING_DEDICATED){
5607                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
5608                 } else {
5609                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
5610                 }
5611             }
5612             uint8_t have_oob_data = 0;
5613 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5614             if (connection->classic_oob_c_192 != NULL){
5615                     have_oob_data |= 1;
5616             }
5617             if (connection->classic_oob_c_256 != NULL){
5618                 have_oob_data |= 2;
5619             }
5620 #endif
5621             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
5622             return true;
5623         }
5624 
5625         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
5626             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
5627             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
5628             return true;
5629         }
5630 
5631 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5632         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
5633             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
5634             const uint8_t zero[16] = { 0 };
5635             const uint8_t * r_192 = zero;
5636             const uint8_t * c_192 = zero;
5637             const uint8_t * r_256 = zero;
5638             const uint8_t * c_256 = zero;
5639             // verify P-256 OOB
5640             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
5641                 c_256 = connection->classic_oob_c_256;
5642                 if (connection->classic_oob_r_256 != NULL) {
5643                     r_256 = connection->classic_oob_r_256;
5644                 }
5645             }
5646             // verify P-192 OOB
5647             if ((connection->classic_oob_c_192 != NULL)) {
5648                 c_192 = connection->classic_oob_c_192;
5649                 if (connection->classic_oob_r_192 != NULL) {
5650                     r_192 = connection->classic_oob_r_192;
5651                 }
5652             }
5653 
5654             // assess security
5655             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
5656             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
5657             if (need_level_4 && !can_reach_level_4){
5658                 log_info("Level 4 required, but not possible -> abort");
5659                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
5660                 // send oob negative reply
5661                 c_256 = NULL;
5662                 c_192 = NULL;
5663             }
5664 
5665             // Reply
5666             if (c_256 != zero) {
5667                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
5668             } else if (c_192 != zero){
5669                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
5670             } else {
5671                 hci_stack->classic_oob_con_handle = connection->con_handle;
5672                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
5673             }
5674             return true;
5675         }
5676 #endif
5677 
5678         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
5679             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
5680             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
5681             return true;
5682         }
5683 
5684         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
5685             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
5686             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
5687             return true;
5688         }
5689 
5690         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
5691             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
5692             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
5693             return true;
5694         }
5695 
5696         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
5697             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
5698             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
5699             connection->state = SENT_DISCONNECT;
5700             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5701             return true;
5702         }
5703 
5704         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
5705             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
5706             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
5707             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
5708             return true;
5709         }
5710 
5711         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
5712             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
5713             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
5714             return true;
5715         }
5716 
5717         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
5718             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
5719             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
5720             return true;
5721         }
5722 
5723         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
5724             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
5725             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
5726             return true;
5727         }
5728 
5729         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
5730             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
5731             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
5732             return true;
5733         }
5734 
5735         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
5736             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
5737             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
5738             return true;
5739         }
5740 #endif
5741 
5742         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
5743             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
5744 #ifdef ENABLE_CLASSIC
5745             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
5746 #endif
5747             if (connection->state != SENT_DISCONNECT){
5748                 connection->state = SENT_DISCONNECT;
5749                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
5750                 return true;
5751             }
5752         }
5753 
5754 #ifdef ENABLE_CLASSIC
5755         uint16_t sniff_min_interval;
5756         switch (connection->sniff_min_interval){
5757             case 0:
5758                 break;
5759             case 0xffff:
5760                 connection->sniff_min_interval = 0;
5761                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
5762                 return true;
5763             default:
5764                 sniff_min_interval = connection->sniff_min_interval;
5765                 connection->sniff_min_interval = 0;
5766                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
5767                 return true;
5768         }
5769 
5770         if (connection->sniff_subrating_max_latency != 0xffff){
5771             uint16_t max_latency = connection->sniff_subrating_max_latency;
5772             connection->sniff_subrating_max_latency = 0;
5773             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
5774             return true;
5775         }
5776 
5777         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
5778             uint8_t service_type = (uint8_t) connection->qos_service_type;
5779             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
5780             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);
5781             return true;
5782         }
5783 
5784         if (connection->request_role != HCI_ROLE_INVALID){
5785             hci_role_t role = connection->request_role;
5786             connection->request_role = HCI_ROLE_INVALID;
5787             hci_send_cmd(&hci_switch_role_command, connection->address, role);
5788             return true;
5789         }
5790 #endif
5791 
5792         if (connection->gap_connection_tasks != 0){
5793 #ifdef ENABLE_CLASSIC
5794             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
5795                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
5796                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
5797                 return true;
5798             }
5799             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
5800                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
5801                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
5802                 return true;
5803             }
5804 #endif
5805             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
5806                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
5807                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
5808                 return true;
5809             }
5810         }
5811 
5812 #ifdef ENABLE_BLE
5813         switch (connection->le_con_parameter_update_state){
5814             // response to L2CAP CON PARAMETER UPDATE REQUEST
5815             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
5816                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5817                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
5818                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
5819                              0x0000, 0xffff);
5820                 return true;
5821             case CON_PARAMETER_UPDATE_REPLY:
5822                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5823                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
5824                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
5825                              0x0000, 0xffff);
5826                 return true;
5827             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
5828                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5829                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
5830                 return true;
5831             default:
5832                 break;
5833         }
5834         if (connection->le_phy_update_all_phys != 0xffu){
5835             uint8_t all_phys = connection->le_phy_update_all_phys;
5836             connection->le_phy_update_all_phys = 0xff;
5837             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);
5838             return true;
5839         }
5840 #endif
5841     }
5842     return false;
5843 }
5844 
5845 static void hci_run(void){
5846 
5847     // stack state sub statemachines
5848     // halting needs to be called even if we cannot send command packet now
5849     switch (hci_stack->state) {
5850         case HCI_STATE_INITIALIZING:
5851             hci_initializing_run();
5852             break;
5853         case HCI_STATE_HALTING:
5854             hci_halting_run();
5855             break;
5856         case HCI_STATE_FALLING_ASLEEP:
5857             hci_falling_asleep_run();
5858             break;
5859         default:
5860             break;
5861     }
5862 
5863     bool done;
5864 
5865     // send continuation fragments first, as they block the prepared packet buffer
5866     done = hci_run_acl_fragments();
5867     if (done) return;
5868 
5869 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5870     // send host num completed packets next as they don't require num_cmd_packets > 0
5871     if (!hci_can_send_comand_packet_transport()) return;
5872     if (hci_stack->host_completed_packets){
5873         hci_host_num_completed_packets();
5874         return;
5875     }
5876 #endif
5877 
5878     if (!hci_can_send_command_packet_now()) return;
5879 
5880     // global/non-connection oriented commands
5881 
5882 
5883 #ifdef ENABLE_CLASSIC
5884     // general gap classic
5885     done = hci_run_general_gap_classic();
5886     if (done) return;
5887 #endif
5888 
5889 #ifdef ENABLE_BLE
5890     // general gap le
5891     done = hci_run_general_gap_le();
5892     if (done) return;
5893 #endif
5894 
5895     // send pending HCI commands
5896     hci_run_general_pending_commands();
5897 }
5898 
5899 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
5900     // house-keeping
5901 
5902 #ifdef ENABLE_CLASSIC
5903     bd_addr_t addr;
5904     hci_connection_t * conn;
5905 #endif
5906 #ifdef ENABLE_LE_CENTRAL
5907     uint8_t initiator_filter_policy;
5908 #endif
5909 
5910     uint16_t opcode = little_endian_read_16(packet, 0);
5911     switch (opcode) {
5912         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
5913             hci_stack->loopback_mode = packet[3];
5914             break;
5915 
5916 #ifdef ENABLE_CLASSIC
5917         case HCI_OPCODE_HCI_CREATE_CONNECTION:
5918             reverse_bd_addr(&packet[3], addr);
5919             log_info("Create_connection to %s", bd_addr_to_str(addr));
5920 
5921             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
5922             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
5923                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
5924                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
5925             }
5926 
5927             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5928             if (!conn) {
5929                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5930                 if (!conn) {
5931                     // notify client that alloc failed
5932                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5933                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
5934                 }
5935                 conn->state = SEND_CREATE_CONNECTION;
5936                 conn->role  = HCI_ROLE_MASTER;
5937             }
5938 
5939             conn->con_handle = HCI_CON_HANDLE_INVALID;
5940             conn->role = HCI_ROLE_INVALID;
5941 
5942             log_info("conn state %u", conn->state);
5943             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
5944             switch (conn->state) {
5945                 // if connection active exists
5946                 case OPEN:
5947                     // and OPEN, emit connection complete command
5948                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
5949                     // packet not sent to controller
5950                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5951                 case RECEIVED_DISCONNECTION_COMPLETE:
5952                     // create connection triggered in disconnect complete event, let's do it now
5953                     break;
5954                 case SEND_CREATE_CONNECTION:
5955 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5956                     if (hci_classic_operation_active()){
5957                         return ERROR_CODE_SUCCESS;
5958                     }
5959 #endif
5960                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
5961                     break;
5962                 default:
5963                     // otherwise, just ignore as it is already in the open process
5964                     // packet not sent to controller
5965                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5966             }
5967             conn->state = SENT_CREATE_CONNECTION;
5968 
5969             // track outgoing connection
5970             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
5971             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
5972             break;
5973 
5974 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
5975         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
5976             // setup_synchronous_connection? Voice setting at offset 22
5977             // TODO: compare to current setting if sco connection already active
5978             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
5979             break;
5980         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
5981             // accept_synchronous_connection? Voice setting at offset 18
5982             // TODO: compare to current setting if sco connection already active
5983             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
5984             // track outgoing connection
5985             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
5986             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
5987             break;
5988 #endif
5989 #endif
5990 
5991 #ifdef ENABLE_BLE
5992 #ifdef ENABLE_LE_CENTRAL
5993         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
5994             // white list used?
5995             initiator_filter_policy = packet[7];
5996             switch (initiator_filter_policy) {
5997                 case 0:
5998                     // whitelist not used
5999                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
6000                     break;
6001                 case 1:
6002                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
6003                     break;
6004                 default:
6005                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
6006                     break;
6007             }
6008             // track outgoing connection
6009             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
6010             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
6011             break;
6012         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
6013             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
6014             break;
6015 #endif
6016 #endif
6017         default:
6018             break;
6019     }
6020 
6021     hci_stack->num_cmd_packets--;
6022 
6023     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
6024     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
6025     if (err != 0){
6026         return ERROR_CODE_HARDWARE_FAILURE;
6027     }
6028     return ERROR_CODE_SUCCESS;
6029 }
6030 
6031 // disconnect because of security block
6032 void hci_disconnect_security_block(hci_con_handle_t con_handle){
6033     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6034     if (!connection) return;
6035     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
6036 }
6037 
6038 
6039 // Configure Secure Simple Pairing
6040 
6041 #ifdef ENABLE_CLASSIC
6042 
6043 // enable will enable SSP during init
6044 void gap_ssp_set_enable(int enable){
6045     hci_stack->ssp_enable = enable;
6046 }
6047 
6048 static int hci_local_ssp_activated(void){
6049     return gap_ssp_supported() && hci_stack->ssp_enable;
6050 }
6051 
6052 // if set, BTstack will respond to io capability request using authentication requirement
6053 void gap_ssp_set_io_capability(int io_capability){
6054     hci_stack->ssp_io_capability = io_capability;
6055 }
6056 void gap_ssp_set_authentication_requirement(int authentication_requirement){
6057     hci_stack->ssp_authentication_requirement = authentication_requirement;
6058 }
6059 
6060 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
6061 void gap_ssp_set_auto_accept(int auto_accept){
6062     hci_stack->ssp_auto_accept = auto_accept;
6063 }
6064 
6065 void gap_secure_connections_enable(bool enable){
6066     hci_stack->secure_connections_enable = enable;
6067 }
6068 bool gap_secure_connections_active(void){
6069     return hci_stack->secure_connections_active;
6070 }
6071 
6072 #endif
6073 
6074 // va_list part of hci_send_cmd
6075 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
6076     if (!hci_can_send_command_packet_now()){
6077         log_error("hci_send_cmd called but cannot send packet now");
6078         return ERROR_CODE_COMMAND_DISALLOWED;
6079     }
6080 
6081     // for HCI INITIALIZATION
6082     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
6083     hci_stack->last_cmd_opcode = cmd->opcode;
6084 
6085     hci_reserve_packet_buffer();
6086     uint8_t * packet = hci_stack->hci_packet_buffer;
6087     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
6088     uint8_t status = hci_send_cmd_packet(packet, size);
6089 
6090     // release packet buffer on error or for synchronous transport implementations
6091     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
6092         hci_release_packet_buffer();
6093         hci_emit_transport_packet_sent();
6094     }
6095 
6096     return status;
6097 }
6098 
6099 /**
6100  * pre: numcmds >= 0 - it's allowed to send a command to the controller
6101  */
6102 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
6103     va_list argptr;
6104     va_start(argptr, cmd);
6105     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
6106     va_end(argptr);
6107     return status;
6108 }
6109 
6110 // Create various non-HCI events.
6111 // TODO: generalize, use table similar to hci_create_command
6112 
6113 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
6114     // dump packet
6115     if (dump) {
6116         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
6117     }
6118 
6119     // dispatch to all event handlers
6120     btstack_linked_list_iterator_t it;
6121     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
6122     while (btstack_linked_list_iterator_has_next(&it)){
6123         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
6124         entry->callback(HCI_EVENT_PACKET, 0, event, size);
6125     }
6126 }
6127 
6128 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
6129     if (!hci_stack->acl_packet_handler) return;
6130     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
6131 }
6132 
6133 #ifdef ENABLE_CLASSIC
6134 static void hci_notify_if_sco_can_send_now(void){
6135     // notify SCO sender if waiting
6136     if (!hci_stack->sco_waiting_for_can_send_now) return;
6137     if (hci_can_send_sco_packet_now()){
6138         hci_stack->sco_waiting_for_can_send_now = 0;
6139         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
6140         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
6141         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
6142     }
6143 }
6144 
6145 // parsing end emitting has been merged to reduce code size
6146 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
6147     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
6148 
6149     uint8_t * eir_data;
6150     ad_context_t context;
6151     const uint8_t * name;
6152     uint8_t         name_len;
6153 
6154     if (size < 3) return;
6155 
6156     int event_type = hci_event_packet_get_type(packet);
6157     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
6158     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
6159 
6160     switch (event_type){
6161         case HCI_EVENT_INQUIRY_RESULT:
6162         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6163             if (size != (3 + (num_responses * 14))) return;
6164             break;
6165         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6166             if (size != 257) return;
6167             if (num_responses != 1) return;
6168             break;
6169         default:
6170             return;
6171     }
6172 
6173     // event[1] is set at the end
6174     int i;
6175     for (i=0; i<num_responses;i++){
6176         memset(event, 0, sizeof(event));
6177         event[0] = GAP_EVENT_INQUIRY_RESULT;
6178         uint8_t event_size = 27;    // if name is not set by EIR
6179 
6180         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
6181         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
6182         (void)memcpy(&event[9],
6183                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
6184                      3); // class of device
6185         (void)memcpy(&event[12],
6186                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
6187                      2); // clock offset
6188 
6189         switch (event_type){
6190             case HCI_EVENT_INQUIRY_RESULT:
6191                 // 14,15,16,17 = 0, size 18
6192                 break;
6193             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6194                 event[14] = 1;
6195                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
6196                 // 16,17 = 0, size 18
6197                 break;
6198             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6199                 event[14] = 1;
6200                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
6201                 // EIR packets only contain a single inquiry response
6202                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
6203                 name = NULL;
6204                 // Iterate over EIR data
6205                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
6206                     uint8_t data_type    = ad_iterator_get_data_type(&context);
6207                     uint8_t data_size    = ad_iterator_get_data_len(&context);
6208                     const uint8_t * data = ad_iterator_get_data(&context);
6209                     // Prefer Complete Local Name over Shortened Local Name
6210                     switch (data_type){
6211                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
6212                             if (name) continue;
6213                             /* fall through */
6214                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
6215                             name = data;
6216                             name_len = data_size;
6217                             break;
6218                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
6219                             if (data_size != 8) break;
6220                             event[16] = 1;
6221                             memcpy(&event[17], data, 8);
6222                             break;
6223                         default:
6224                             break;
6225                     }
6226                 }
6227                 if (name){
6228                     event[25] = 1;
6229                     // truncate name if needed
6230                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
6231                     event[26] = len;
6232                     (void)memcpy(&event[27], name, len);
6233                     event_size += len;
6234                 }
6235                 break;
6236             default:
6237                 return;
6238         }
6239         event[1] = event_size - 2;
6240         hci_emit_event(event, event_size, 1);
6241     }
6242 }
6243 #endif
6244 
6245 void hci_emit_state(void){
6246     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
6247     uint8_t event[3];
6248     event[0] = BTSTACK_EVENT_STATE;
6249     event[1] = sizeof(event) - 2u;
6250     event[2] = hci_stack->state;
6251     hci_emit_event(event, sizeof(event), 1);
6252 }
6253 
6254 #ifdef ENABLE_CLASSIC
6255 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
6256     uint8_t event[13];
6257     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
6258     event[1] = sizeof(event) - 2;
6259     event[2] = status;
6260     little_endian_store_16(event, 3, con_handle);
6261     reverse_bd_addr(address, &event[5]);
6262     event[11] = 1; // ACL connection
6263     event[12] = 0; // encryption disabled
6264     hci_emit_event(event, sizeof(event), 1);
6265 }
6266 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
6267     if (disable_l2cap_timeouts) return;
6268     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
6269     uint8_t event[4];
6270     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
6271     event[1] = sizeof(event) - 2;
6272     little_endian_store_16(event, 2, conn->con_handle);
6273     hci_emit_event(event, sizeof(event), 1);
6274 }
6275 #endif
6276 
6277 #ifdef ENABLE_BLE
6278 #ifdef ENABLE_LE_CENTRAL
6279 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){
6280     uint8_t event[21];
6281     event[0] = HCI_EVENT_LE_META;
6282     event[1] = sizeof(event) - 2u;
6283     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
6284     event[3] = status;
6285     little_endian_store_16(event, 4, con_handle);
6286     event[6] = 0; // TODO: role
6287     event[7] = address_type;
6288     reverse_bd_addr(address, &event[8]);
6289     little_endian_store_16(event, 14, 0); // interval
6290     little_endian_store_16(event, 16, 0); // latency
6291     little_endian_store_16(event, 18, 0); // supervision timeout
6292     event[20] = 0; // master clock accuracy
6293     hci_emit_event(event, sizeof(event), 1);
6294 }
6295 #endif
6296 #endif
6297 
6298 static void hci_emit_transport_packet_sent(void){
6299     // notify upper stack that it might be possible to send again
6300     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
6301     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
6302 }
6303 
6304 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
6305     uint8_t event[6];
6306     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
6307     event[1] = sizeof(event) - 2u;
6308     event[2] = 0; // status = OK
6309     little_endian_store_16(event, 3, con_handle);
6310     event[5] = reason;
6311     hci_emit_event(event, sizeof(event), 1);
6312 }
6313 
6314 static void hci_emit_nr_connections_changed(void){
6315     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
6316     uint8_t event[3];
6317     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
6318     event[1] = sizeof(event) - 2u;
6319     event[2] = nr_hci_connections();
6320     hci_emit_event(event, sizeof(event), 1);
6321 }
6322 
6323 static void hci_emit_hci_open_failed(void){
6324     log_info("BTSTACK_EVENT_POWERON_FAILED");
6325     uint8_t event[2];
6326     event[0] = BTSTACK_EVENT_POWERON_FAILED;
6327     event[1] = sizeof(event) - 2u;
6328     hci_emit_event(event, sizeof(event), 1);
6329 }
6330 
6331 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
6332     log_info("hci_emit_dedicated_bonding_result %u ", status);
6333     uint8_t event[9];
6334     int pos = 0;
6335     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
6336     event[pos++] = sizeof(event) - 2u;
6337     event[pos++] = status;
6338     reverse_bd_addr(address, &event[pos]);
6339     hci_emit_event(event, sizeof(event), 1);
6340 }
6341 
6342 
6343 #ifdef ENABLE_CLASSIC
6344 
6345 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
6346     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
6347     uint8_t event[5];
6348     int pos = 0;
6349     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
6350     event[pos++] = sizeof(event) - 2;
6351     little_endian_store_16(event, 2, con_handle);
6352     pos += 2;
6353     event[pos++] = level;
6354     hci_emit_event(event, sizeof(event), 1);
6355 }
6356 
6357 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
6358     if (!connection) return LEVEL_0;
6359     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
6360     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
6361     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
6362     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
6363     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
6364     // LEVEL 4 always requires 128 bit encrytion key size
6365     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
6366         security_level = LEVEL_3;
6367     }
6368     return security_level;
6369 }
6370 
6371 static void hci_emit_discoverable_enabled(uint8_t enabled){
6372     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
6373     uint8_t event[3];
6374     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
6375     event[1] = sizeof(event) - 2;
6376     event[2] = enabled;
6377     hci_emit_event(event, sizeof(event), 1);
6378 }
6379 
6380 // query if remote side supports eSCO
6381 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
6382     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6383     if (!connection) return false;
6384     return (connection->remote_supported_features[0] & 1) != 0;
6385 }
6386 
6387 static bool hci_ssp_supported(hci_connection_t * connection){
6388     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
6389     return (connection->bonding_flags & mask) == mask;
6390 }
6391 
6392 // query if remote side supports SSP
6393 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
6394     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6395     if (!connection) return false;
6396     return hci_ssp_supported(connection) ? 1 : 0;
6397 }
6398 
6399 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
6400     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
6401 }
6402 
6403 /**
6404  * Check if remote supported features query has completed
6405  */
6406 bool hci_remote_features_available(hci_con_handle_t handle){
6407     hci_connection_t * connection = hci_connection_for_handle(handle);
6408     if (!connection) return false;
6409     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
6410 }
6411 
6412 /**
6413  * Trigger remote supported features query
6414  */
6415 
6416 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
6417     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
6418         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6419     }
6420 }
6421 
6422 void hci_remote_features_query(hci_con_handle_t con_handle){
6423     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6424     if (!connection) return;
6425     hci_trigger_remote_features_for_connection(connection);
6426     hci_run();
6427 }
6428 
6429 // GAP API
6430 /**
6431  * @bbrief enable/disable bonding. default is enabled
6432  * @praram enabled
6433  */
6434 void gap_set_bondable_mode(int enable){
6435     hci_stack->bondable = enable ? 1 : 0;
6436 }
6437 /**
6438  * @brief Get bondable mode.
6439  * @return 1 if bondable
6440  */
6441 int gap_get_bondable_mode(void){
6442     return hci_stack->bondable;
6443 }
6444 
6445 /**
6446  * @brief map link keys to security levels
6447  */
6448 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
6449     switch (link_key_type){
6450         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6451             return LEVEL_4;
6452         case COMBINATION_KEY:
6453         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
6454             return LEVEL_3;
6455         default:
6456             return LEVEL_2;
6457     }
6458 }
6459 
6460 /**
6461  * @brief map link keys to secure connection yes/no
6462  */
6463 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
6464     switch (link_key_type){
6465         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6466         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6467             return true;
6468         default:
6469             return false;
6470     }
6471 }
6472 
6473 /**
6474  * @brief map link keys to authenticated
6475  */
6476 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
6477     switch (link_key_type){
6478         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6479         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
6480             return true;
6481         default:
6482             return false;
6483     }
6484 }
6485 
6486 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
6487     log_info("gap_mitm_protection_required_for_security_level %u", level);
6488     return level > LEVEL_2;
6489 }
6490 
6491 /**
6492  * @brief get current security level
6493  */
6494 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
6495     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6496     if (!connection) return LEVEL_0;
6497     return gap_security_level_for_connection(connection);
6498 }
6499 
6500 /**
6501  * @brief request connection to device to
6502  * @result GAP_AUTHENTICATION_RESULT
6503  */
6504 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
6505     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6506     if (!connection){
6507         hci_emit_security_level(con_handle, LEVEL_0);
6508         return;
6509     }
6510 
6511     btstack_assert(hci_is_le_connection(connection) == false);
6512 
6513     // 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)
6514     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
6515     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
6516         requested_level = LEVEL_4;
6517     }
6518 
6519     gap_security_level_t current_level = gap_security_level(con_handle);
6520     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
6521         requested_level, connection->requested_security_level, current_level);
6522 
6523     // authentication active if authentication request was sent or planned level > 0
6524     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
6525     if (authentication_active){
6526         // authentication already active
6527         if (connection->requested_security_level < requested_level){
6528             // increase requested level as new level is higher
6529             // TODO: handle re-authentication when done
6530             connection->requested_security_level = requested_level;
6531         }
6532     } else {
6533         // no request active, notify if security sufficient
6534         if (requested_level <= current_level){
6535             hci_emit_security_level(con_handle, current_level);
6536             return;
6537         }
6538 
6539         // store request
6540         connection->requested_security_level = requested_level;
6541 
6542         // request remote features if not already active
6543         hci_remote_features_query(con_handle);
6544 
6545         // start to authenticate connection
6546         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
6547         hci_run();
6548     }
6549 }
6550 
6551 /**
6552  * @brief start dedicated bonding with device. disconnect after bonding
6553  * @param device
6554  * @param request MITM protection
6555  * @result GAP_DEDICATED_BONDING_COMPLETE
6556  */
6557 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
6558 
6559     // create connection state machine
6560     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
6561 
6562     if (!connection){
6563         return BTSTACK_MEMORY_ALLOC_FAILED;
6564     }
6565 
6566     // delete linkn key
6567     gap_drop_link_key_for_bd_addr(device);
6568 
6569     // configure LEVEL_2/3, dedicated bonding
6570     connection->state = SEND_CREATE_CONNECTION;
6571     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
6572     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
6573     connection->bonding_flags = BONDING_DEDICATED;
6574 
6575     // wait for GAP Security Result and send GAP Dedicated Bonding complete
6576 
6577     // handle: connnection failure (connection complete != ok)
6578     // handle: authentication failure
6579     // handle: disconnect on done
6580 
6581     hci_run();
6582 
6583     return 0;
6584 }
6585 
6586 void gap_set_local_name(const char * local_name){
6587     hci_stack->local_name = local_name;
6588     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
6589     // also update EIR if not set by user
6590     if (hci_stack->eir_data == NULL){
6591         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
6592     }
6593     hci_run();
6594 }
6595 #endif
6596 
6597 
6598 #ifdef ENABLE_BLE
6599 
6600 #ifdef ENABLE_LE_CENTRAL
6601 void gap_start_scan(void){
6602     hci_stack->le_scanning_enabled = true;
6603     hci_run();
6604 }
6605 
6606 void gap_stop_scan(void){
6607     hci_stack->le_scanning_enabled = false;
6608     hci_run();
6609 }
6610 
6611 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
6612     hci_stack->le_scan_type          = scan_type;
6613     hci_stack->le_scan_filter_policy = scanning_filter_policy;
6614     hci_stack->le_scan_interval      = scan_interval;
6615     hci_stack->le_scan_window        = scan_window;
6616     hci_stack->le_scanning_param_update = true;
6617     hci_run();
6618 }
6619 
6620 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
6621     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
6622 }
6623 
6624 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
6625     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
6626     if (!conn){
6627         // disallow if le connection is already outgoing
6628         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6629             log_error("le connection already active");
6630             return ERROR_CODE_COMMAND_DISALLOWED;
6631         }
6632 
6633         log_info("gap_connect: no connection exists yet, creating context");
6634         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
6635         if (!conn){
6636             // notify client that alloc failed
6637             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6638             log_info("gap_connect: failed to alloc hci_connection_t");
6639             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
6640         }
6641 
6642         // set le connecting state
6643         if (hci_is_le_connection_type(addr_type)){
6644             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
6645         }
6646 
6647         conn->state = SEND_CREATE_CONNECTION;
6648         log_info("gap_connect: send create connection next");
6649         hci_run();
6650         return ERROR_CODE_SUCCESS;
6651     }
6652 
6653     if (!hci_is_le_connection(conn) ||
6654         (conn->state == SEND_CREATE_CONNECTION) ||
6655         (conn->state == SENT_CREATE_CONNECTION)) {
6656         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
6657         log_error("gap_connect: classic connection or connect is already being created");
6658         return GATT_CLIENT_IN_WRONG_STATE;
6659     }
6660 
6661     // check if connection was just disconnected
6662     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
6663         log_info("gap_connect: send create connection (again)");
6664         conn->state = SEND_CREATE_CONNECTION;
6665         hci_run();
6666         return ERROR_CODE_SUCCESS;
6667     }
6668 
6669     log_info("gap_connect: context exists with state %u", conn->state);
6670     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
6671     hci_run();
6672     return ERROR_CODE_SUCCESS;
6673 }
6674 
6675 // @assumption: only a single outgoing LE Connection exists
6676 static hci_connection_t * gap_get_outgoing_connection(void){
6677     btstack_linked_item_t *it;
6678     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6679         hci_connection_t * conn = (hci_connection_t *) it;
6680         if (!hci_is_le_connection(conn)) continue;
6681         switch (conn->state){
6682             case SEND_CREATE_CONNECTION:
6683             case SENT_CREATE_CONNECTION:
6684             case SENT_CANCEL_CONNECTION:
6685                 return conn;
6686             default:
6687                 break;
6688         };
6689     }
6690     return NULL;
6691 }
6692 
6693 uint8_t gap_connect_cancel(void){
6694     hci_connection_t * conn = gap_get_outgoing_connection();
6695     if (!conn) return 0;
6696     switch (conn->state){
6697         case SEND_CREATE_CONNECTION:
6698             // skip sending create connection and emit event instead
6699             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6700             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
6701             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
6702             btstack_memory_hci_connection_free( conn );
6703             break;
6704         case SENT_CREATE_CONNECTION:
6705             // request to send cancel connection
6706             conn->state = SEND_CANCEL_CONNECTION;
6707             hci_run();
6708             break;
6709         default:
6710             break;
6711     }
6712     return 0;
6713 }
6714 
6715 /**
6716  * @brief Set connection parameters for outgoing connections
6717  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
6718  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
6719  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
6720  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
6721  * @param conn_latency, default: 4
6722  * @param supervision_timeout (unit: 10ms), default: 720 ms
6723  * @param min_ce_length (unit: 0.625ms), default: 10 ms
6724  * @param max_ce_length (unit: 0.625ms), default: 30 ms
6725  */
6726 
6727 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
6728     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
6729     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
6730     hci_stack->le_connection_scan_interval = conn_scan_interval;
6731     hci_stack->le_connection_scan_window = conn_scan_window;
6732     hci_stack->le_connection_interval_min = conn_interval_min;
6733     hci_stack->le_connection_interval_max = conn_interval_max;
6734     hci_stack->le_connection_latency = conn_latency;
6735     hci_stack->le_supervision_timeout = supervision_timeout;
6736     hci_stack->le_minimum_ce_length = min_ce_length;
6737     hci_stack->le_maximum_ce_length = max_ce_length;
6738 }
6739 #endif
6740 
6741 /**
6742  * @brief Updates the connection parameters for a given LE connection
6743  * @param handle
6744  * @param conn_interval_min (unit: 1.25ms)
6745  * @param conn_interval_max (unit: 1.25ms)
6746  * @param conn_latency
6747  * @param supervision_timeout (unit: 10ms)
6748  * @return 0 if ok
6749  */
6750 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6751     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6752     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6753     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6754     connection->le_conn_interval_min = conn_interval_min;
6755     connection->le_conn_interval_max = conn_interval_max;
6756     connection->le_conn_latency = conn_latency;
6757     connection->le_supervision_timeout = supervision_timeout;
6758     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
6759     hci_run();
6760     return 0;
6761 }
6762 
6763 /**
6764  * @brief Request an update of the connection parameter for a given LE connection
6765  * @param handle
6766  * @param conn_interval_min (unit: 1.25ms)
6767  * @param conn_interval_max (unit: 1.25ms)
6768  * @param conn_latency
6769  * @param supervision_timeout (unit: 10ms)
6770  * @return 0 if ok
6771  */
6772 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6773     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6774     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6775     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6776     connection->le_conn_interval_min = conn_interval_min;
6777     connection->le_conn_interval_max = conn_interval_max;
6778     connection->le_conn_latency = conn_latency;
6779     connection->le_supervision_timeout = supervision_timeout;
6780     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
6781     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
6782     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
6783     return 0;
6784 }
6785 
6786 #ifdef ENABLE_LE_PERIPHERAL
6787 
6788 /**
6789  * @brief Set Advertisement Data
6790  * @param advertising_data_length
6791  * @param advertising_data (max 31 octets)
6792  * @note data is not copied, pointer has to stay valid
6793  */
6794 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
6795     hci_stack->le_advertisements_data_len = advertising_data_length;
6796     hci_stack->le_advertisements_data = advertising_data;
6797     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6798     hci_run();
6799 }
6800 
6801 /**
6802  * @brief Set Scan Response Data
6803  * @param advertising_data_length
6804  * @param advertising_data (max 31 octets)
6805  * @note data is not copied, pointer has to stay valid
6806  */
6807 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
6808     hci_stack->le_scan_response_data_len = scan_response_data_length;
6809     hci_stack->le_scan_response_data = scan_response_data;
6810     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6811     hci_run();
6812 }
6813 
6814 /**
6815  * @brief Set Advertisement Parameters
6816  * @param adv_int_min
6817  * @param adv_int_max
6818  * @param adv_type
6819  * @param direct_address_type
6820  * @param direct_address
6821  * @param channel_map
6822  * @param filter_policy
6823  *
6824  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
6825  */
6826  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
6827     uint8_t direct_address_typ, bd_addr_t direct_address,
6828     uint8_t channel_map, uint8_t filter_policy) {
6829 
6830     hci_stack->le_advertisements_interval_min = adv_int_min;
6831     hci_stack->le_advertisements_interval_max = adv_int_max;
6832     hci_stack->le_advertisements_type = adv_type;
6833     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
6834     hci_stack->le_advertisements_channel_map = channel_map;
6835     hci_stack->le_advertisements_filter_policy = filter_policy;
6836     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
6837                  6);
6838 
6839     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6840     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
6841     hci_run();
6842  }
6843 
6844 /**
6845  * @brief Enable/Disable Advertisements
6846  * @param enabled
6847  */
6848 void gap_advertisements_enable(int enabled){
6849     if (enabled == 0){
6850         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
6851     } else {
6852         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
6853     }
6854     hci_update_advertisements_enabled_for_current_roles();
6855     hci_run();
6856 }
6857 
6858 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6859 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
6860     btstack_linked_list_iterator_t it;
6861     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6862     while (btstack_linked_list_iterator_has_next(&it)){
6863         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6864         if ( item->advertising_handle == advertising_handle ) {
6865             return item;
6866         }
6867     }
6868     return NULL;
6869 }
6870 
6871 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
6872     // find free advertisement handle
6873     uint8_t advertisement_handle;
6874     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
6875         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
6876     }
6877     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
6878     // clear
6879     memset(storage, 0, sizeof(le_advertising_set_t));
6880     // copy params
6881     storage->advertising_handle = advertisement_handle;
6882     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
6883     // add to list
6884     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
6885     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6886     *out_advertising_handle = advertisement_handle;
6887     // set tasks and start
6888     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6889     hci_run();
6890     return ERROR_CODE_SUCCESS;
6891 }
6892 
6893 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
6894     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6895     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6896     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
6897     // set tasks and start
6898     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6899     hci_run();
6900     return ERROR_CODE_SUCCESS;
6901 }
6902 
6903 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
6904     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6905     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6906     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
6907     return ERROR_CODE_SUCCESS;
6908 }
6909 
6910 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
6911     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6912     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6913     // periodic advertising requires neither connectable, scannable, legacy or anonymous
6914     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
6915     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
6916     // set tasks and start
6917     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
6918     hci_run();
6919     return ERROR_CODE_SUCCESS;
6920 }
6921 
6922 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
6923     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6924     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6925     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
6926     return ERROR_CODE_SUCCESS;
6927 }
6928 
6929 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
6930     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6931     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6932     memcpy(advertising_set->random_address, random_address, 6);
6933     // set tasks and start
6934     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6935     hci_run();
6936     return ERROR_CODE_SUCCESS;
6937 }
6938 
6939 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
6940     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6941     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6942     advertising_set->adv_data = advertising_data;
6943     advertising_set->adv_data_len = advertising_data_length;
6944     // set tasks and start
6945     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6946     hci_run();
6947     return ERROR_CODE_SUCCESS;
6948 }
6949 
6950 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){
6951     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6952     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6953     advertising_set->scan_data = scan_response_data;
6954     advertising_set->scan_data_len = scan_response_data_length;
6955     // set tasks and start
6956     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6957     hci_run();
6958     return ERROR_CODE_SUCCESS;
6959 }
6960 
6961 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
6962     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6963     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6964     advertising_set->periodic_data = periodic_data;
6965     advertising_set->periodic_data_len = periodic_data_length;
6966     // set tasks and start
6967     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
6968     hci_run();
6969     return ERROR_CODE_SUCCESS;
6970 }
6971 
6972 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
6973     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6974     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6975     advertising_set->enable_timeout = timeout;
6976     advertising_set->enable_max_scan_events = num_extended_advertising_events;
6977     // set tasks and start
6978     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
6979     hci_run();
6980     return ERROR_CODE_SUCCESS;
6981 }
6982 
6983 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
6984     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6985     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
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_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
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->periodic_include_adi = include_adi;
6997     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
6998     hci_run();
6999     return ERROR_CODE_SUCCESS;
7000 }
7001 
7002 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
7003     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7004     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7005     // set tasks and start
7006     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7007     hci_run();
7008     return ERROR_CODE_SUCCESS;
7009 }
7010 
7011 uint8_t gap_extended_advertising_remove(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->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
7016     hci_run();
7017     return ERROR_CODE_SUCCESS;
7018 }
7019 #endif
7020 
7021 #endif
7022 
7023 void hci_le_set_own_address_type(uint8_t own_address_type){
7024     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
7025     if (own_address_type == hci_stack->le_own_addr_type) return;
7026     hci_stack->le_own_addr_type = own_address_type;
7027 
7028 #ifdef ENABLE_LE_PERIPHERAL
7029     // update advertisement parameters, too
7030     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7031     hci_run();
7032 #endif
7033 #ifdef ENABLE_LE_CENTRAL
7034     // note: we don't update scan parameters or modify ongoing connection attempts
7035 #endif
7036 }
7037 
7038 void hci_le_random_address_set(const bd_addr_t random_address){
7039     memcpy(hci_stack->le_random_address, random_address, 6);
7040     hci_stack->le_random_address_set = true;
7041     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7042     hci_run();
7043 }
7044 
7045 #endif
7046 
7047 uint8_t gap_disconnect(hci_con_handle_t handle){
7048     hci_connection_t * conn = hci_connection_for_handle(handle);
7049     if (!conn){
7050         hci_emit_disconnection_complete(handle, 0);
7051         return 0;
7052     }
7053     // ignore if already disconnected
7054     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7055         return 0;
7056     }
7057     conn->state = SEND_DISCONNECT;
7058     hci_run();
7059     return 0;
7060 }
7061 
7062 int gap_read_rssi(hci_con_handle_t con_handle){
7063     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7064     if (hci_connection == NULL) return 0;
7065     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
7066     hci_run();
7067     return 1;
7068 }
7069 
7070 /**
7071  * @brief Get connection type
7072  * @param con_handle
7073  * @result connection_type
7074  */
7075 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
7076     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7077     if (!conn) return GAP_CONNECTION_INVALID;
7078     switch (conn->address_type){
7079         case BD_ADDR_TYPE_LE_PUBLIC:
7080         case BD_ADDR_TYPE_LE_RANDOM:
7081             return GAP_CONNECTION_LE;
7082         case BD_ADDR_TYPE_SCO:
7083             return GAP_CONNECTION_SCO;
7084         case BD_ADDR_TYPE_ACL:
7085             return GAP_CONNECTION_ACL;
7086         default:
7087             return GAP_CONNECTION_INVALID;
7088     }
7089 }
7090 
7091 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
7092     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7093     if (!conn) return HCI_ROLE_INVALID;
7094     return (hci_role_t) conn->role;
7095 }
7096 
7097 
7098 #ifdef ENABLE_CLASSIC
7099 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
7100     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7101     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7102     conn->request_role = role;
7103     hci_run();
7104     return ERROR_CODE_SUCCESS;
7105 }
7106 #endif
7107 
7108 #ifdef ENABLE_BLE
7109 
7110 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){
7111     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7112     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7113 
7114     conn->le_phy_update_all_phys    = all_phys;
7115     conn->le_phy_update_tx_phys     = tx_phys;
7116     conn->le_phy_update_rx_phys     = rx_phys;
7117     conn->le_phy_update_phy_options = phy_options;
7118 
7119     hci_run();
7120 
7121     return 0;
7122 }
7123 
7124 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
7125     // check if already in list
7126     btstack_linked_list_iterator_t it;
7127     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7128     while (btstack_linked_list_iterator_has_next(&it)) {
7129         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
7130         if (entry->address_type != address_type) {
7131             continue;
7132         }
7133         if (memcmp(entry->address, address, 6) != 0) {
7134             continue;
7135         }
7136 		// disallow if already scheduled to add
7137 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
7138 			return ERROR_CODE_COMMAND_DISALLOWED;
7139 		}
7140 		// still on controller, but scheduled to remove -> re-add
7141 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
7142 		return ERROR_CODE_SUCCESS;
7143     }
7144     // alloc and add to list
7145     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
7146     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
7147     entry->address_type = address_type;
7148     (void)memcpy(entry->address, address, 6);
7149     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
7150     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
7151     return ERROR_CODE_SUCCESS;
7152 }
7153 
7154 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7155     btstack_linked_list_iterator_t it;
7156     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7157     while (btstack_linked_list_iterator_has_next(&it)){
7158         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7159         if (entry->address_type != address_type) {
7160             continue;
7161         }
7162         if (memcmp(entry->address, address, 6) != 0) {
7163             continue;
7164         }
7165         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7166             // remove from controller if already present
7167             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7168         }  else {
7169             // directly remove entry from whitelist
7170             btstack_linked_list_iterator_remove(&it);
7171             btstack_memory_whitelist_entry_free(entry);
7172         }
7173         return ERROR_CODE_SUCCESS;
7174     }
7175     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7176 }
7177 
7178 static void hci_whitelist_clear(void){
7179     btstack_linked_list_iterator_t it;
7180     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7181     while (btstack_linked_list_iterator_has_next(&it)){
7182         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7183         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7184             // remove from controller if already present
7185             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7186             continue;
7187         }
7188         // directly remove entry from whitelist
7189         btstack_linked_list_iterator_remove(&it);
7190         btstack_memory_whitelist_entry_free(entry);
7191     }
7192 }
7193 
7194 // free all entries unconditionally
7195 static void hci_whitelist_free(void){
7196     btstack_linked_list_iterator_t lit;
7197     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
7198     while (btstack_linked_list_iterator_has_next(&lit)){
7199         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
7200         btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
7201         btstack_memory_whitelist_entry_free(entry);
7202     }
7203 }
7204 
7205 /**
7206  * @brief Clear Whitelist
7207  * @return 0 if ok
7208  */
7209 uint8_t gap_whitelist_clear(void){
7210     hci_whitelist_clear();
7211     hci_run();
7212     return ERROR_CODE_SUCCESS;
7213 }
7214 
7215 /**
7216  * @brief Add Device to Whitelist
7217  * @param address_typ
7218  * @param address
7219  * @return 0 if ok
7220  */
7221 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
7222     uint8_t status = hci_whitelist_add(address_type, address);
7223     if (status){
7224         return status;
7225     }
7226     hci_run();
7227     return ERROR_CODE_SUCCESS;
7228 }
7229 
7230 /**
7231  * @brief Remove Device from Whitelist
7232  * @param address_typ
7233  * @param address
7234  * @return 0 if ok
7235  */
7236 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7237     uint8_t status = hci_whitelist_remove(address_type, address);
7238     if (status){
7239         return status;
7240     }
7241     hci_run();
7242     return ERROR_CODE_SUCCESS;
7243 }
7244 
7245 #ifdef ENABLE_LE_CENTRAL
7246 /**
7247  * @brief Connect with Whitelist
7248  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
7249  * @return - if ok
7250  */
7251 uint8_t gap_connect_with_whitelist(void){
7252     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7253         return ERROR_CODE_COMMAND_DISALLOWED;
7254     }
7255     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
7256     hci_run();
7257     return ERROR_CODE_SUCCESS;
7258 }
7259 
7260 /**
7261  * @brief Auto Connection Establishment - Start Connecting to device
7262  * @param address_typ
7263  * @param address
7264  * @return 0 if ok
7265  */
7266 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
7267     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
7268         return ERROR_CODE_COMMAND_DISALLOWED;
7269     }
7270 
7271     uint8_t status = hci_whitelist_add(address_type, address);
7272     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
7273         return status;
7274     }
7275 
7276     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
7277 
7278     hci_run();
7279     return ERROR_CODE_SUCCESS;
7280 }
7281 
7282 /**
7283  * @brief Auto Connection Establishment - Stop Connecting to device
7284  * @param address_typ
7285  * @param address
7286  * @return 0 if ok
7287  */
7288 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
7289     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
7290         return ERROR_CODE_COMMAND_DISALLOWED;
7291     }
7292 
7293     hci_whitelist_remove(address_type, address);
7294     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
7295         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7296     }
7297     hci_run();
7298     return 0;
7299 }
7300 
7301 /**
7302  * @brief Auto Connection Establishment - Stop everything
7303  * @note  Convenience function to stop all active auto connection attempts
7304  */
7305 uint8_t gap_auto_connection_stop_all(void){
7306     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
7307         return ERROR_CODE_COMMAND_DISALLOWED;
7308     }
7309     hci_whitelist_clear();
7310     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7311     hci_run();
7312     return ERROR_CODE_SUCCESS;
7313 }
7314 
7315 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
7316     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7317     if (!conn) return 0;
7318     return conn->le_connection_interval;
7319 }
7320 #endif
7321 #endif
7322 
7323 #ifdef ENABLE_CLASSIC
7324 /**
7325  * @brief Set Extended Inquiry Response data
7326  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
7327  * @note has to be done before stack starts up
7328  */
7329 void gap_set_extended_inquiry_response(const uint8_t * data){
7330     hci_stack->eir_data = data;
7331     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7332     hci_run();
7333 }
7334 
7335 /**
7336  * @brief Start GAP Classic Inquiry
7337  * @param duration in 1.28s units
7338  * @return 0 if ok
7339  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
7340  */
7341 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
7342     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
7343     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7344     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
7345         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7346     }
7347     hci_stack->inquiry_state = duration_in_1280ms_units;
7348     hci_run();
7349     return 0;
7350 }
7351 
7352 /**
7353  * @brief Stop GAP Classic Inquiry
7354  * @return 0 if ok
7355  */
7356 int gap_inquiry_stop(void){
7357     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
7358         // emit inquiry complete event, before it even started
7359         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
7360         hci_emit_event(event, sizeof(event), 1);
7361         return 0;
7362     }
7363     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
7364     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
7365     hci_run();
7366     return 0;
7367 }
7368 
7369 void gap_inquiry_set_lap(uint32_t lap){
7370     hci_stack->inquiry_lap = lap;
7371 }
7372 
7373 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
7374     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
7375     hci_stack->inquiry_scan_window   = inquiry_scan_window;
7376     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
7377     hci_run();
7378 }
7379 
7380 
7381 /**
7382  * @brief Remote Name Request
7383  * @param addr
7384  * @param page_scan_repetition_mode
7385  * @param clock_offset only used when bit 15 is set
7386  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
7387  */
7388 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
7389     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7390     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
7391     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
7392     hci_stack->remote_name_clock_offset = clock_offset;
7393     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
7394     hci_run();
7395     return 0;
7396 }
7397 
7398 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
7399     hci_stack->gap_pairing_state = state;
7400     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
7401     hci_run();
7402     return 0;
7403 }
7404 
7405 /**
7406  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
7407  * @param addr
7408  * @param pin_data
7409  * @param pin_len
7410  * @return 0 if ok
7411  */
7412 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
7413     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7414     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
7415     hci_stack->gap_pairing_pin_len = pin_len;
7416     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
7417 }
7418 
7419 /**
7420  * @brief Legacy Pairing Pin Code Response
7421  * @param addr
7422  * @param pin
7423  * @return 0 if ok
7424  */
7425 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
7426     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
7427 }
7428 
7429 /**
7430  * @brief Abort Legacy Pairing
7431  * @param addr
7432  * @param pin
7433  * @return 0 if ok
7434  */
7435 int gap_pin_code_negative(bd_addr_t addr){
7436     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7437     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
7438 }
7439 
7440 /**
7441  * @brief SSP Passkey Response
7442  * @param addr
7443  * @param passkey
7444  * @return 0 if ok
7445  */
7446 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
7447     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7448     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
7449     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
7450 }
7451 
7452 /**
7453  * @brief Abort SSP Passkey Entry/Pairing
7454  * @param addr
7455  * @param pin
7456  * @return 0 if ok
7457  */
7458 int gap_ssp_passkey_negative(const bd_addr_t addr){
7459     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7460     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
7461 }
7462 
7463 /**
7464  * @brief Accept SSP Numeric Comparison
7465  * @param addr
7466  * @param passkey
7467  * @return 0 if ok
7468  */
7469 int gap_ssp_confirmation_response(const bd_addr_t addr){
7470     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7471     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
7472 }
7473 
7474 /**
7475  * @brief Abort SSP Numeric Comparison/Pairing
7476  * @param addr
7477  * @param pin
7478  * @return 0 if ok
7479  */
7480 int gap_ssp_confirmation_negative(const bd_addr_t addr){
7481     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7482     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
7483 }
7484 
7485 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
7486 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
7487     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7488     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7489     connectionSetAuthenticationFlags(conn, flag);
7490     hci_run();
7491     return ERROR_CODE_SUCCESS;
7492 }
7493 #endif
7494 
7495 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
7496 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
7497     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7498 }
7499 
7500 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
7501     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
7502 }
7503 #endif
7504 
7505 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7506 /**
7507  * @brief Report Remote OOB Data
7508  * @param bd_addr
7509  * @param c_192 Simple Pairing Hash C derived from P-192 public key
7510  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
7511  * @param c_256 Simple Pairing Hash C derived from P-256 public key
7512  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
7513  */
7514 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){
7515     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7516     if (connection == NULL) {
7517         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7518     }
7519     connection->classic_oob_c_192 = c_192;
7520     connection->classic_oob_r_192 = r_192;
7521 
7522     // ignore P-256 if not supported by us
7523     if (hci_stack->secure_connections_active){
7524         connection->classic_oob_c_256 = c_256;
7525         connection->classic_oob_r_256 = r_256;
7526     }
7527 
7528     return ERROR_CODE_SUCCESS;
7529 }
7530 /**
7531  * @brief Generate new OOB data
7532  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
7533  */
7534 void gap_ssp_generate_oob_data(void){
7535     hci_stack->classic_read_local_oob_data = true;
7536     hci_run();
7537 }
7538 
7539 #endif
7540 
7541 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
7542 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
7543     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7544     if (connection == NULL) {
7545         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7546     }
7547 
7548     memcpy(connection->link_key, link_key, sizeof(link_key_t));
7549     connection->link_key_type = type;
7550 
7551     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
7552 }
7553 
7554 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
7555 /**
7556  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
7557  * @param inquiry_mode see bluetooth_defines.h
7558  */
7559 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
7560     hci_stack->inquiry_mode = inquiry_mode;
7561 }
7562 
7563 /**
7564  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
7565  */
7566 void hci_set_sco_voice_setting(uint16_t voice_setting){
7567     hci_stack->sco_voice_setting = voice_setting;
7568 }
7569 
7570 /**
7571  * @brief Get SCO Voice Setting
7572  * @return current voice setting
7573  */
7574 uint16_t hci_get_sco_voice_setting(void){
7575     return hci_stack->sco_voice_setting;
7576 }
7577 
7578 static int hci_have_usb_transport(void){
7579     if (!hci_stack->hci_transport) return 0;
7580     const char * transport_name = hci_stack->hci_transport->name;
7581     if (!transport_name) return 0;
7582     return (transport_name[0] == 'H') && (transport_name[1] == '2');
7583 }
7584 
7585 /** @brief Get SCO packet length for current SCO Voice setting
7586  *  @note  Using SCO packets of the exact length is required for USB transfer
7587  *  @return Length of SCO packets in bytes (not audio frames)
7588  */
7589 uint16_t hci_get_sco_packet_length(void){
7590     uint16_t sco_packet_length = 0;
7591 
7592 #ifdef ENABLE_SCO_OVER_HCI
7593     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
7594     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
7595 
7596     if (hci_have_usb_transport()){
7597         // see Core Spec for H2 USB Transfer.
7598         // 3 byte SCO header + 24 bytes per connection
7599         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
7600         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
7601     } else {
7602         // 3 byte SCO header + SCO packet size over the air (60 bytes)
7603         sco_packet_length = 3 + 60 * multiplier;
7604         // assert that it still fits inside an SCO buffer
7605         if (sco_packet_length > hci_stack->sco_data_packet_length){
7606             sco_packet_length = 3 + 60;
7607         }
7608     }
7609 #endif
7610 
7611 #ifdef HAVE_SCO_TRANSPORT
7612     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
7613     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
7614     sco_packet_length = 3 + 60 * multiplier;
7615 #endif
7616     return sco_packet_length;
7617 }
7618 
7619 /**
7620 * @brief Sets the master/slave policy
7621 * @param policy (0: attempt to become master, 1: let connecting device decide)
7622 */
7623 void hci_set_master_slave_policy(uint8_t policy){
7624     hci_stack->master_slave_policy = policy;
7625 }
7626 
7627 #endif
7628 
7629 HCI_STATE hci_get_state(void){
7630     return hci_stack->state;
7631 }
7632 
7633 #ifdef ENABLE_CLASSIC
7634 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
7635     hci_stack->gap_classic_accept_callback = accept_callback;
7636 }
7637 #endif
7638 
7639 /**
7640  * @brief Set callback for Bluetooth Hardware Error
7641  */
7642 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
7643     hci_stack->hardware_error_callback = fn;
7644 }
7645 
7646 void hci_disconnect_all(void){
7647     btstack_linked_list_iterator_t it;
7648     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
7649     while (btstack_linked_list_iterator_has_next(&it)){
7650         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
7651         if (con->state == SENT_DISCONNECT) continue;
7652         con->state = SEND_DISCONNECT;
7653     }
7654     hci_run();
7655 }
7656 
7657 uint16_t hci_get_manufacturer(void){
7658     return hci_stack->manufacturer;
7659 }
7660 
7661 #ifdef ENABLE_BLE
7662 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
7663     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
7664     if (!hci_con) return NULL;
7665     return &hci_con->sm_connection;
7666 }
7667 
7668 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
7669 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
7670 #endif
7671 
7672 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
7673     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7674     if (hci_connection == NULL) return 0;
7675     if (hci_is_le_connection(hci_connection)){
7676 #ifdef ENABLE_BLE
7677         sm_connection_t * sm_conn = &hci_connection->sm_connection;
7678         if (sm_conn->sm_connection_encrypted) {
7679             return sm_conn->sm_actual_encryption_key_size;
7680         }
7681 #endif
7682     } else {
7683 #ifdef ENABLE_CLASSIC
7684         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
7685             return hci_connection->encryption_key_size;
7686         }
7687 #endif
7688     }
7689     return 0;
7690 }
7691 
7692 bool gap_authenticated(hci_con_handle_t con_handle){
7693     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7694     if (hci_connection == NULL) return false;
7695 
7696     switch (hci_connection->address_type){
7697 #ifdef ENABLE_BLE
7698         case BD_ADDR_TYPE_LE_PUBLIC:
7699         case BD_ADDR_TYPE_LE_RANDOM:
7700             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
7701             return hci_connection->sm_connection.sm_connection_authenticated != 0;
7702 #endif
7703 #ifdef ENABLE_CLASSIC
7704         case BD_ADDR_TYPE_SCO:
7705         case BD_ADDR_TYPE_ACL:
7706             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
7707 #endif
7708         default:
7709             return false;
7710     }
7711 }
7712 
7713 bool gap_secure_connection(hci_con_handle_t con_handle){
7714     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7715     if (hci_connection == NULL) return 0;
7716 
7717     switch (hci_connection->address_type){
7718 #ifdef ENABLE_BLE
7719         case BD_ADDR_TYPE_LE_PUBLIC:
7720         case BD_ADDR_TYPE_LE_RANDOM:
7721             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
7722             return hci_connection->sm_connection.sm_connection_sc != 0;
7723 #endif
7724 #ifdef ENABLE_CLASSIC
7725         case BD_ADDR_TYPE_SCO:
7726         case BD_ADDR_TYPE_ACL:
7727             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
7728 #endif
7729         default:
7730             return false;
7731     }
7732 }
7733 
7734 bool gap_bonded(hci_con_handle_t con_handle){
7735 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7736 	if (hci_connection == NULL) return 0;
7737 
7738 #ifdef ENABLE_CLASSIC
7739 	link_key_t link_key;
7740 	link_key_type_t link_key_type;
7741 #endif
7742 	switch (hci_connection->address_type){
7743 #ifdef ENABLE_BLE
7744 		case BD_ADDR_TYPE_LE_PUBLIC:
7745 		case BD_ADDR_TYPE_LE_RANDOM:
7746 			return hci_connection->sm_connection.sm_le_db_index >= 0;
7747 #endif
7748 #ifdef ENABLE_CLASSIC
7749 		case BD_ADDR_TYPE_SCO:
7750 		case BD_ADDR_TYPE_ACL:
7751 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
7752 #endif
7753 		default:
7754 			return false;
7755 	}
7756 }
7757 
7758 #ifdef ENABLE_BLE
7759 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
7760     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
7761     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
7762     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
7763     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
7764     return sm_conn->sm_connection_authorization_state;
7765 }
7766 #endif
7767 
7768 #ifdef ENABLE_CLASSIC
7769 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){
7770     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7771     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7772     conn->sniff_min_interval = sniff_min_interval;
7773     conn->sniff_max_interval = sniff_max_interval;
7774     conn->sniff_attempt = sniff_attempt;
7775     conn->sniff_timeout = sniff_timeout;
7776     hci_run();
7777     return 0;
7778 }
7779 
7780 /**
7781  * @brief Exit Sniff mode
7782  * @param con_handle
7783  @ @return 0 if ok
7784  */
7785 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
7786     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7787     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7788     conn->sniff_min_interval = 0xffff;
7789     hci_run();
7790     return 0;
7791 }
7792 
7793 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){
7794     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7795     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7796     conn->sniff_subrating_max_latency = max_latency;
7797     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
7798     conn->sniff_subrating_min_local_timeout = min_local_timeout;
7799     hci_run();
7800     return ERROR_CODE_SUCCESS;
7801 }
7802 
7803 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){
7804     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7805     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7806     conn->qos_service_type = service_type;
7807     conn->qos_token_rate = token_rate;
7808     conn->qos_peak_bandwidth = peak_bandwidth;
7809     conn->qos_latency = latency;
7810     conn->qos_delay_variation = delay_variation;
7811     hci_run();
7812     return ERROR_CODE_SUCCESS;
7813 }
7814 
7815 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
7816     hci_stack->new_page_scan_interval = page_scan_interval;
7817     hci_stack->new_page_scan_window = page_scan_window;
7818     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
7819     hci_run();
7820 }
7821 
7822 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
7823     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
7824     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
7825     hci_run();
7826 }
7827 
7828 void gap_set_page_timeout(uint16_t page_timeout){
7829     hci_stack->page_timeout = page_timeout;
7830     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
7831     hci_run();
7832 }
7833 
7834 #endif
7835 
7836 void hci_halting_defer(void){
7837     if (hci_stack->state != HCI_STATE_HALTING) return;
7838     switch (hci_stack->substate){
7839         case HCI_HALTING_READY_FOR_CLOSE:
7840             hci_stack->substate = HCI_HALTING_DEFER_CLOSE;
7841             break;
7842         default:
7843             break;
7844     }
7845 }
7846 
7847 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
7848 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
7849     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
7850     if (le_device_db_index >= le_device_db_max_count()) return;
7851     uint8_t offset = le_device_db_index >> 3;
7852     uint8_t mask = 1 << (le_device_db_index & 7);
7853     hci_stack->le_resolving_list_add_entries[offset] |= mask;
7854     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
7855     	// note: go back to remove entries, otherwise, a remove + add will skip the add
7856         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
7857     }
7858 }
7859 
7860 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
7861 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
7862 	if (le_device_db_index >= le_device_db_max_count()) return;
7863 	uint8_t offset = le_device_db_index >> 3;
7864 	uint8_t mask = 1 << (le_device_db_index & 7);
7865 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
7866 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
7867 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
7868 	}
7869 }
7870 
7871 uint8_t gap_load_resolving_list_from_le_device_db(void){
7872     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
7873 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
7874 	}
7875 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
7876 		// restart le resolving list update
7877 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
7878 	}
7879 	return ERROR_CODE_SUCCESS;
7880 }
7881 #endif
7882 
7883 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
7884 void hci_setup_test_connections_fuzz(void){
7885     hci_connection_t * conn;
7886 
7887     // default address: 66:55:44:33:00:01
7888     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
7889 
7890     // setup Controller info
7891     hci_stack->num_cmd_packets = 255;
7892     hci_stack->acl_packets_total_num = 255;
7893 
7894     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
7895     addr[5] = 0x01;
7896     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7897     conn->con_handle = addr[5];
7898     conn->role  = HCI_ROLE_SLAVE;
7899     conn->state = RECEIVED_CONNECTION_REQUEST;
7900     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7901 
7902     // setup incoming Classic SCO connection with con handle 0x0002
7903     addr[5] = 0x02;
7904     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
7905     conn->con_handle = addr[5];
7906     conn->role  = HCI_ROLE_SLAVE;
7907     conn->state = RECEIVED_CONNECTION_REQUEST;
7908     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7909 
7910     // setup ready Classic ACL connection with con handle 0x0003
7911     addr[5] = 0x03;
7912     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7913     conn->con_handle = addr[5];
7914     conn->role  = HCI_ROLE_SLAVE;
7915     conn->state = OPEN;
7916     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7917 
7918     // setup ready Classic SCO connection with con handle 0x0004
7919     addr[5] = 0x04;
7920     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
7921     conn->con_handle = addr[5];
7922     conn->role  = HCI_ROLE_SLAVE;
7923     conn->state = OPEN;
7924     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7925 
7926     // setup ready LE ACL connection with con handle 0x005 and public address
7927     addr[5] = 0x05;
7928     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
7929     conn->con_handle = addr[5];
7930     conn->role  = HCI_ROLE_SLAVE;
7931     conn->state = OPEN;
7932     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7933     conn->sm_connection.sm_connection_encrypted = 1;
7934 }
7935 
7936 void hci_free_connections_fuzz(void){
7937     btstack_linked_list_iterator_t it;
7938     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
7939     while (btstack_linked_list_iterator_has_next(&it)){
7940         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
7941         btstack_linked_list_iterator_remove(&it);
7942         btstack_memory_hci_connection_free(con);
7943     }
7944 }
7945 void hci_simulate_working_fuzz(void){
7946     hci_stack->le_scanning_param_update = false;
7947     hci_init_done();
7948     hci_stack->num_cmd_packets = 255;
7949 }
7950 #endif
7951