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