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