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