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