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