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