xref: /btstack/src/hci.c (revision f66adbded43748729afdd4ae735df05b49cbabbb)
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_CENTRAL
4846     if (hci_stack->le_scanning_param_update){
4847         hci_stack->le_scanning_param_update = false;
4848 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4849         if (hci_extended_advertising_supported()){
4850             // prepare arrays for all PHYs
4851             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
4852             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
4853             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
4854             uint8_t  scanning_phys     = 1;  // LE 1M PHY
4855             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
4856                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
4857         } else
4858 #endif
4859         {
4860             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
4861                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
4862         }
4863         return true;
4864     }
4865 #endif
4866 
4867 #ifdef ENABLE_LE_PERIPHERAL
4868     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
4869         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4870         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
4871 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4872         if (hci_extended_advertising_supported()){
4873             // map advertisment type to advertising event properties
4874             uint16_t adv_event_properties = 0;
4875             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
4876             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
4877                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
4878             }
4879             hci_stack->le_advertising_set_in_current_command = 0;
4880             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
4881                          0,
4882                          adv_event_properties,
4883                          hci_stack->le_advertisements_interval_min,
4884                          hci_stack->le_advertisements_interval_max,
4885                          hci_stack->le_advertisements_channel_map,
4886                          hci_stack->le_advertisements_own_addr_type,
4887                          hci_stack->le_advertisements_direct_address_type,
4888                          hci_stack->le_advertisements_direct_address,
4889                          hci_stack->le_advertisements_filter_policy,
4890                          0x7f,  // tx power: no preference
4891                          0x01,  // primary adv phy: LE 1M
4892                          0,     // secondary adv max skip
4893                          0,     // secondary adv phy
4894                          0,     // adv sid
4895                          0      // scan request notification
4896                          );
4897         }
4898 #endif
4899         {
4900             hci_send_cmd(&hci_le_set_advertising_parameters,
4901                          hci_stack->le_advertisements_interval_min,
4902                          hci_stack->le_advertisements_interval_max,
4903                          hci_stack->le_advertisements_type,
4904                          hci_stack->le_advertisements_own_addr_type,
4905                          hci_stack->le_advertisements_direct_address_type,
4906                          hci_stack->le_advertisements_direct_address,
4907                          hci_stack->le_advertisements_channel_map,
4908                          hci_stack->le_advertisements_filter_policy);
4909         }
4910         return true;
4911     }
4912 
4913     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
4914         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4915         uint8_t adv_data_clean[31];
4916         memset(adv_data_clean, 0, sizeof(adv_data_clean));
4917         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
4918                      hci_stack->le_advertisements_data_len);
4919         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
4920 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4921         if (hci_extended_advertising_supported()){
4922             hci_stack->le_advertising_set_in_current_command = 0;
4923             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
4924         } else
4925 #endif
4926         {
4927             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
4928         }
4929         return true;
4930     }
4931 
4932     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
4933         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4934         uint8_t scan_data_clean[31];
4935         memset(scan_data_clean, 0, sizeof(scan_data_clean));
4936         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
4937                      hci_stack->le_scan_response_data_len);
4938         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
4939 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4940         if (hci_extended_advertising_supported()){
4941             hci_stack->le_advertising_set_in_current_command = 0;
4942             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
4943         } else
4944 #endif
4945         {
4946             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
4947         }
4948         return true;
4949     }
4950 
4951 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4952     if (hci_extended_advertising_supported()) {
4953         btstack_linked_list_iterator_t it;
4954         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4955         while (btstack_linked_list_iterator_has_next(&it)){
4956             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4957             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
4958                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
4959                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
4960                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
4961                 return true;
4962             }
4963             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
4964                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
4965                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
4966                 return true;
4967             }
4968             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
4969                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4970                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
4971                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
4972                              advertising_set->advertising_handle,
4973                              advertising_set->params.advertising_event_properties,
4974                              advertising_set->params.primary_advertising_interval_min,
4975                              advertising_set->params.primary_advertising_interval_max,
4976                              advertising_set->params.primary_advertising_channel_map,
4977                              advertising_set->params.own_address_type,
4978                              advertising_set->params.peer_address_type,
4979                              advertising_set->params.peer_address,
4980                              advertising_set->params.advertising_filter_policy,
4981                              advertising_set->params.advertising_tx_power,
4982                              advertising_set->params.primary_advertising_phy,
4983                              advertising_set->params.secondary_advertising_max_skip,
4984                              advertising_set->params.secondary_advertising_phy,
4985                              advertising_set->params.advertising_sid,
4986                              advertising_set->params.scan_request_notification_enable
4987                 );
4988                 return true;
4989             }
4990             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
4991                 uint16_t pos = advertising_set->adv_data_pos;
4992                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
4993                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
4994                 if ((operation & 0x02) != 0){
4995                     // last fragment or complete data
4996                     operation |= 2;
4997                     advertising_set->adv_data_pos = 0;
4998                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4999                 } else {
5000                     advertising_set->adv_data_pos += data_to_upload;
5001                 }
5002                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5003                 hci_send_cmd(&hci_le_set_extended_advertising_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
5004                 return true;
5005             }
5006             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
5007                 uint16_t pos = advertising_set->scan_data_pos;
5008                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
5009                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5010                 if ((operation & 0x02) != 0){
5011                     advertising_set->scan_data_pos = 0;
5012                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5013                 } else {
5014                     advertising_set->scan_data_pos += data_to_upload;
5015                 }
5016                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5017                 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
5018                 return true;
5019             }
5020         }
5021     }
5022 #endif
5023 
5024 
5025 #endif
5026 
5027 
5028 #ifdef ENABLE_LE_CENTRAL
5029     // if connect with whitelist was active and is not cancelled yet, wait until next time
5030     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
5031 #endif
5032 
5033     // LE Whitelist Management
5034     if (whitelist_modification_pending){
5035         // add/remove entries
5036         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5037         while (btstack_linked_list_iterator_has_next(&lit)){
5038             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5039 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5040 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5041 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
5042 				return true;
5043 			}
5044             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
5045 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
5046                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
5047                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
5048                 return true;
5049             }
5050             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
5051 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5052 				btstack_memory_whitelist_entry_free(entry);
5053             }
5054         }
5055     }
5056 
5057 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5058     // LE Resolving List Management
5059     if (resolving_list_supported) {
5060 		uint16_t i;
5061 		switch (hci_stack->le_resolving_list_state) {
5062 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
5063 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
5064 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
5065 				return true;
5066 			case LE_RESOLVING_LIST_READ_SIZE:
5067 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
5068 				hci_send_cmd(&hci_le_read_resolving_list_size);
5069 				return true;
5070 			case LE_RESOLVING_LIST_SEND_CLEAR:
5071 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
5072 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
5073 							  sizeof(hci_stack->le_resolving_list_add_entries));
5074 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
5075 							  sizeof(hci_stack->le_resolving_list_remove_entries));
5076 				hci_send_cmd(&hci_le_clear_resolving_list);
5077 				return true;
5078 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
5079 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5080 					uint8_t offset = i >> 3;
5081 					uint8_t mask = 1 << (i & 7);
5082 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
5083 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
5084 					bd_addr_t peer_identity_addreses;
5085 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5086 					sm_key_t peer_irk;
5087 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5088 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5089 
5090 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
5091 					// trigger whitelist entry 'update' (work around for controller bug)
5092 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5093 					while (btstack_linked_list_iterator_has_next(&lit)) {
5094 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
5095 						if (entry->address_type != peer_identity_addr_type) continue;
5096 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
5097 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
5098 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
5099 					}
5100 #endif
5101 
5102 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
5103 								 peer_identity_addreses);
5104 					return true;
5105 				}
5106 
5107 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
5108 
5109 				/* fall through */
5110 
5111 			case LE_RESOLVING_LIST_ADD_ENTRIES:
5112 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5113 					uint8_t offset = i >> 3;
5114 					uint8_t mask = 1 << (i & 7);
5115 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
5116 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
5117 					bd_addr_t peer_identity_addreses;
5118 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5119 					sm_key_t peer_irk;
5120 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5121 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5122 					const uint8_t *local_irk = gap_get_persistent_irk();
5123 					// command uses format specifier 'P' that stores 16-byte value without flip
5124 					uint8_t local_irk_flipped[16];
5125 					uint8_t peer_irk_flipped[16];
5126 					reverse_128(local_irk, local_irk_flipped);
5127 					reverse_128(peer_irk, peer_irk_flipped);
5128 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
5129 								 peer_irk_flipped, local_irk_flipped);
5130 					return true;
5131 				}
5132 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5133 				break;
5134 
5135 			default:
5136 				break;
5137 		}
5138 	}
5139     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5140 #endif
5141 
5142     // post-pone all actions until stack is fully working
5143     if (hci_stack->state != HCI_STATE_WORKING) return false;
5144 
5145     // advertisements, active scanning, and creating connections requires random address to be set if using private address
5146     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
5147 
5148     // Phase 4: restore state
5149 
5150 #ifdef ENABLE_LE_CENTRAL
5151     // re-start scanning
5152     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
5153         hci_stack->le_scanning_active = true;
5154 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5155         if (hci_extended_advertising_supported()){
5156             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0);
5157         } else
5158 #endif
5159         {
5160             hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
5161         }
5162         return true;
5163     }
5164 #endif
5165 
5166 #ifdef ENABLE_LE_CENTRAL
5167     // re-start connecting
5168     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
5169         bd_addr_t null_addr;
5170         memset(null_addr, 0, 6);
5171         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
5172         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
5173         hci_send_cmd(&hci_le_create_connection,
5174                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
5175                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
5176                      1,         // use whitelist
5177                      0,         // peer address type
5178                      null_addr, // peer bd addr
5179                      hci_stack->le_connection_own_addr_type,   // our addr type:
5180                      hci_stack->le_connection_interval_min,    // conn interval min
5181                      hci_stack->le_connection_interval_max,    // conn interval max
5182                      hci_stack->le_connection_latency,         // conn latency
5183                      hci_stack->le_supervision_timeout,        // conn latency
5184                      hci_stack->le_minimum_ce_length,          // min ce length
5185                      hci_stack->le_maximum_ce_length           // max ce length
5186         );
5187         return true;
5188     }
5189 #endif
5190 
5191 #ifdef ENABLE_LE_PERIPHERAL
5192     // re-start advertising
5193     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
5194         // check if advertisements should be enabled given
5195         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
5196         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
5197 
5198 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5199         if (hci_extended_advertising_supported()){
5200             const uint8_t advertising_handles[] = { 0 };
5201             const uint16_t durations[] = { 0 };
5202             const uint16_t max_events[] = { 0 };
5203             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
5204         } else
5205 #endif
5206         {
5207             hci_send_cmd(&hci_le_set_advertise_enable, 1);
5208         }
5209         return true;
5210     }
5211 
5212 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5213     if (hci_extended_advertising_supported()) {
5214         btstack_linked_list_iterator_t it;
5215         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5216         while (btstack_linked_list_iterator_has_next(&it)) {
5217             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
5218             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
5219                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
5220                 const uint16_t durations[] = { advertising_set->enable_timeout };
5221                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
5222                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
5223                 return true;
5224             }
5225         }
5226     }
5227 #endif
5228 #endif
5229 
5230     return false;
5231 }
5232 #endif
5233 
5234 static bool hci_run_general_pending_commands(void){
5235     btstack_linked_item_t * it;
5236     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5237         hci_connection_t * connection = (hci_connection_t *) it;
5238 
5239         switch(connection->state){
5240             case SEND_CREATE_CONNECTION:
5241                 switch(connection->address_type){
5242 #ifdef ENABLE_CLASSIC
5243                     case BD_ADDR_TYPE_ACL:
5244                         log_info("sending hci_create_connection");
5245                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
5246                         break;
5247 #endif
5248                     default:
5249 #ifdef ENABLE_BLE
5250 #ifdef ENABLE_LE_CENTRAL
5251                         log_info("sending hci_le_create_connection");
5252                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
5253                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
5254                         hci_send_cmd(&hci_le_create_connection,
5255                                      hci_stack->le_connection_scan_interval,    // conn scan interval
5256                                      hci_stack->le_connection_scan_window,      // conn scan windows
5257                                      0,         // don't use whitelist
5258                                      connection->address_type, // peer address type
5259                                      connection->address,      // peer bd addr
5260                                      hci_stack->le_connection_own_addr_type,   // our addr type:
5261                                      hci_stack->le_connection_interval_min,    // conn interval min
5262                                      hci_stack->le_connection_interval_max,    // conn interval max
5263                                      hci_stack->le_connection_latency,         // conn latency
5264                                      hci_stack->le_supervision_timeout,        // conn latency
5265                                      hci_stack->le_minimum_ce_length,          // min ce length
5266                                      hci_stack->le_maximum_ce_length          // max ce length
5267                         );
5268                         connection->state = SENT_CREATE_CONNECTION;
5269 #endif
5270 #endif
5271                         break;
5272                 }
5273                 return true;
5274 
5275 #ifdef ENABLE_CLASSIC
5276             case RECEIVED_CONNECTION_REQUEST:
5277                 connection->role  = HCI_ROLE_SLAVE;
5278                 if (connection->address_type == BD_ADDR_TYPE_ACL){
5279                     log_info("sending hci_accept_connection_request");
5280                     connection->state = ACCEPTED_CONNECTION_REQUEST;
5281                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
5282                     return true;
5283                 }
5284                 break;
5285 #endif
5286 
5287 #ifdef ENABLE_BLE
5288 #ifdef ENABLE_LE_CENTRAL
5289             case SEND_CANCEL_CONNECTION:
5290                 connection->state = SENT_CANCEL_CONNECTION;
5291                 hci_send_cmd(&hci_le_create_connection_cancel);
5292                 return true;
5293 #endif
5294 #endif
5295             case SEND_DISCONNECT:
5296                 connection->state = SENT_DISCONNECT;
5297                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5298                 return true;
5299 
5300             default:
5301                 break;
5302         }
5303 
5304         // no further commands if connection is about to get shut down
5305         if (connection->state == SENT_DISCONNECT) continue;
5306 
5307         if (connection->authentication_flags & AUTH_FLAG_READ_RSSI){
5308             connectionClearAuthenticationFlags(connection, AUTH_FLAG_READ_RSSI);
5309             hci_send_cmd(&hci_read_rssi, connection->con_handle);
5310             return true;
5311         }
5312 
5313 #ifdef ENABLE_CLASSIC
5314 
5315         if (connection->authentication_flags & AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT){
5316             connectionClearAuthenticationFlags(connection, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
5317             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
5318             return true;
5319         }
5320 
5321         // Handling link key request requires remote supported features
5322         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
5323             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
5324             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
5325 
5326             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
5327             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
5328             if (have_link_key && security_level_sufficient){
5329                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
5330             } else {
5331                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
5332             }
5333             return true;
5334         }
5335 
5336         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
5337             log_info("denying to pin request");
5338             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
5339             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
5340             return true;
5341         }
5342 
5343         // security assessment requires remote features
5344         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
5345             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
5346             hci_ssp_assess_security_on_io_cap_request(connection);
5347             // 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
5348         }
5349 
5350         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
5351             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
5352             // set authentication requirements:
5353             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
5354             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
5355             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
5356             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
5357                 authreq |= 1;
5358             }
5359             bool bonding = hci_stack->bondable;
5360             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
5361                 // if we have received IO Cap Response, we're in responder role
5362                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
5363                 if (bonding && !remote_bonding){
5364                     log_info("Remote not bonding, dropping local flag");
5365                     bonding = false;
5366                 }
5367             }
5368             if (bonding){
5369                 if (connection->bonding_flags & BONDING_DEDICATED){
5370                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
5371                 } else {
5372                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
5373                 }
5374             }
5375             uint8_t have_oob_data = 0;
5376 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5377             if (connection->classic_oob_c_192 != NULL){
5378                     have_oob_data |= 1;
5379             }
5380             if (connection->classic_oob_c_256 != NULL){
5381                 have_oob_data |= 2;
5382             }
5383 #endif
5384             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
5385             return true;
5386         }
5387 
5388         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
5389             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
5390             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
5391             return true;
5392         }
5393 
5394 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5395         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
5396             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
5397             const uint8_t zero[16] = { 0 };
5398             const uint8_t * r_192 = zero;
5399             const uint8_t * c_192 = zero;
5400             const uint8_t * r_256 = zero;
5401             const uint8_t * c_256 = zero;
5402             // verify P-256 OOB
5403             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
5404                 c_256 = connection->classic_oob_c_256;
5405                 if (connection->classic_oob_r_256 != NULL) {
5406                     r_256 = connection->classic_oob_r_256;
5407                 }
5408             }
5409             // verify P-192 OOB
5410             if ((connection->classic_oob_c_192 != NULL)) {
5411                 c_192 = connection->classic_oob_c_192;
5412                 if (connection->classic_oob_r_192 != NULL) {
5413                     r_192 = connection->classic_oob_r_192;
5414                 }
5415             }
5416 
5417             // assess security
5418             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
5419             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
5420             if (need_level_4 && !can_reach_level_4){
5421                 log_info("Level 4 required, but not possible -> abort");
5422                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
5423                 // send oob negative reply
5424                 c_256 = NULL;
5425                 c_192 = NULL;
5426             }
5427 
5428             // Reply
5429             if (c_256 != zero) {
5430                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
5431             } else if (c_192 != zero){
5432                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
5433             } else {
5434                 hci_stack->classic_oob_con_handle = connection->con_handle;
5435                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
5436             }
5437             return true;
5438         }
5439 #endif
5440 
5441         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
5442             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
5443             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
5444             return true;
5445         }
5446 
5447         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
5448             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
5449             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
5450             return true;
5451         }
5452 
5453         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
5454             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
5455             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
5456             return true;
5457         }
5458 
5459         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
5460             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
5461             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
5462             connection->state = SENT_DISCONNECT;
5463             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5464             return true;
5465         }
5466 
5467         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
5468             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
5469             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
5470             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
5471             return true;
5472         }
5473 
5474         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
5475             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
5476             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
5477             return true;
5478         }
5479 
5480         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
5481             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
5482             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
5483             return true;
5484         }
5485 
5486         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
5487             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
5488             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
5489             return true;
5490         }
5491 
5492         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
5493             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
5494             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
5495             return true;
5496         }
5497 
5498         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
5499             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
5500             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
5501             return true;
5502         }
5503 #endif
5504 
5505         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
5506             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
5507 #ifdef ENABLE_CLASSIC
5508             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
5509 #endif
5510             if (connection->state != SENT_DISCONNECT){
5511                 connection->state = SENT_DISCONNECT;
5512                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
5513                 return true;
5514             }
5515         }
5516 
5517 #ifdef ENABLE_CLASSIC
5518         uint16_t sniff_min_interval;
5519         switch (connection->sniff_min_interval){
5520             case 0:
5521                 break;
5522             case 0xffff:
5523                 connection->sniff_min_interval = 0;
5524                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
5525                 return true;
5526             default:
5527                 sniff_min_interval = connection->sniff_min_interval;
5528                 connection->sniff_min_interval = 0;
5529                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
5530                 return true;
5531         }
5532 
5533         if (connection->sniff_subrating_max_latency != 0xffff){
5534             uint16_t max_latency = connection->sniff_subrating_max_latency;
5535             connection->sniff_subrating_max_latency = 0;
5536             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
5537             return true;
5538         }
5539 
5540         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
5541             uint8_t service_type = (uint8_t) connection->qos_service_type;
5542             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
5543             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);
5544             return true;
5545         }
5546 
5547         if (connection->request_role != HCI_ROLE_INVALID){
5548             hci_role_t role = connection->request_role;
5549             connection->request_role = HCI_ROLE_INVALID;
5550             hci_send_cmd(&hci_switch_role_command, connection->address, role);
5551             return true;
5552         }
5553 #endif
5554 
5555 #ifdef ENABLE_BLE
5556         switch (connection->le_con_parameter_update_state){
5557             // response to L2CAP CON PARAMETER UPDATE REQUEST
5558             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
5559                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5560                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
5561                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
5562                              0x0000, 0xffff);
5563                 return true;
5564             case CON_PARAMETER_UPDATE_REPLY:
5565                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5566                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
5567                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
5568                              0x0000, 0xffff);
5569                 return true;
5570             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
5571                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5572                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
5573                 return true;
5574             default:
5575                 break;
5576         }
5577         if (connection->le_phy_update_all_phys != 0xffu){
5578             uint8_t all_phys = connection->le_phy_update_all_phys;
5579             connection->le_phy_update_all_phys = 0xff;
5580             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);
5581             return true;
5582         }
5583 #endif
5584     }
5585     return false;
5586 }
5587 
5588 static void hci_run(void){
5589 
5590     // stack state sub statemachines
5591     // halting needs to be called even if we cannot send command packet now
5592     switch (hci_stack->state) {
5593         case HCI_STATE_INITIALIZING:
5594             hci_initializing_run();
5595             break;
5596         case HCI_STATE_HALTING:
5597             hci_halting_run();
5598             break;
5599         case HCI_STATE_FALLING_ASLEEP:
5600             hci_falling_asleep_run();
5601             break;
5602         default:
5603             break;
5604     }
5605 
5606     bool done;
5607 
5608     // send continuation fragments first, as they block the prepared packet buffer
5609     done = hci_run_acl_fragments();
5610     if (done) return;
5611 
5612 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5613     // send host num completed packets next as they don't require num_cmd_packets > 0
5614     if (!hci_can_send_comand_packet_transport()) return;
5615     if (hci_stack->host_completed_packets){
5616         hci_host_num_completed_packets();
5617         return;
5618     }
5619 #endif
5620 
5621     if (!hci_can_send_command_packet_now()) return;
5622 
5623     // global/non-connection oriented commands
5624 
5625 
5626 #ifdef ENABLE_CLASSIC
5627     // general gap classic
5628     done = hci_run_general_gap_classic();
5629     if (done) return;
5630 #endif
5631 
5632 #ifdef ENABLE_BLE
5633     // general gap le
5634     done = hci_run_general_gap_le();
5635     if (done) return;
5636 #endif
5637 
5638     // send pending HCI commands
5639     hci_run_general_pending_commands();
5640 }
5641 
5642 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
5643     // house-keeping
5644 
5645 #ifdef ENABLE_CLASSIC
5646     bd_addr_t addr;
5647     hci_connection_t * conn;
5648 #endif
5649 #ifdef ENABLE_LE_CENTRAL
5650     uint8_t initiator_filter_policy;
5651 #endif
5652 
5653     uint16_t opcode = little_endian_read_16(packet, 0);
5654     switch (opcode) {
5655         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
5656             hci_stack->loopback_mode = packet[3];
5657             break;
5658 
5659 #ifdef ENABLE_CLASSIC
5660         case HCI_OPCODE_HCI_CREATE_CONNECTION:
5661             reverse_bd_addr(&packet[3], addr);
5662             log_info("Create_connection to %s", bd_addr_to_str(addr));
5663 
5664             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
5665             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
5666                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
5667                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
5668             }
5669 
5670             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5671             if (!conn) {
5672                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5673                 if (!conn) {
5674                     // notify client that alloc failed
5675                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5676                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
5677                 }
5678                 conn->state = SEND_CREATE_CONNECTION;
5679                 conn->role  = HCI_ROLE_MASTER;
5680             }
5681 
5682             conn->con_handle = HCI_CON_HANDLE_INVALID;
5683             conn->role = HCI_ROLE_INVALID;
5684 
5685             log_info("conn state %u", conn->state);
5686             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
5687             switch (conn->state) {
5688                 // if connection active exists
5689                 case OPEN:
5690                     // and OPEN, emit connection complete command
5691                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
5692                     // packet not sent to controller
5693                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5694                 case RECEIVED_DISCONNECTION_COMPLETE:
5695                     // create connection triggered in disconnect complete event, let's do it now
5696                     break;
5697                 case SEND_CREATE_CONNECTION:
5698                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
5699                     break;
5700                 default:
5701                     // otherwise, just ignore as it is already in the open process
5702                     // packet not sent to controller
5703                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5704             }
5705             conn->state = SENT_CREATE_CONNECTION;
5706 
5707             // track outgoing connection
5708             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
5709             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
5710             break;
5711 
5712 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
5713         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
5714             // setup_synchronous_connection? Voice setting at offset 22
5715             // TODO: compare to current setting if sco connection already active
5716             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
5717             break;
5718         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
5719             // accept_synchronous_connection? Voice setting at offset 18
5720             // TODO: compare to current setting if sco connection already active
5721             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
5722             // track outgoing connection
5723             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
5724             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
5725             break;
5726 #endif
5727 #endif
5728 
5729 #ifdef ENABLE_BLE
5730 #ifdef ENABLE_LE_CENTRAL
5731         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
5732             // white list used?
5733             initiator_filter_policy = packet[7];
5734             switch (initiator_filter_policy) {
5735                 case 0:
5736                     // whitelist not used
5737                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
5738                     break;
5739                 case 1:
5740                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
5741                     break;
5742                 default:
5743                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
5744                     break;
5745             }
5746             // track outgoing connection
5747             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
5748             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
5749             break;
5750         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
5751             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
5752             break;
5753 #endif
5754 #endif
5755         default:
5756             break;
5757     }
5758 
5759     hci_stack->num_cmd_packets--;
5760 
5761     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5762     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5763     if (err != 0){
5764         return ERROR_CODE_HARDWARE_FAILURE;
5765     }
5766     return ERROR_CODE_SUCCESS;
5767 }
5768 
5769 // disconnect because of security block
5770 void hci_disconnect_security_block(hci_con_handle_t con_handle){
5771     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5772     if (!connection) return;
5773     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
5774 }
5775 
5776 
5777 // Configure Secure Simple Pairing
5778 
5779 #ifdef ENABLE_CLASSIC
5780 
5781 // enable will enable SSP during init
5782 void gap_ssp_set_enable(int enable){
5783     hci_stack->ssp_enable = enable;
5784 }
5785 
5786 static int hci_local_ssp_activated(void){
5787     return gap_ssp_supported() && hci_stack->ssp_enable;
5788 }
5789 
5790 // if set, BTstack will respond to io capability request using authentication requirement
5791 void gap_ssp_set_io_capability(int io_capability){
5792     hci_stack->ssp_io_capability = io_capability;
5793 }
5794 void gap_ssp_set_authentication_requirement(int authentication_requirement){
5795     hci_stack->ssp_authentication_requirement = authentication_requirement;
5796 }
5797 
5798 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
5799 void gap_ssp_set_auto_accept(int auto_accept){
5800     hci_stack->ssp_auto_accept = auto_accept;
5801 }
5802 
5803 void gap_secure_connections_enable(bool enable){
5804     hci_stack->secure_connections_enable = enable;
5805 }
5806 
5807 #endif
5808 
5809 // va_list part of hci_send_cmd
5810 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
5811     if (!hci_can_send_command_packet_now()){
5812         log_error("hci_send_cmd called but cannot send packet now");
5813         return ERROR_CODE_COMMAND_DISALLOWED;
5814     }
5815 
5816     // for HCI INITIALIZATION
5817     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
5818     hci_stack->last_cmd_opcode = cmd->opcode;
5819 
5820     hci_reserve_packet_buffer();
5821     uint8_t * packet = hci_stack->hci_packet_buffer;
5822     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
5823     uint8_t status = hci_send_cmd_packet(packet, size);
5824 
5825     // release packet buffer on error or for synchronous transport implementations
5826     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
5827         hci_release_packet_buffer();
5828         hci_emit_transport_packet_sent();
5829     }
5830 
5831     return status;
5832 }
5833 
5834 /**
5835  * pre: numcmds >= 0 - it's allowed to send a command to the controller
5836  */
5837 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
5838     va_list argptr;
5839     va_start(argptr, cmd);
5840     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
5841     va_end(argptr);
5842     return status;
5843 }
5844 
5845 // Create various non-HCI events.
5846 // TODO: generalize, use table similar to hci_create_command
5847 
5848 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
5849     // dump packet
5850     if (dump) {
5851         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
5852     }
5853 
5854     // dispatch to all event handlers
5855     btstack_linked_list_iterator_t it;
5856     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
5857     while (btstack_linked_list_iterator_has_next(&it)){
5858         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
5859         entry->callback(HCI_EVENT_PACKET, 0, event, size);
5860     }
5861 }
5862 
5863 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
5864     if (!hci_stack->acl_packet_handler) return;
5865     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
5866 }
5867 
5868 #ifdef ENABLE_CLASSIC
5869 static void hci_notify_if_sco_can_send_now(void){
5870     // notify SCO sender if waiting
5871     if (!hci_stack->sco_waiting_for_can_send_now) return;
5872     if (hci_can_send_sco_packet_now()){
5873         hci_stack->sco_waiting_for_can_send_now = 0;
5874         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
5875         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
5876         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
5877     }
5878 }
5879 
5880 // parsing end emitting has been merged to reduce code size
5881 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
5882     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
5883 
5884     uint8_t * eir_data;
5885     ad_context_t context;
5886     const uint8_t * name;
5887     uint8_t         name_len;
5888 
5889     if (size < 3) return;
5890 
5891     int event_type = hci_event_packet_get_type(packet);
5892     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
5893     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
5894 
5895     switch (event_type){
5896         case HCI_EVENT_INQUIRY_RESULT:
5897         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5898             if (size != (3 + (num_responses * 14))) return;
5899             break;
5900         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5901             if (size != 257) return;
5902             if (num_responses != 1) return;
5903             break;
5904         default:
5905             return;
5906     }
5907 
5908     // event[1] is set at the end
5909     int i;
5910     for (i=0; i<num_responses;i++){
5911         memset(event, 0, sizeof(event));
5912         event[0] = GAP_EVENT_INQUIRY_RESULT;
5913         uint8_t event_size = 27;    // if name is not set by EIR
5914 
5915         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
5916         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
5917         (void)memcpy(&event[9],
5918                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
5919                      3); // class of device
5920         (void)memcpy(&event[12],
5921                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
5922                      2); // clock offset
5923 
5924         switch (event_type){
5925             case HCI_EVENT_INQUIRY_RESULT:
5926                 // 14,15,16,17 = 0, size 18
5927                 break;
5928             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5929                 event[14] = 1;
5930                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5931                 // 16,17 = 0, size 18
5932                 break;
5933             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5934                 event[14] = 1;
5935                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5936                 // EIR packets only contain a single inquiry response
5937                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
5938                 name = NULL;
5939                 // Iterate over EIR data
5940                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
5941                     uint8_t data_type    = ad_iterator_get_data_type(&context);
5942                     uint8_t data_size    = ad_iterator_get_data_len(&context);
5943                     const uint8_t * data = ad_iterator_get_data(&context);
5944                     // Prefer Complete Local Name over Shortened Local Name
5945                     switch (data_type){
5946                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
5947                             if (name) continue;
5948                             /* fall through */
5949                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
5950                             name = data;
5951                             name_len = data_size;
5952                             break;
5953                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
5954                             if (data_size != 8) break;
5955                             event[16] = 1;
5956                             memcpy(&event[17], data, 8);
5957                             break;
5958                         default:
5959                             break;
5960                     }
5961                 }
5962                 if (name){
5963                     event[25] = 1;
5964                     // truncate name if needed
5965                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
5966                     event[26] = len;
5967                     (void)memcpy(&event[27], name, len);
5968                     event_size += len;
5969                 }
5970                 break;
5971             default:
5972                 return;
5973         }
5974         event[1] = event_size - 2;
5975         hci_emit_event(event, event_size, 1);
5976     }
5977 }
5978 #endif
5979 
5980 void hci_emit_state(void){
5981     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
5982     uint8_t event[3];
5983     event[0] = BTSTACK_EVENT_STATE;
5984     event[1] = sizeof(event) - 2u;
5985     event[2] = hci_stack->state;
5986     hci_emit_event(event, sizeof(event), 1);
5987 }
5988 
5989 #ifdef ENABLE_CLASSIC
5990 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5991     uint8_t event[13];
5992     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
5993     event[1] = sizeof(event) - 2;
5994     event[2] = status;
5995     little_endian_store_16(event, 3, con_handle);
5996     reverse_bd_addr(address, &event[5]);
5997     event[11] = 1; // ACL connection
5998     event[12] = 0; // encryption disabled
5999     hci_emit_event(event, sizeof(event), 1);
6000 }
6001 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
6002     if (disable_l2cap_timeouts) return;
6003     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
6004     uint8_t event[4];
6005     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
6006     event[1] = sizeof(event) - 2;
6007     little_endian_store_16(event, 2, conn->con_handle);
6008     hci_emit_event(event, sizeof(event), 1);
6009 }
6010 #endif
6011 
6012 #ifdef ENABLE_BLE
6013 #ifdef ENABLE_LE_CENTRAL
6014 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){
6015     uint8_t event[21];
6016     event[0] = HCI_EVENT_LE_META;
6017     event[1] = sizeof(event) - 2u;
6018     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
6019     event[3] = status;
6020     little_endian_store_16(event, 4, con_handle);
6021     event[6] = 0; // TODO: role
6022     event[7] = address_type;
6023     reverse_bd_addr(address, &event[8]);
6024     little_endian_store_16(event, 14, 0); // interval
6025     little_endian_store_16(event, 16, 0); // latency
6026     little_endian_store_16(event, 18, 0); // supervision timeout
6027     event[20] = 0; // master clock accuracy
6028     hci_emit_event(event, sizeof(event), 1);
6029 }
6030 #endif
6031 #endif
6032 
6033 static void hci_emit_transport_packet_sent(void){
6034     // notify upper stack that it might be possible to send again
6035     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
6036     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
6037 }
6038 
6039 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
6040     uint8_t event[6];
6041     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
6042     event[1] = sizeof(event) - 2u;
6043     event[2] = 0; // status = OK
6044     little_endian_store_16(event, 3, con_handle);
6045     event[5] = reason;
6046     hci_emit_event(event, sizeof(event), 1);
6047 }
6048 
6049 static void hci_emit_nr_connections_changed(void){
6050     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
6051     uint8_t event[3];
6052     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
6053     event[1] = sizeof(event) - 2u;
6054     event[2] = nr_hci_connections();
6055     hci_emit_event(event, sizeof(event), 1);
6056 }
6057 
6058 static void hci_emit_hci_open_failed(void){
6059     log_info("BTSTACK_EVENT_POWERON_FAILED");
6060     uint8_t event[2];
6061     event[0] = BTSTACK_EVENT_POWERON_FAILED;
6062     event[1] = sizeof(event) - 2u;
6063     hci_emit_event(event, sizeof(event), 1);
6064 }
6065 
6066 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
6067     log_info("hci_emit_dedicated_bonding_result %u ", status);
6068     uint8_t event[9];
6069     int pos = 0;
6070     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
6071     event[pos++] = sizeof(event) - 2u;
6072     event[pos++] = status;
6073     reverse_bd_addr(address, &event[pos]);
6074     hci_emit_event(event, sizeof(event), 1);
6075 }
6076 
6077 
6078 #ifdef ENABLE_CLASSIC
6079 
6080 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
6081     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
6082     uint8_t event[5];
6083     int pos = 0;
6084     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
6085     event[pos++] = sizeof(event) - 2;
6086     little_endian_store_16(event, 2, con_handle);
6087     pos += 2;
6088     event[pos++] = level;
6089     hci_emit_event(event, sizeof(event), 1);
6090 }
6091 
6092 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
6093     if (!connection) return LEVEL_0;
6094     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
6095     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
6096     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
6097     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
6098     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
6099     // LEVEL 4 always requires 128 bit encrytion key size
6100     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
6101         security_level = LEVEL_3;
6102     }
6103     return security_level;
6104 }
6105 
6106 static void hci_emit_discoverable_enabled(uint8_t enabled){
6107     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
6108     uint8_t event[3];
6109     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
6110     event[1] = sizeof(event) - 2;
6111     event[2] = enabled;
6112     hci_emit_event(event, sizeof(event), 1);
6113 }
6114 
6115 // query if remote side supports eSCO
6116 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
6117     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6118     if (!connection) return false;
6119     return (connection->remote_supported_features[0] & 1) != 0;
6120 }
6121 
6122 static bool hci_ssp_supported(hci_connection_t * connection){
6123     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
6124     return (connection->bonding_flags & mask) == mask;
6125 }
6126 
6127 // query if remote side supports SSP
6128 bool hci_remote_ssp_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 hci_ssp_supported(connection) ? 1 : 0;
6132 }
6133 
6134 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
6135     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
6136 }
6137 
6138 /**
6139  * Check if remote supported features query has completed
6140  */
6141 bool hci_remote_features_available(hci_con_handle_t handle){
6142     hci_connection_t * connection = hci_connection_for_handle(handle);
6143     if (!connection) return false;
6144     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
6145 }
6146 
6147 /**
6148  * Trigger remote supported features query
6149  */
6150 
6151 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
6152     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
6153         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6154     }
6155 }
6156 
6157 void hci_remote_features_query(hci_con_handle_t con_handle){
6158     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6159     if (!connection) return;
6160     hci_trigger_remote_features_for_connection(connection);
6161     hci_run();
6162 }
6163 
6164 // GAP API
6165 /**
6166  * @bbrief enable/disable bonding. default is enabled
6167  * @praram enabled
6168  */
6169 void gap_set_bondable_mode(int enable){
6170     hci_stack->bondable = enable ? 1 : 0;
6171 }
6172 /**
6173  * @brief Get bondable mode.
6174  * @return 1 if bondable
6175  */
6176 int gap_get_bondable_mode(void){
6177     return hci_stack->bondable;
6178 }
6179 
6180 /**
6181  * @brief map link keys to security levels
6182  */
6183 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
6184     switch (link_key_type){
6185         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6186             return LEVEL_4;
6187         case COMBINATION_KEY:
6188         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
6189             return LEVEL_3;
6190         default:
6191             return LEVEL_2;
6192     }
6193 }
6194 
6195 /**
6196  * @brief map link keys to secure connection yes/no
6197  */
6198 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
6199     switch (link_key_type){
6200         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6201         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6202             return true;
6203         default:
6204             return false;
6205     }
6206 }
6207 
6208 /**
6209  * @brief map link keys to authenticated
6210  */
6211 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
6212     switch (link_key_type){
6213         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6214         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
6215             return true;
6216         default:
6217             return false;
6218     }
6219 }
6220 
6221 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
6222     log_info("gap_mitm_protection_required_for_security_level %u", level);
6223     return level > LEVEL_2;
6224 }
6225 
6226 /**
6227  * @brief get current security level
6228  */
6229 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
6230     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6231     if (!connection) return LEVEL_0;
6232     return gap_security_level_for_connection(connection);
6233 }
6234 
6235 /**
6236  * @brief request connection to device to
6237  * @result GAP_AUTHENTICATION_RESULT
6238  */
6239 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
6240     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6241     if (!connection){
6242         hci_emit_security_level(con_handle, LEVEL_0);
6243         return;
6244     }
6245 
6246     btstack_assert(hci_is_le_connection(connection) == false);
6247 
6248     // 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)
6249     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
6250     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
6251         requested_level = LEVEL_4;
6252     }
6253 
6254     gap_security_level_t current_level = gap_security_level(con_handle);
6255     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
6256         requested_level, connection->requested_security_level, current_level);
6257 
6258     // authentication active if authentication request was sent or planned level > 0
6259     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
6260     if (authentication_active){
6261         // authentication already active
6262         if (connection->requested_security_level < requested_level){
6263             // increase requested level as new level is higher
6264             // TODO: handle re-authentication when done
6265             connection->requested_security_level = requested_level;
6266         }
6267     } else {
6268         // no request active, notify if security sufficient
6269         if (requested_level <= current_level){
6270             hci_emit_security_level(con_handle, current_level);
6271             return;
6272         }
6273 
6274         // store request
6275         connection->requested_security_level = requested_level;
6276 
6277         // request remote features if not already active
6278         hci_remote_features_query(con_handle);
6279 
6280         // start to authenticate connection
6281         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
6282         hci_run();
6283     }
6284 }
6285 
6286 /**
6287  * @brief start dedicated bonding with device. disconnect after bonding
6288  * @param device
6289  * @param request MITM protection
6290  * @result GAP_DEDICATED_BONDING_COMPLETE
6291  */
6292 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
6293 
6294     // create connection state machine
6295     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
6296 
6297     if (!connection){
6298         return BTSTACK_MEMORY_ALLOC_FAILED;
6299     }
6300 
6301     // delete linkn key
6302     gap_drop_link_key_for_bd_addr(device);
6303 
6304     // configure LEVEL_2/3, dedicated bonding
6305     connection->state = SEND_CREATE_CONNECTION;
6306     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
6307     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
6308     connection->bonding_flags = BONDING_DEDICATED;
6309 
6310     // wait for GAP Security Result and send GAP Dedicated Bonding complete
6311 
6312     // handle: connnection failure (connection complete != ok)
6313     // handle: authentication failure
6314     // handle: disconnect on done
6315 
6316     hci_run();
6317 
6318     return 0;
6319 }
6320 
6321 void gap_set_local_name(const char * local_name){
6322     hci_stack->local_name = local_name;
6323     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
6324     // also update EIR if not set by user
6325     if (hci_stack->eir_data == NULL){
6326         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
6327     }
6328     hci_run();
6329 }
6330 #endif
6331 
6332 
6333 #ifdef ENABLE_BLE
6334 
6335 #ifdef ENABLE_LE_CENTRAL
6336 void gap_start_scan(void){
6337     hci_stack->le_scanning_enabled = true;
6338     hci_run();
6339 }
6340 
6341 void gap_stop_scan(void){
6342     hci_stack->le_scanning_enabled = false;
6343     hci_run();
6344 }
6345 
6346 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
6347     hci_stack->le_scan_type          = scan_type;
6348     hci_stack->le_scan_filter_policy = scanning_filter_policy;
6349     hci_stack->le_scan_interval      = scan_interval;
6350     hci_stack->le_scan_window        = scan_window;
6351     hci_stack->le_scanning_param_update = true;
6352     hci_run();
6353 }
6354 
6355 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
6356     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
6357 }
6358 
6359 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
6360     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
6361     if (!conn){
6362         // disallow if le connection is already outgoing
6363         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6364             log_error("le connection already active");
6365             return ERROR_CODE_COMMAND_DISALLOWED;
6366         }
6367 
6368         log_info("gap_connect: no connection exists yet, creating context");
6369         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
6370         if (!conn){
6371             // notify client that alloc failed
6372             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6373             log_info("gap_connect: failed to alloc hci_connection_t");
6374             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
6375         }
6376 
6377         // set le connecting state
6378         if (hci_is_le_connection_type(addr_type)){
6379             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
6380         }
6381 
6382         conn->state = SEND_CREATE_CONNECTION;
6383         log_info("gap_connect: send create connection next");
6384         hci_run();
6385         return ERROR_CODE_SUCCESS;
6386     }
6387 
6388     if (!hci_is_le_connection(conn) ||
6389         (conn->state == SEND_CREATE_CONNECTION) ||
6390         (conn->state == SENT_CREATE_CONNECTION)) {
6391         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
6392         log_error("gap_connect: classic connection or connect is already being created");
6393         return GATT_CLIENT_IN_WRONG_STATE;
6394     }
6395 
6396     // check if connection was just disconnected
6397     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
6398         log_info("gap_connect: send create connection (again)");
6399         conn->state = SEND_CREATE_CONNECTION;
6400         hci_run();
6401         return ERROR_CODE_SUCCESS;
6402     }
6403 
6404     log_info("gap_connect: context exists with state %u", conn->state);
6405     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
6406     hci_run();
6407     return ERROR_CODE_SUCCESS;
6408 }
6409 
6410 // @assumption: only a single outgoing LE Connection exists
6411 static hci_connection_t * gap_get_outgoing_connection(void){
6412     btstack_linked_item_t *it;
6413     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6414         hci_connection_t * conn = (hci_connection_t *) it;
6415         if (!hci_is_le_connection(conn)) continue;
6416         switch (conn->state){
6417             case SEND_CREATE_CONNECTION:
6418             case SENT_CREATE_CONNECTION:
6419             case SENT_CANCEL_CONNECTION:
6420                 return conn;
6421             default:
6422                 break;
6423         };
6424     }
6425     return NULL;
6426 }
6427 
6428 uint8_t gap_connect_cancel(void){
6429     hci_connection_t * conn = gap_get_outgoing_connection();
6430     if (!conn) return 0;
6431     switch (conn->state){
6432         case SEND_CREATE_CONNECTION:
6433             // skip sending create connection and emit event instead
6434             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6435             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
6436             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
6437             btstack_memory_hci_connection_free( conn );
6438             break;
6439         case SENT_CREATE_CONNECTION:
6440             // request to send cancel connection
6441             conn->state = SEND_CANCEL_CONNECTION;
6442             hci_run();
6443             break;
6444         default:
6445             break;
6446     }
6447     return 0;
6448 }
6449 
6450 /**
6451  * @brief Set connection parameters for outgoing connections
6452  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
6453  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
6454  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
6455  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
6456  * @param conn_latency, default: 4
6457  * @param supervision_timeout (unit: 10ms), default: 720 ms
6458  * @param min_ce_length (unit: 0.625ms), default: 10 ms
6459  * @param max_ce_length (unit: 0.625ms), default: 30 ms
6460  */
6461 
6462 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
6463     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
6464     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
6465     hci_stack->le_connection_scan_interval = conn_scan_interval;
6466     hci_stack->le_connection_scan_window = conn_scan_window;
6467     hci_stack->le_connection_interval_min = conn_interval_min;
6468     hci_stack->le_connection_interval_max = conn_interval_max;
6469     hci_stack->le_connection_latency = conn_latency;
6470     hci_stack->le_supervision_timeout = supervision_timeout;
6471     hci_stack->le_minimum_ce_length = min_ce_length;
6472     hci_stack->le_maximum_ce_length = max_ce_length;
6473 }
6474 #endif
6475 
6476 /**
6477  * @brief Updates the connection parameters for a given LE connection
6478  * @param handle
6479  * @param conn_interval_min (unit: 1.25ms)
6480  * @param conn_interval_max (unit: 1.25ms)
6481  * @param conn_latency
6482  * @param supervision_timeout (unit: 10ms)
6483  * @return 0 if ok
6484  */
6485 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6486     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6487     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6488     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6489     connection->le_conn_interval_min = conn_interval_min;
6490     connection->le_conn_interval_max = conn_interval_max;
6491     connection->le_conn_latency = conn_latency;
6492     connection->le_supervision_timeout = supervision_timeout;
6493     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
6494     hci_run();
6495     return 0;
6496 }
6497 
6498 /**
6499  * @brief Request an update of the connection parameter for a given LE connection
6500  * @param handle
6501  * @param conn_interval_min (unit: 1.25ms)
6502  * @param conn_interval_max (unit: 1.25ms)
6503  * @param conn_latency
6504  * @param supervision_timeout (unit: 10ms)
6505  * @return 0 if ok
6506  */
6507 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6508     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6509     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6510     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6511     connection->le_conn_interval_min = conn_interval_min;
6512     connection->le_conn_interval_max = conn_interval_max;
6513     connection->le_conn_latency = conn_latency;
6514     connection->le_supervision_timeout = supervision_timeout;
6515     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
6516     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
6517     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
6518     return 0;
6519 }
6520 
6521 #ifdef ENABLE_LE_PERIPHERAL
6522 
6523 /**
6524  * @brief Set Advertisement Data
6525  * @param advertising_data_length
6526  * @param advertising_data (max 31 octets)
6527  * @note data is not copied, pointer has to stay valid
6528  */
6529 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
6530     hci_stack->le_advertisements_data_len = advertising_data_length;
6531     hci_stack->le_advertisements_data = advertising_data;
6532     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6533     hci_run();
6534 }
6535 
6536 /**
6537  * @brief Set Scan Response Data
6538  * @param advertising_data_length
6539  * @param advertising_data (max 31 octets)
6540  * @note data is not copied, pointer has to stay valid
6541  */
6542 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
6543     hci_stack->le_scan_response_data_len = scan_response_data_length;
6544     hci_stack->le_scan_response_data = scan_response_data;
6545     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6546     hci_run();
6547 }
6548 
6549 /**
6550  * @brief Set Advertisement Parameters
6551  * @param adv_int_min
6552  * @param adv_int_max
6553  * @param adv_type
6554  * @param direct_address_type
6555  * @param direct_address
6556  * @param channel_map
6557  * @param filter_policy
6558  *
6559  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
6560  */
6561  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
6562     uint8_t direct_address_typ, bd_addr_t direct_address,
6563     uint8_t channel_map, uint8_t filter_policy) {
6564 
6565     hci_stack->le_advertisements_interval_min = adv_int_min;
6566     hci_stack->le_advertisements_interval_max = adv_int_max;
6567     hci_stack->le_advertisements_type = adv_type;
6568     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
6569     hci_stack->le_advertisements_channel_map = channel_map;
6570     hci_stack->le_advertisements_filter_policy = filter_policy;
6571     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
6572                  6);
6573 
6574     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6575     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
6576     hci_run();
6577  }
6578 
6579 /**
6580  * @brief Enable/Disable Advertisements
6581  * @param enabled
6582  */
6583 void gap_advertisements_enable(int enabled){
6584     if (enabled == 0){
6585         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
6586     } else {
6587         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
6588     }
6589     hci_update_advertisements_enabled_for_current_roles();
6590     hci_run();
6591 }
6592 
6593 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6594 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
6595     btstack_linked_list_iterator_t it;
6596     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6597     while (btstack_linked_list_iterator_has_next(&it)){
6598         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6599         if ( item->advertising_handle == advertising_handle ) {
6600             return item;
6601         }
6602     }
6603     return NULL;
6604 }
6605 
6606 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
6607     // find free advertisement handle
6608     uint8_t advertisement_handle;
6609     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
6610         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
6611     }
6612     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
6613     // clear
6614     memset(storage, 0, sizeof(le_advertising_set_t));
6615     // copy params
6616     memcpy(&storage->params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
6617     // add to list
6618     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
6619     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6620     // set tasks and start
6621     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6622     hci_run();
6623     return ERROR_CODE_SUCCESS;
6624 }
6625 
6626 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
6627     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6628     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6629     memcpy(&advertising_set->params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
6630     // set tasks and start
6631     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6632     hci_run();
6633     return ERROR_CODE_SUCCESS;
6634 }
6635 
6636 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
6637     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6638     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6639     memcpy(advertising_parameters, &advertising_set->params, sizeof(le_extended_advertising_parameters_t));
6640     return ERROR_CODE_SUCCESS;
6641 }
6642 
6643 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
6644     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6645     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6646     memcpy(advertising_set->random_address, random_address, 6);
6647     // set tasks and start
6648     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6649     hci_run();
6650     return ERROR_CODE_SUCCESS;
6651 }
6652 
6653 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, uint8_t * advertising_data){
6654     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6655     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6656     advertising_set->adv_data = advertising_data;
6657     advertising_set->adv_data_len = advertising_data_length;
6658     // set tasks and start
6659     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6660     hci_run();
6661     return ERROR_CODE_SUCCESS;
6662 }
6663 
6664 uint8_t gap_extended_advertising_set_scan_response_data(uint8_t advertising_handle, uint16_t scan_response_data_length, uint8_t * scan_response_data){
6665     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6666     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6667     advertising_set->scan_data = scan_response_data;
6668     advertising_set->scan_data_len = scan_response_data_length;
6669     // set tasks and start
6670     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6671     hci_run();
6672     return ERROR_CODE_SUCCESS;
6673 }
6674 
6675 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
6676     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6677     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6678     advertising_set->enable_timeout = timeout;
6679     advertising_set->enable_max_scan_events = num_extended_advertising_events;
6680     // set tasks and start
6681     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
6682     hci_run();
6683     return ERROR_CODE_SUCCESS;
6684 }
6685 
6686 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
6687     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6688     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6689     // set tasks and start
6690     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
6691     hci_run();
6692     return ERROR_CODE_SUCCESS;
6693 }
6694 
6695 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
6696     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
6697     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6698     // set tasks and start
6699     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6700     hci_run();
6701     return ERROR_CODE_SUCCESS;
6702 }
6703 #endif
6704 
6705 #endif
6706 
6707 void hci_le_set_own_address_type(uint8_t own_address_type){
6708     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
6709     if (own_address_type == hci_stack->le_own_addr_type) return;
6710     hci_stack->le_own_addr_type = own_address_type;
6711 
6712 #ifdef ENABLE_LE_PERIPHERAL
6713     // update advertisement parameters, too
6714     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6715     hci_run();
6716 #endif
6717 #ifdef ENABLE_LE_CENTRAL
6718     // note: we don't update scan parameters or modify ongoing connection attempts
6719 #endif
6720 }
6721 
6722 void hci_le_random_address_set(const bd_addr_t random_address){
6723     memcpy(hci_stack->le_random_address, random_address, 6);
6724     hci_stack->le_random_address_set = true;
6725     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6726     hci_run();
6727 }
6728 
6729 #endif
6730 
6731 uint8_t gap_disconnect(hci_con_handle_t handle){
6732     hci_connection_t * conn = hci_connection_for_handle(handle);
6733     if (!conn){
6734         hci_emit_disconnection_complete(handle, 0);
6735         return 0;
6736     }
6737     // ignore if already disconnected
6738     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
6739         return 0;
6740     }
6741     conn->state = SEND_DISCONNECT;
6742     hci_run();
6743     return 0;
6744 }
6745 
6746 int gap_read_rssi(hci_con_handle_t con_handle){
6747     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6748     if (hci_connection == NULL) return 0;
6749     connectionSetAuthenticationFlags(hci_connection, AUTH_FLAG_READ_RSSI);
6750     hci_run();
6751     return 1;
6752 }
6753 
6754 /**
6755  * @brief Get connection type
6756  * @param con_handle
6757  * @result connection_type
6758  */
6759 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
6760     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6761     if (!conn) return GAP_CONNECTION_INVALID;
6762     switch (conn->address_type){
6763         case BD_ADDR_TYPE_LE_PUBLIC:
6764         case BD_ADDR_TYPE_LE_RANDOM:
6765             return GAP_CONNECTION_LE;
6766         case BD_ADDR_TYPE_SCO:
6767             return GAP_CONNECTION_SCO;
6768         case BD_ADDR_TYPE_ACL:
6769             return GAP_CONNECTION_ACL;
6770         default:
6771             return GAP_CONNECTION_INVALID;
6772     }
6773 }
6774 
6775 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
6776     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6777     if (!conn) return HCI_ROLE_INVALID;
6778     return (hci_role_t) conn->role;
6779 }
6780 
6781 
6782 #ifdef ENABLE_CLASSIC
6783 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
6784     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6785     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6786     conn->request_role = role;
6787     hci_run();
6788     return ERROR_CODE_SUCCESS;
6789 }
6790 #endif
6791 
6792 #ifdef ENABLE_BLE
6793 
6794 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){
6795     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6796     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6797 
6798     conn->le_phy_update_all_phys    = all_phys;
6799     conn->le_phy_update_tx_phys     = tx_phys;
6800     conn->le_phy_update_rx_phys     = rx_phys;
6801     conn->le_phy_update_phy_options = phy_options;
6802 
6803     hci_run();
6804 
6805     return 0;
6806 }
6807 
6808 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6809     // check if already in list
6810     btstack_linked_list_iterator_t it;
6811     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6812     while (btstack_linked_list_iterator_has_next(&it)) {
6813         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
6814         if (entry->address_type != address_type) {
6815             continue;
6816         }
6817         if (memcmp(entry->address, address, 6) != 0) {
6818             continue;
6819         }
6820 		// disallow if already scheduled to add
6821 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
6822 			return ERROR_CODE_COMMAND_DISALLOWED;
6823 		}
6824 		// still on controller, but scheduled to remove -> re-add
6825 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
6826 		return ERROR_CODE_SUCCESS;
6827     }
6828     // alloc and add to list
6829     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
6830     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
6831     entry->address_type = address_type;
6832     (void)memcpy(entry->address, address, 6);
6833     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
6834     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
6835     return ERROR_CODE_SUCCESS;
6836 }
6837 
6838 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6839     btstack_linked_list_iterator_t it;
6840     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6841     while (btstack_linked_list_iterator_has_next(&it)){
6842         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6843         if (entry->address_type != address_type) {
6844             continue;
6845         }
6846         if (memcmp(entry->address, address, 6) != 0) {
6847             continue;
6848         }
6849         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6850             // remove from controller if already present
6851             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6852         }  else {
6853             // directly remove entry from whitelist
6854             btstack_linked_list_iterator_remove(&it);
6855             btstack_memory_whitelist_entry_free(entry);
6856         }
6857         return ERROR_CODE_SUCCESS;
6858     }
6859     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6860 }
6861 
6862 static void hci_whitelist_clear(void){
6863     btstack_linked_list_iterator_t it;
6864     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6865     while (btstack_linked_list_iterator_has_next(&it)){
6866         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6867         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6868             // remove from controller if already present
6869             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6870             continue;
6871         }
6872         // directly remove entry from whitelist
6873         btstack_linked_list_iterator_remove(&it);
6874         btstack_memory_whitelist_entry_free(entry);
6875     }
6876 }
6877 
6878 // free all entries unconditionally
6879 static void hci_whitelist_free(void){
6880     btstack_linked_list_iterator_t lit;
6881     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6882     while (btstack_linked_list_iterator_has_next(&lit)){
6883         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6884         btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6885         btstack_memory_whitelist_entry_free(entry);
6886     }
6887 }
6888 
6889 /**
6890  * @brief Clear Whitelist
6891  * @return 0 if ok
6892  */
6893 uint8_t gap_whitelist_clear(void){
6894     hci_whitelist_clear();
6895     hci_run();
6896     return ERROR_CODE_SUCCESS;
6897 }
6898 
6899 /**
6900  * @brief Add Device to Whitelist
6901  * @param address_typ
6902  * @param address
6903  * @return 0 if ok
6904  */
6905 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6906     uint8_t status = hci_whitelist_add(address_type, address);
6907     if (status){
6908         return status;
6909     }
6910     hci_run();
6911     return ERROR_CODE_SUCCESS;
6912 }
6913 
6914 /**
6915  * @brief Remove Device from Whitelist
6916  * @param address_typ
6917  * @param address
6918  * @return 0 if ok
6919  */
6920 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6921     uint8_t status = hci_whitelist_remove(address_type, address);
6922     if (status){
6923         return status;
6924     }
6925     hci_run();
6926     return ERROR_CODE_SUCCESS;
6927 }
6928 
6929 #ifdef ENABLE_LE_CENTRAL
6930 /**
6931  * @brief Connect with Whitelist
6932  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
6933  * @return - if ok
6934  */
6935 uint8_t gap_connect_with_whitelist(void){
6936     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6937         return ERROR_CODE_COMMAND_DISALLOWED;
6938     }
6939     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6940     hci_run();
6941     return ERROR_CODE_SUCCESS;
6942 }
6943 
6944 /**
6945  * @brief Auto Connection Establishment - Start Connecting to device
6946  * @param address_typ
6947  * @param address
6948  * @return 0 if ok
6949  */
6950 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
6951     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6952         return ERROR_CODE_COMMAND_DISALLOWED;
6953     }
6954 
6955     uint8_t status = hci_whitelist_add(address_type, address);
6956     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
6957         return status;
6958     }
6959 
6960     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6961 
6962     hci_run();
6963     return ERROR_CODE_SUCCESS;
6964 }
6965 
6966 /**
6967  * @brief Auto Connection Establishment - Stop Connecting to device
6968  * @param address_typ
6969  * @param address
6970  * @return 0 if ok
6971  */
6972 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
6973     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6974         return ERROR_CODE_COMMAND_DISALLOWED;
6975     }
6976 
6977     hci_whitelist_remove(address_type, address);
6978     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
6979         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6980     }
6981     hci_run();
6982     return 0;
6983 }
6984 
6985 /**
6986  * @brief Auto Connection Establishment - Stop everything
6987  * @note  Convenience function to stop all active auto connection attempts
6988  */
6989 uint8_t gap_auto_connection_stop_all(void){
6990     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
6991         return ERROR_CODE_COMMAND_DISALLOWED;
6992     }
6993     hci_whitelist_clear();
6994     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6995     hci_run();
6996     return ERROR_CODE_SUCCESS;
6997 }
6998 
6999 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
7000     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7001     if (!conn) return 0;
7002     return conn->le_connection_interval;
7003 }
7004 #endif
7005 #endif
7006 
7007 #ifdef ENABLE_CLASSIC
7008 /**
7009  * @brief Set Extended Inquiry Response data
7010  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
7011  * @note has to be done before stack starts up
7012  */
7013 void gap_set_extended_inquiry_response(const uint8_t * data){
7014     hci_stack->eir_data = data;
7015     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7016     hci_run();
7017 }
7018 
7019 /**
7020  * @brief Start GAP Classic Inquiry
7021  * @param duration in 1.28s units
7022  * @return 0 if ok
7023  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
7024  */
7025 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
7026     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
7027     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7028     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
7029         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7030     }
7031     hci_stack->inquiry_state = duration_in_1280ms_units;
7032     hci_run();
7033     return 0;
7034 }
7035 
7036 /**
7037  * @brief Stop GAP Classic Inquiry
7038  * @return 0 if ok
7039  */
7040 int gap_inquiry_stop(void){
7041     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
7042         // emit inquiry complete event, before it even started
7043         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
7044         hci_emit_event(event, sizeof(event), 1);
7045         return 0;
7046     }
7047     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
7048     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
7049     hci_run();
7050     return 0;
7051 }
7052 
7053 void gap_inquiry_set_lap(uint32_t lap){
7054     hci_stack->inquiry_lap = lap;
7055 }
7056 
7057 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
7058     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
7059     hci_stack->inquiry_scan_window   = inquiry_scan_window;
7060     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
7061     hci_run();
7062 }
7063 
7064 
7065 /**
7066  * @brief Remote Name Request
7067  * @param addr
7068  * @param page_scan_repetition_mode
7069  * @param clock_offset only used when bit 15 is set
7070  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
7071  */
7072 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
7073     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7074     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
7075     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
7076     hci_stack->remote_name_clock_offset = clock_offset;
7077     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
7078     hci_run();
7079     return 0;
7080 }
7081 
7082 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
7083     hci_stack->gap_pairing_state = state;
7084     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
7085     hci_run();
7086     return 0;
7087 }
7088 
7089 /**
7090  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
7091  * @param addr
7092  * @param pin_data
7093  * @param pin_len
7094  * @return 0 if ok
7095  */
7096 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
7097     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7098     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
7099     hci_stack->gap_pairing_pin_len = pin_len;
7100     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
7101 }
7102 
7103 /**
7104  * @brief Legacy Pairing Pin Code Response
7105  * @param addr
7106  * @param pin
7107  * @return 0 if ok
7108  */
7109 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
7110     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
7111 }
7112 
7113 /**
7114  * @brief Abort Legacy Pairing
7115  * @param addr
7116  * @param pin
7117  * @return 0 if ok
7118  */
7119 int gap_pin_code_negative(bd_addr_t addr){
7120     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7121     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
7122 }
7123 
7124 /**
7125  * @brief SSP Passkey Response
7126  * @param addr
7127  * @param passkey
7128  * @return 0 if ok
7129  */
7130 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
7131     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7132     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
7133     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
7134 }
7135 
7136 /**
7137  * @brief Abort SSP Passkey Entry/Pairing
7138  * @param addr
7139  * @param pin
7140  * @return 0 if ok
7141  */
7142 int gap_ssp_passkey_negative(const bd_addr_t addr){
7143     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7144     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
7145 }
7146 
7147 /**
7148  * @brief Accept SSP Numeric Comparison
7149  * @param addr
7150  * @param passkey
7151  * @return 0 if ok
7152  */
7153 int gap_ssp_confirmation_response(const bd_addr_t addr){
7154     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7155     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
7156 }
7157 
7158 /**
7159  * @brief Abort SSP Numeric Comparison/Pairing
7160  * @param addr
7161  * @param pin
7162  * @return 0 if ok
7163  */
7164 int gap_ssp_confirmation_negative(const bd_addr_t addr){
7165     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7166     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
7167 }
7168 
7169 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
7170 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
7171     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7172     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7173     connectionSetAuthenticationFlags(conn, flag);
7174     hci_run();
7175     return ERROR_CODE_SUCCESS;
7176 }
7177 #endif
7178 
7179 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
7180 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
7181     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7182 }
7183 
7184 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
7185     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
7186 }
7187 #endif
7188 
7189 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7190 /**
7191  * @brief Report Remote OOB Data
7192  * @param bd_addr
7193  * @param c_192 Simple Pairing Hash C derived from P-192 public key
7194  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
7195  * @param c_256 Simple Pairing Hash C derived from P-256 public key
7196  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
7197  */
7198 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){
7199     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7200     if (connection == NULL) {
7201         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7202     }
7203     connection->classic_oob_c_192 = c_192;
7204     connection->classic_oob_r_192 = r_192;
7205 
7206     // ignore P-256 if not supported by us
7207     if (hci_stack->secure_connections_active){
7208         connection->classic_oob_c_256 = c_256;
7209         connection->classic_oob_r_256 = r_256;
7210     }
7211 
7212     return ERROR_CODE_SUCCESS;
7213 }
7214 /**
7215  * @brief Generate new OOB data
7216  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
7217  */
7218 void gap_ssp_generate_oob_data(void){
7219     hci_stack->classic_read_local_oob_data = true;
7220     hci_run();
7221 }
7222 
7223 #endif
7224 
7225 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
7226 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
7227     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7228     if (connection == NULL) {
7229         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7230     }
7231 
7232     memcpy(connection->link_key, link_key, sizeof(link_key_t));
7233     connection->link_key_type = type;
7234 
7235     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
7236 }
7237 
7238 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
7239 /**
7240  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
7241  * @param inquiry_mode see bluetooth_defines.h
7242  */
7243 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
7244     hci_stack->inquiry_mode = inquiry_mode;
7245 }
7246 
7247 /**
7248  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
7249  */
7250 void hci_set_sco_voice_setting(uint16_t voice_setting){
7251     hci_stack->sco_voice_setting = voice_setting;
7252 }
7253 
7254 /**
7255  * @brief Get SCO Voice Setting
7256  * @return current voice setting
7257  */
7258 uint16_t hci_get_sco_voice_setting(void){
7259     return hci_stack->sco_voice_setting;
7260 }
7261 
7262 static int hci_have_usb_transport(void){
7263     if (!hci_stack->hci_transport) return 0;
7264     const char * transport_name = hci_stack->hci_transport->name;
7265     if (!transport_name) return 0;
7266     return (transport_name[0] == 'H') && (transport_name[1] == '2');
7267 }
7268 
7269 /** @brief Get SCO packet length for current SCO Voice setting
7270  *  @note  Using SCO packets of the exact length is required for USB transfer
7271  *  @return Length of SCO packets in bytes (not audio frames)
7272  */
7273 uint16_t hci_get_sco_packet_length(void){
7274     uint16_t sco_packet_length = 0;
7275 
7276 #ifdef ENABLE_SCO_OVER_HCI
7277     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
7278     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
7279 
7280     if (hci_have_usb_transport()){
7281         // see Core Spec for H2 USB Transfer.
7282         // 3 byte SCO header + 24 bytes per connection
7283         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
7284         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
7285     } else {
7286         // 3 byte SCO header + SCO packet size over the air (60 bytes)
7287         sco_packet_length = 3 + 60 * multiplier;
7288         // assert that it still fits inside an SCO buffer
7289         if (sco_packet_length > hci_stack->sco_data_packet_length){
7290             sco_packet_length = 3 + 60;
7291         }
7292     }
7293 #endif
7294 
7295 #ifdef HAVE_SCO_TRANSPORT
7296     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
7297     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
7298     sco_packet_length = 3 + 60 * multiplier;
7299 #endif
7300     return sco_packet_length;
7301 }
7302 
7303 /**
7304 * @brief Sets the master/slave policy
7305 * @param policy (0: attempt to become master, 1: let connecting device decide)
7306 */
7307 void hci_set_master_slave_policy(uint8_t policy){
7308     hci_stack->master_slave_policy = policy;
7309 }
7310 
7311 #endif
7312 
7313 HCI_STATE hci_get_state(void){
7314     return hci_stack->state;
7315 }
7316 
7317 #ifdef ENABLE_CLASSIC
7318 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
7319     hci_stack->gap_classic_accept_callback = accept_callback;
7320 }
7321 #endif
7322 
7323 /**
7324  * @brief Set callback for Bluetooth Hardware Error
7325  */
7326 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
7327     hci_stack->hardware_error_callback = fn;
7328 }
7329 
7330 void hci_disconnect_all(void){
7331     btstack_linked_list_iterator_t it;
7332     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
7333     while (btstack_linked_list_iterator_has_next(&it)){
7334         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
7335         if (con->state == SENT_DISCONNECT) continue;
7336         con->state = SEND_DISCONNECT;
7337     }
7338     hci_run();
7339 }
7340 
7341 uint16_t hci_get_manufacturer(void){
7342     return hci_stack->manufacturer;
7343 }
7344 
7345 #ifdef ENABLE_BLE
7346 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
7347     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
7348     if (!hci_con) return NULL;
7349     return &hci_con->sm_connection;
7350 }
7351 
7352 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
7353 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
7354 #endif
7355 
7356 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
7357     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7358     if (hci_connection == NULL) return 0;
7359     if (hci_is_le_connection(hci_connection)){
7360 #ifdef ENABLE_BLE
7361         sm_connection_t * sm_conn = &hci_connection->sm_connection;
7362         if (sm_conn->sm_connection_encrypted) {
7363             return sm_conn->sm_actual_encryption_key_size;
7364         }
7365 #endif
7366     } else {
7367 #ifdef ENABLE_CLASSIC
7368         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
7369             return hci_connection->encryption_key_size;
7370         }
7371 #endif
7372     }
7373     return 0;
7374 }
7375 
7376 bool gap_authenticated(hci_con_handle_t con_handle){
7377     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7378     if (hci_connection == NULL) return false;
7379 
7380     switch (hci_connection->address_type){
7381 #ifdef ENABLE_BLE
7382         case BD_ADDR_TYPE_LE_PUBLIC:
7383         case BD_ADDR_TYPE_LE_RANDOM:
7384             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
7385             return hci_connection->sm_connection.sm_connection_authenticated != 0;
7386 #endif
7387 #ifdef ENABLE_CLASSIC
7388         case BD_ADDR_TYPE_SCO:
7389         case BD_ADDR_TYPE_ACL:
7390             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
7391 #endif
7392         default:
7393             return false;
7394     }
7395 }
7396 
7397 bool gap_secure_connection(hci_con_handle_t con_handle){
7398     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7399     if (hci_connection == NULL) return 0;
7400 
7401     switch (hci_connection->address_type){
7402 #ifdef ENABLE_BLE
7403         case BD_ADDR_TYPE_LE_PUBLIC:
7404         case BD_ADDR_TYPE_LE_RANDOM:
7405             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
7406             return hci_connection->sm_connection.sm_connection_sc != 0;
7407 #endif
7408 #ifdef ENABLE_CLASSIC
7409         case BD_ADDR_TYPE_SCO:
7410         case BD_ADDR_TYPE_ACL:
7411             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
7412 #endif
7413         default:
7414             return false;
7415     }
7416 }
7417 
7418 bool gap_bonded(hci_con_handle_t con_handle){
7419 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7420 	if (hci_connection == NULL) return 0;
7421 
7422 #ifdef ENABLE_CLASSIC
7423 	link_key_t link_key;
7424 	link_key_type_t link_key_type;
7425 #endif
7426 	switch (hci_connection->address_type){
7427 #ifdef ENABLE_BLE
7428 		case BD_ADDR_TYPE_LE_PUBLIC:
7429 		case BD_ADDR_TYPE_LE_RANDOM:
7430 			return hci_connection->sm_connection.sm_le_db_index >= 0;
7431 #endif
7432 #ifdef ENABLE_CLASSIC
7433 		case BD_ADDR_TYPE_SCO:
7434 		case BD_ADDR_TYPE_ACL:
7435 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
7436 #endif
7437 		default:
7438 			return false;
7439 	}
7440 }
7441 
7442 #ifdef ENABLE_BLE
7443 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
7444     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
7445     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
7446     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
7447     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
7448     return sm_conn->sm_connection_authorization_state;
7449 }
7450 #endif
7451 
7452 #ifdef ENABLE_CLASSIC
7453 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){
7454     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7455     if (!conn) return GAP_CONNECTION_INVALID;
7456     conn->sniff_min_interval = sniff_min_interval;
7457     conn->sniff_max_interval = sniff_max_interval;
7458     conn->sniff_attempt = sniff_attempt;
7459     conn->sniff_timeout = sniff_timeout;
7460     hci_run();
7461     return 0;
7462 }
7463 
7464 /**
7465  * @brief Exit Sniff mode
7466  * @param con_handle
7467  @ @return 0 if ok
7468  */
7469 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
7470     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7471     if (!conn) return GAP_CONNECTION_INVALID;
7472     conn->sniff_min_interval = 0xffff;
7473     hci_run();
7474     return 0;
7475 }
7476 
7477 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){
7478     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7479     if (!conn) return GAP_CONNECTION_INVALID;
7480     conn->sniff_subrating_max_latency = max_latency;
7481     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
7482     conn->sniff_subrating_min_local_timeout = min_local_timeout;
7483     hci_run();
7484     return ERROR_CODE_SUCCESS;
7485 }
7486 
7487 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){
7488     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7489     if (!conn) return GAP_CONNECTION_INVALID;
7490     conn->qos_service_type = service_type;
7491     conn->qos_token_rate = token_rate;
7492     conn->qos_peak_bandwidth = peak_bandwidth;
7493     conn->qos_latency = latency;
7494     conn->qos_delay_variation = delay_variation;
7495     hci_run();
7496     return ERROR_CODE_SUCCESS;
7497 }
7498 
7499 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
7500     hci_stack->new_page_scan_interval = page_scan_interval;
7501     hci_stack->new_page_scan_window = page_scan_window;
7502     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
7503     hci_run();
7504 }
7505 
7506 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
7507     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
7508     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
7509     hci_run();
7510 }
7511 
7512 void gap_set_page_timeout(uint16_t page_timeout){
7513     hci_stack->page_timeout = page_timeout;
7514     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
7515     hci_run();
7516 }
7517 
7518 #endif
7519 
7520 void hci_halting_defer(void){
7521     if (hci_stack->state != HCI_STATE_HALTING) return;
7522     switch (hci_stack->substate){
7523         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
7524         case HCI_HALTING_CLOSE:
7525             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
7526             break;
7527         default:
7528             break;
7529     }
7530 }
7531 
7532 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
7533 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
7534     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
7535     if (le_device_db_index >= le_device_db_max_count()) return;
7536     uint8_t offset = le_device_db_index >> 3;
7537     uint8_t mask = 1 << (le_device_db_index & 7);
7538     hci_stack->le_resolving_list_add_entries[offset] |= mask;
7539     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
7540     	// note: go back to remove entries, otherwise, a remove + add will skip the add
7541         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
7542     }
7543 }
7544 
7545 void hci_remove_le_device_db_entry_from_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_remove_entries[offset] |= mask;
7551 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
7552 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
7553 	}
7554 }
7555 
7556 uint8_t gap_load_resolving_list_from_le_device_db(void){
7557     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
7558 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
7559 	}
7560 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
7561 		// restart le resolving list update
7562 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
7563 	}
7564 	return ERROR_CODE_SUCCESS;
7565 }
7566 #endif
7567 
7568 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
7569 void hci_setup_test_connections_fuzz(void){
7570     hci_connection_t * conn;
7571 
7572     // default address: 66:55:44:33:00:01
7573     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
7574 
7575     // setup Controller info
7576     hci_stack->num_cmd_packets = 255;
7577     hci_stack->acl_packets_total_num = 255;
7578 
7579     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
7580     addr[5] = 0x01;
7581     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7582     conn->con_handle = addr[5];
7583     conn->role  = HCI_ROLE_SLAVE;
7584     conn->state = RECEIVED_CONNECTION_REQUEST;
7585     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7586 
7587     // setup incoming Classic SCO connection with con handle 0x0002
7588     addr[5] = 0x02;
7589     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
7590     conn->con_handle = addr[5];
7591     conn->role  = HCI_ROLE_SLAVE;
7592     conn->state = RECEIVED_CONNECTION_REQUEST;
7593     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7594 
7595     // setup ready Classic ACL connection with con handle 0x0003
7596     addr[5] = 0x03;
7597     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7598     conn->con_handle = addr[5];
7599     conn->role  = HCI_ROLE_SLAVE;
7600     conn->state = OPEN;
7601     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7602 
7603     // setup ready Classic SCO connection with con handle 0x0004
7604     addr[5] = 0x04;
7605     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
7606     conn->con_handle = addr[5];
7607     conn->role  = HCI_ROLE_SLAVE;
7608     conn->state = OPEN;
7609     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7610 
7611     // setup ready LE ACL connection with con handle 0x005 and public address
7612     addr[5] = 0x05;
7613     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
7614     conn->con_handle = addr[5];
7615     conn->role  = HCI_ROLE_SLAVE;
7616     conn->state = OPEN;
7617     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
7618     conn->sm_connection.sm_connection_encrypted = 1;
7619 }
7620 
7621 void hci_free_connections_fuzz(void){
7622     btstack_linked_list_iterator_t it;
7623     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
7624     while (btstack_linked_list_iterator_has_next(&it)){
7625         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
7626         btstack_linked_list_iterator_remove(&it);
7627         btstack_memory_hci_connection_free(con);
7628     }
7629 }
7630 void hci_simulate_working_fuzz(void){
7631     hci_stack->le_scanning_param_update = false;
7632     hci_init_done();
7633     hci_stack->num_cmd_packets = 255;
7634 }
7635 #endif
7636