xref: /btstack/src/hci.c (revision d90722d454a027a73a0561873342f97012ce96a5)
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_CONTROLLER_DUMP_PACKETS
78 #include <stdio.h>  // sprintf
79 #endif
80 
81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
82 #ifndef HCI_HOST_ACL_PACKET_NUM
83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
84 #endif
85 #ifndef HCI_HOST_ACL_PACKET_LEN
86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
87 #endif
88 #ifndef HCI_HOST_SCO_PACKET_NUM
89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
90 #endif
91 #ifndef HCI_HOST_SCO_PACKET_LEN
92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
93 #endif
94 #endif
95 
96 #ifndef MAX_NR_CONTROLLER_ACL_BUFFERS
97 #define MAX_NR_CONTROLLER_ACL_BUFFERS 255
98 #endif
99 #ifndef MAX_NR_CONTROLLER_SCO_PACKETS
100 #define MAX_NR_CONTROLLER_SCO_PACKETS 255
101 #endif
102 
103 #ifndef HCI_ACL_CHUNK_SIZE_ALIGNMENT
104 #define HCI_ACL_CHUNK_SIZE_ALIGNMENT 1
105 #endif
106 
107 #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
108 #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."
109 #endif
110 
111 #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT)
112 #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."
113 #endif
114 
115 #define HCI_CONNECTION_TIMEOUT_MS 10000
116 
117 #ifndef HCI_RESET_RESEND_TIMEOUT_MS
118 #define HCI_RESET_RESEND_TIMEOUT_MS 200
119 #endif
120 
121 // Names are arbitrarily shortened to 32 bytes if not requested otherwise
122 #ifndef GAP_INQUIRY_MAX_NAME_LEN
123 #define GAP_INQUIRY_MAX_NAME_LEN 32
124 #endif
125 
126 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
127 #define GAP_INQUIRY_DURATION_MIN       0x01
128 #define GAP_INQUIRY_DURATION_MAX       0x30
129 #define GAP_INQUIRY_MIN_PERIODIC_LEN_MIN 0x02
130 #define GAP_INQUIRY_MAX_PERIODIC_LEN_MIN 0x03
131 #define GAP_INQUIRY_STATE_IDLE         0x00
132 #define GAP_INQUIRY_STATE_W4_ACTIVE    0x80
133 #define GAP_INQUIRY_STATE_ACTIVE       0x81
134 #define GAP_INQUIRY_STATE_W2_CANCEL    0x82
135 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83
136 #define GAP_INQUIRY_STATE_PERIODIC     0x84
137 #define GAP_INQUIRY_STATE_W2_EXIT_PERIODIC 0x85
138 
139 // GAP Remote Name Request
140 #define GAP_REMOTE_NAME_STATE_IDLE 0
141 #define GAP_REMOTE_NAME_STATE_W2_SEND 1
142 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
143 
144 // GAP Pairing
145 #define GAP_PAIRING_STATE_IDLE                       0
146 #define GAP_PAIRING_STATE_SEND_PIN                   1
147 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
148 #define GAP_PAIRING_STATE_SEND_PASSKEY               3
149 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
150 #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
151 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
152 #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE  7
153 
154 //
155 // compact storage of relevant supported HCI Commands.
156 // X-Macro below provides enumeration and mapping table into the supported
157 // commands bitmap (64 bytes) from HCI Read Local Supported Commands
158 //
159 
160 // format: command name, byte offset, bit nr in 64-byte supported commands
161 // currently stored in 32-bit variable
162 #define SUPPORTED_HCI_COMMANDS \
163     X( SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES         ,  2, 5) \
164     X( SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE , 10, 4) \
165     X( SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE                      , 14, 7) \
166     X( SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, 18, 3) \
167     X( SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE              , 20, 4) \
168     X( SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2                 , 22, 2) \
169     X( SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED               , 24, 6) \
170     X( SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, 32, 1) \
171     X( SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST         , 32, 3) \
172     X( SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND  , 32, 6) \
173     X( SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, 34, 0) \
174     X( SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE      , 35, 1) \
175     X( SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH           , 35, 3) \
176     X( SUPPORTED_HCI_COMMAND_LE_SET_DEFAULT_PHY                    , 35, 5) \
177     X( SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE    , 36, 6) \
178     X( SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2                , 41, 5) \
179     X( SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE           , 45, 7) \
180 
181 // enumerate supported commands
182 #define X(name, offset, bit) name,
183 enum {
184     SUPPORTED_HCI_COMMANDS
185     SUPPORTED_HCI_COMMANDS_COUNT
186 };
187 #undef X
188 
189 // prototypes
190 #ifdef ENABLE_CLASSIC
191 static void hci_update_scan_enable(void);
192 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable);
193 static int  hci_local_ssp_activated(void);
194 static bool hci_remote_ssp_supported(hci_con_handle_t con_handle);
195 static bool hci_ssp_supported(hci_connection_t * connection);
196 static void hci_notify_if_sco_can_send_now(void);
197 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
198 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
199 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
200 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
201 static void hci_connection_timestamp(hci_connection_t *connection);
202 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
203 static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
204 #endif
205 
206 static int  hci_power_control_on(void);
207 static void hci_power_control_off(void);
208 static void hci_state_reset(void);
209 static void hci_halting_timeout_handler(btstack_timer_source_t * ds);
210 static void hci_emit_transport_packet_sent(void);
211 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
212 static void hci_emit_nr_connections_changed(void);
213 static void hci_emit_hci_open_failed(void);
214 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
215 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
216 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
217 static void hci_run(void);
218 static bool hci_is_le_connection(hci_connection_t * connection);
219 
220 #ifdef ENABLE_CLASSIC
221 static int hci_have_usb_transport(void);
222 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection);
223 #endif
224 
225 #ifdef ENABLE_BLE
226 static bool hci_run_general_gap_le(void);
227 static void gap_privacy_clients_handle_ready(void);
228 static void gap_privacy_clients_notify(bd_addr_t new_random_address);
229 #ifdef ENABLE_LE_CENTRAL
230 // called from test/ble_client/advertising_data_parser.c
231 void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
232 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
233 static hci_connection_t * gap_get_outgoing_le_connection(void);
234 static void hci_le_scan_stop(void);
235 #endif
236 #ifdef ENABLE_LE_PERIPHERAL
237 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
238 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle);
239 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
240 #endif /* ENABLE_LE_PERIPHERAL */
241 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
242 static hci_iso_stream_t * hci_iso_stream_create(hci_iso_type_t iso_type, hci_iso_stream_state_t state, uint8_t group_id, uint8_t stream_id);
243 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream);
244 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id);
245 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle);
246 static void hci_iso_stream_requested_finalize(uint8_t big_handle);
247 static void hci_iso_stream_requested_confirm(uint8_t big_handle);
248 static void hci_iso_packet_handler(hci_iso_stream_t *iso_stream, uint8_t *packet, uint16_t size);
249 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle);
250 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id);
251 static void hci_iso_notify_can_send_now(void);
252 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status);
253 static void hci_emit_big_terminated(const le_audio_big_t * big);
254 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status);
255 static void hci_emit_big_sync_stopped(uint8_t big_handle);
256 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status);
257 static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status);
258 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle);
259 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
260 #endif /* ENABLE_BLE */
261 
262 // the STACK is here
263 #ifndef HAVE_MALLOC
264 static hci_stack_t   hci_stack_static;
265 #endif
266 static hci_stack_t * hci_stack = NULL;
267 
268 #ifdef ENABLE_CLASSIC
269 // default name
270 static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
271 
272 // test helper
273 static uint8_t disable_l2cap_timeouts = 0;
274 #endif
275 
276 // reset connection state on create and on reconnect
277 // don't overwrite addr, con handle, role
278 static void hci_connection_init(hci_connection_t * conn){
279     conn->authentication_flags = AUTH_FLAG_NONE;
280     conn->bonding_flags = 0;
281     conn->requested_security_level = LEVEL_0;
282     conn->link_key_type = INVALID_LINK_KEY;
283 #ifdef ENABLE_CLASSIC
284     conn->request_role = HCI_ROLE_INVALID;
285     conn->sniff_subrating_max_latency = 0xffff;
286     conn->qos_service_type = HCI_SERVICE_TYPE_INVALID;
287     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
288     btstack_run_loop_set_timer_context(&conn->timeout, conn);
289     hci_connection_timestamp(conn);
290 #endif
291     conn->acl_recombination_length = 0;
292     conn->acl_recombination_pos = 0;
293     conn->num_packets_sent = 0;
294 
295     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
296 #ifdef ENABLE_BLE
297     conn->le_phy_update_all_phys = 0xff;
298 #endif
299 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
300     conn->le_max_tx_octets = 27;
301 #endif
302 #ifdef ENABLE_CLASSIC_PAIRING_OOB
303     conn->classic_oob_c_192 = NULL;
304     conn->classic_oob_r_192 = NULL;
305     conn->classic_oob_c_256 = NULL;
306     conn->classic_oob_r_256 = NULL;
307 #endif
308 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
309     conn->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
310     conn->le_past_advertising_handle = 0xff;
311 #endif
312 }
313 
314 /**
315  * create connection for given address
316  *
317  * @return connection OR NULL, if no memory left
318  */
319 static hci_connection_t *
320 create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type, hci_role_t role) {
321     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
322 
323     hci_connection_t * conn = btstack_memory_hci_connection_get();
324     if (!conn) return NULL;
325     hci_connection_init(conn);
326 
327     bd_addr_copy(conn->address, addr);
328     conn->address_type = addr_type;
329     conn->con_handle = HCI_CON_HANDLE_INVALID;
330     conn->role = role;
331     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
332 
333     return conn;
334 }
335 
336 
337 /**
338  * get le connection parameter range
339 *
340  * @return le connection parameter range struct
341  */
342 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
343     *range = hci_stack->le_connection_parameter_range;
344 }
345 
346 /**
347  * set le connection parameter range
348  *
349  */
350 
351 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
352     hci_stack->le_connection_parameter_range = *range;
353 }
354 
355 /**
356  * @brief Test if connection parameters are inside in existing rage
357  * @param conn_interval_min (unit: 1.25ms)
358  * @param conn_interval_max (unit: 1.25ms)
359  * @param conn_latency
360  * @param supervision_timeout (unit: 10ms)
361  * @return 1 if included
362  */
363 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){
364     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
365     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
366 
367     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
368     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
369 
370     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
371     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
372 
373     return 1;
374 }
375 
376 /**
377  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
378  * @note: default: 1
379  * @param max_peripheral_connections
380  */
381 #ifdef ENABLE_LE_PERIPHERAL
382 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
383     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
384 }
385 #endif
386 
387 /**
388  * get hci connections iterator
389  *
390  * @return hci connections iterator
391  */
392 
393 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
394     btstack_linked_list_iterator_init(it, &hci_stack->connections);
395 }
396 
397 /**
398  * get connection for a given handle
399  *
400  * @return connection OR NULL, if not found
401  */
402 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
403     btstack_linked_list_iterator_t it;
404     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
405     while (btstack_linked_list_iterator_has_next(&it)){
406         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
407         if ( item->con_handle == con_handle ) {
408             return item;
409         }
410     }
411     return NULL;
412 }
413 
414 /**
415  * get connection for given address
416  *
417  * @return connection OR NULL, if not found
418  */
419 hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
420     btstack_linked_list_iterator_t it;
421     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
422     while (btstack_linked_list_iterator_has_next(&it)){
423         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
424         if (connection->address_type != addr_type)  continue;
425         if (memcmp(addr, connection->address, 6) != 0) continue;
426         return connection;
427     }
428     return NULL;
429 }
430 
431 #ifdef ENABLE_CLASSIC
432 
433 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
434     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
435 }
436 
437 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
438     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
439 }
440 
441 #ifdef ENABLE_SCO_OVER_HCI
442 static int hci_number_sco_connections(void){
443     int connections = 0;
444     btstack_linked_list_iterator_t it;
445     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
446     while (btstack_linked_list_iterator_has_next(&it)){
447         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
448         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
449         connections++;
450     }
451     return connections;
452 }
453 #endif
454 
455 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
456     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
457 #ifdef HAVE_EMBEDDED_TICK
458     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
459         // connections might be timed out
460         hci_emit_l2cap_check_timeout(connection);
461     }
462 #else
463     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
464         // connections might be timed out
465         hci_emit_l2cap_check_timeout(connection);
466     }
467 #endif
468 }
469 
470 static void hci_connection_timestamp(hci_connection_t *connection){
471 #ifdef HAVE_EMBEDDED_TICK
472     connection->timestamp = btstack_run_loop_embedded_get_ticks();
473 #else
474     connection->timestamp = btstack_run_loop_get_time_ms();
475 #endif
476 }
477 
478 /**
479  * add authentication flags and reset timer
480  * @note: assumes classic connection
481  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
482  */
483 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
484     bd_addr_t addr;
485     reverse_bd_addr(bd_addr, addr);
486     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
487     if (conn) {
488         connectionSetAuthenticationFlags(conn, flags);
489         hci_connection_timestamp(conn);
490     }
491 }
492 
493 static bool hci_pairing_active(hci_connection_t * hci_connection){
494     return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0;
495 }
496 
497 static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){
498     if (hci_pairing_active(hci_connection)) return;
499     if (ssp){
500         hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE;
501     } else {
502         hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE;
503     }
504     // if we are initiator, we have sent an HCI Authenticate Request
505     bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0;
506 
507     // if we are responder, use minimal service security level as required level
508     if (!initiator){
509         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);
510     }
511 
512     log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level);
513 
514     uint8_t event[12];
515     event[0] = GAP_EVENT_PAIRING_STARTED;
516     event[1] = 10;
517     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
518     reverse_bd_addr(hci_connection->address, &event[4]);
519     event[10] = (uint8_t) ssp;
520     event[11] = (uint8_t) initiator;
521     hci_emit_event(event, sizeof(event), 1);
522 }
523 
524 static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){
525     hci_connection->requested_security_level = LEVEL_0;
526     if (!hci_pairing_active(hci_connection)) return;
527     hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK;
528 #ifdef ENABLE_CLASSIC_PAIRING_OOB
529     hci_connection->classic_oob_c_192 = NULL;
530     hci_connection->classic_oob_r_192 = NULL;
531     hci_connection->classic_oob_c_256 = NULL;
532     hci_connection->classic_oob_r_256 = NULL;
533 #endif
534     log_info("pairing complete, status %02x", status);
535 
536     uint8_t event[11];
537     event[0] = GAP_EVENT_PAIRING_COMPLETE;
538     event[1] = 9;
539     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
540     reverse_bd_addr(hci_connection->address, &event[4]);
541     event[10] = status;
542     hci_emit_event(event, sizeof(event), 1);
543 
544     // emit dedicated bonding done on failure, otherwise verify that connection can be encrypted
545     if ((status != ERROR_CODE_SUCCESS) && ((hci_connection->bonding_flags & BONDING_DEDICATED) != 0)){
546         hci_connection->bonding_flags &= ~BONDING_DEDICATED;
547         hci_connection->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
548         hci_connection->bonding_status = status;
549     }
550 }
551 
552 bool hci_authentication_active_for_handle(hci_con_handle_t handle){
553     hci_connection_t * conn = hci_connection_for_handle(handle);
554     if (!conn) return false;
555     return hci_pairing_active(conn);
556 }
557 
558 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
559     if (!hci_stack->link_key_db) return;
560     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
561     hci_stack->link_key_db->delete_link_key(addr);
562 }
563 
564 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
565     if (!hci_stack->link_key_db) return;
566     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
567     hci_stack->link_key_db->put_link_key(addr, link_key, type);
568 }
569 
570 bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
571 	if (!hci_stack->link_key_db) return false;
572 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
573 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
574 	return result;
575 }
576 
577 void gap_delete_all_link_keys(void){
578     bd_addr_t  addr;
579     link_key_t link_key;
580     link_key_type_t type;
581     btstack_link_key_iterator_t it;
582     int ok = gap_link_key_iterator_init(&it);
583     if (!ok) {
584         log_error("could not initialize iterator");
585         return;
586     }
587     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
588         gap_drop_link_key_for_bd_addr(addr);
589     }
590     gap_link_key_iterator_done(&it);
591 }
592 
593 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
594     if (!hci_stack->link_key_db) return 0;
595     if (!hci_stack->link_key_db->iterator_init) return 0;
596     return hci_stack->link_key_db->iterator_init(it);
597 }
598 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){
599     if (!hci_stack->link_key_db) return 0;
600     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
601 }
602 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
603     if (!hci_stack->link_key_db) return;
604     hci_stack->link_key_db->iterator_done(it);
605 }
606 #endif
607 
608 bool hci_is_le_connection_type(bd_addr_type_t address_type){
609     switch (address_type){
610         case BD_ADDR_TYPE_LE_PUBLIC:
611         case BD_ADDR_TYPE_LE_RANDOM:
612         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
613         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
614             return true;
615         default:
616             return false;
617     }
618 }
619 
620 bool hci_is_le_identity_address_type(bd_addr_type_t address_type){
621     switch (address_type){
622         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
623         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
624             return true;
625         default:
626             return false;
627     }
628 }
629 
630 static bool hci_is_le_connection(hci_connection_t * connection){
631     return hci_is_le_connection_type(connection->address_type);
632 }
633 
634 /**
635  * count connections
636  */
637 static int nr_hci_connections(void){
638     int count = 0;
639     btstack_linked_item_t *it;
640     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
641         count++;
642     }
643     return count;
644 }
645 
646 uint16_t hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
647 
648     unsigned int num_packets_sent_classic = 0;
649     unsigned int num_packets_sent_le = 0;
650 
651     btstack_linked_item_t *it;
652     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
653         hci_connection_t * connection = (hci_connection_t *) it;
654         if (hci_is_le_connection(connection)){
655             num_packets_sent_le += connection->num_packets_sent;
656         }
657         if (connection->address_type == BD_ADDR_TYPE_ACL){
658             num_packets_sent_classic += connection->num_packets_sent;
659         }
660     }
661     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
662     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
663     int free_slots_le = 0;
664 
665     if (free_slots_classic < 0){
666         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);
667         return 0;
668     }
669 
670     if (hci_stack->le_acl_packets_total_num){
671         // if we have LE slots, they are used
672         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
673         if (free_slots_le < 0){
674             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);
675             return 0;
676         }
677     } else {
678         // otherwise, classic slots are used for LE, too
679         free_slots_classic -= num_packets_sent_le;
680         if (free_slots_classic < 0){
681             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);
682             return 0;
683         }
684     }
685 
686     switch (address_type){
687         case BD_ADDR_TYPE_UNKNOWN:
688             log_error("hci_number_free_acl_slots: unknown address type");
689             return 0;
690 
691         case BD_ADDR_TYPE_ACL:
692             return (uint16_t) free_slots_classic;
693 
694         default:
695            if (hci_stack->le_acl_packets_total_num > 0){
696                return (uint16_t) free_slots_le;
697            }
698            return (uint16_t) free_slots_classic;
699     }
700 }
701 
702 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
703     // get connection type
704     hci_connection_t * connection = hci_connection_for_handle(con_handle);
705     if (!connection){
706         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
707         return 0;
708     }
709     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
710 }
711 
712 #ifdef ENABLE_CLASSIC
713 static int hci_number_free_sco_slots(void){
714     unsigned int num_sco_packets_sent  = 0;
715     btstack_linked_item_t *it;
716     if (hci_stack->synchronous_flow_control_enabled){
717         // explicit flow control
718         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
719             hci_connection_t * connection = (hci_connection_t *) it;
720             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
721             num_sco_packets_sent += connection->num_packets_sent;
722         }
723         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
724             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
725             return 0;
726         }
727         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
728     } else {
729         // implicit flow control
730         int num_ready = 0;
731         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
732             hci_connection_t * connection = (hci_connection_t *) it;
733             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
734             if (connection->sco_tx_ready == 0) continue;
735             num_ready++;
736         }
737         return num_ready;
738     }
739 }
740 #endif
741 
742 // only used to send HCI Host Number Completed Packets
743 static int hci_can_send_comand_packet_transport(void){
744     if (hci_stack->hci_packet_buffer_reserved) return 0;
745 
746     // check for async hci transport implementations
747     if (hci_stack->hci_transport->can_send_packet_now){
748         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
749             return 0;
750         }
751     }
752     return 1;
753 }
754 
755 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
756 bool hci_can_send_command_packet_now(void){
757     if (hci_can_send_comand_packet_transport() == 0) return false;
758     return hci_stack->num_cmd_packets > 0u;
759 }
760 
761 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
762     // check for async hci transport implementations
763     if (!hci_stack->hci_transport->can_send_packet_now) return true;
764     return hci_stack->hci_transport->can_send_packet_now(packet_type);
765 }
766 
767 static bool hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
768     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
769     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
770 }
771 
772 bool hci_can_send_acl_le_packet_now(void){
773     if (hci_stack->hci_packet_buffer_reserved) return false;
774     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
775 }
776 
777 bool hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
778     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
779     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
780 }
781 
782 bool hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
783     if (hci_stack->hci_packet_buffer_reserved) return false;
784     return hci_can_send_prepared_acl_packet_now(con_handle);
785 }
786 
787 #ifdef ENABLE_CLASSIC
788 bool hci_can_send_acl_classic_packet_now(void){
789     if (hci_stack->hci_packet_buffer_reserved) return false;
790     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
791 }
792 
793 bool hci_can_send_prepared_sco_packet_now(void){
794     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return false;
795     if (hci_have_usb_transport()){
796         return hci_stack->sco_can_send_now;
797     } else {
798         return hci_number_free_sco_slots() > 0;
799     }
800 }
801 
802 bool hci_can_send_sco_packet_now(void){
803     if (hci_stack->hci_packet_buffer_reserved) return false;
804     return hci_can_send_prepared_sco_packet_now();
805 }
806 
807 void hci_request_sco_can_send_now_event(void){
808     hci_stack->sco_waiting_for_can_send_now = 1;
809     hci_notify_if_sco_can_send_now();
810 }
811 #endif
812 
813 // used for internal checks in l2cap.c
814 bool hci_is_packet_buffer_reserved(void){
815     return hci_stack->hci_packet_buffer_reserved;
816 }
817 
818 // reserves outgoing packet buffer.
819 // @return 1 if successful
820 bool hci_reserve_packet_buffer(void){
821     if (hci_stack->hci_packet_buffer_reserved) {
822         log_error("hci_reserve_packet_buffer called but buffer already reserved");
823         return false;
824     }
825     hci_stack->hci_packet_buffer_reserved = true;
826     return true;
827 }
828 
829 void hci_release_packet_buffer(void){
830     hci_stack->hci_packet_buffer_reserved = false;
831 }
832 
833 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
834 static int hci_transport_synchronous(void){
835     return hci_stack->hci_transport->can_send_packet_now == NULL;
836 }
837 
838 // used for debugging
839 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
840 static void hci_controller_dump_packets(void){
841     // format: "{handle:04x}:{count:02d} "
842     char summaries[3][7 * 8 + 1];
843     uint16_t totals[3];
844     uint8_t index;
845     for (index = 0 ; index < 3 ; index++){
846         summaries[index][0] = 0;
847         totals[index] = 0;
848     }
849     btstack_linked_item_t *it;
850     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
851         hci_connection_t * connection = (hci_connection_t *) it;
852         switch (connection->address_type){
853             case BD_ADDR_TYPE_ACL:
854                 index = 0;
855                 break;
856             case BD_ADDR_TYPE_SCO:
857                 index = 2;
858                 break;
859             default:
860                 index = 1;
861                 break;
862         }
863         totals[index] += connection->num_packets_sent;
864         char item_text[10];
865         sprintf(item_text, "%04x:%02d ", connection->con_handle,connection->num_packets_sent);
866         btstack_strcat(summaries[index], sizeof(summaries[0]), item_text);
867     }
868     for (index = 0 ; index < 3 ; index++){
869         if (summaries[index][0] == 0){
870             summaries[index][0] = '-';
871             summaries[index][1] = 0;
872         }
873     }
874     log_info("Controller ACL BR/EDR: %s total %u / LE: %s total %u / SCO: %s total %u", summaries[0], totals[0], summaries[1], totals[1], summaries[2], totals[2]);
875 }
876 #endif
877 
878 static uint8_t hci_send_acl_packet_fragments(hci_connection_t *connection){
879 
880     // 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);
881 
882     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
883     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
884     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
885         max_acl_data_packet_length = hci_stack->le_data_packets_length;
886     }
887 
888 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
889     if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){
890         max_acl_data_packet_length = connection->le_max_tx_octets;
891     }
892 #endif
893 
894     log_debug("hci_send_acl_packet_fragments entered");
895 
896     uint8_t status = ERROR_CODE_SUCCESS;
897     // multiple packets could be send on a synchronous HCI transport
898     while (true){
899 
900         log_debug("hci_send_acl_packet_fragments loop entered");
901 
902         // get current data
903         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
904         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
905         bool more_fragments = false;
906 
907         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
908         if (current_acl_data_packet_length > max_acl_data_packet_length){
909             more_fragments = true;
910             current_acl_data_packet_length = max_acl_data_packet_length & (~(HCI_ACL_CHUNK_SIZE_ALIGNMENT-1));
911         }
912 
913         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
914         if (acl_header_pos > 0u){
915             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
916             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
917             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
918         }
919 
920         // update header len
921         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
922 
923         // count packet
924         connection->num_packets_sent++;
925         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
926 
927         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
928         if (more_fragments){
929             // update start of next fragment to send
930             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
931         } else {
932             // done
933             hci_stack->acl_fragmentation_pos = 0;
934             hci_stack->acl_fragmentation_total_size = 0;
935         }
936 
937         // send packet
938         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
939         const int size = current_acl_data_packet_length + 4;
940         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
941         hci_stack->acl_fragmentation_tx_active = 1;
942         int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
943         if (err != 0){
944             // no error from HCI Transport expected
945             status = ERROR_CODE_HARDWARE_FAILURE;
946         }
947 
948 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
949         hci_controller_dump_packets();
950 #endif
951 
952         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
953 
954         // done yet?
955         if (!more_fragments) break;
956 
957         // can send more?
958         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return status;
959     }
960 
961     log_debug("hci_send_acl_packet_fragments loop over");
962 
963     // release buffer now for synchronous transport
964     if (hci_transport_synchronous()){
965         hci_stack->acl_fragmentation_tx_active = 0;
966         hci_release_packet_buffer();
967         hci_emit_transport_packet_sent();
968     }
969 
970     return status;
971 }
972 
973 // pre: caller has reserved the packet buffer
974 uint8_t hci_send_acl_packet_buffer(int size){
975     btstack_assert(hci_stack->hci_packet_buffer_reserved);
976 
977     uint8_t * packet = hci_stack->hci_packet_buffer;
978     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
979 
980     hci_connection_t *connection = hci_connection_for_handle( con_handle);
981     if (!connection) {
982         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
983         hci_release_packet_buffer();
984         hci_emit_transport_packet_sent();
985         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
986     }
987 
988     // check for free places on Bluetooth module
989     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
990         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
991         hci_release_packet_buffer();
992         hci_emit_transport_packet_sent();
993         return BTSTACK_ACL_BUFFERS_FULL;
994     }
995 
996 #ifdef ENABLE_CLASSIC
997     hci_connection_timestamp(connection);
998 #endif
999 
1000     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
1001 
1002     // setup data
1003     hci_stack->acl_fragmentation_total_size = size;
1004     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
1005 
1006     return hci_send_acl_packet_fragments(connection);
1007 }
1008 
1009 #ifdef ENABLE_CLASSIC
1010 // pre: caller has reserved the packet buffer
1011 uint8_t hci_send_sco_packet_buffer(int size){
1012     btstack_assert(hci_stack->hci_packet_buffer_reserved);
1013 
1014     uint8_t * packet = hci_stack->hci_packet_buffer;
1015 
1016     // skip checks in loopback mode
1017     if (!hci_stack->loopback_mode){
1018         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
1019 
1020         // check for free places on Bluetooth module
1021         if (!hci_can_send_prepared_sco_packet_now()) {
1022             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
1023             hci_release_packet_buffer();
1024             hci_emit_transport_packet_sent();
1025             return BTSTACK_ACL_BUFFERS_FULL;
1026         }
1027 
1028         // track send packet in connection struct
1029         hci_connection_t *connection = hci_connection_for_handle( con_handle);
1030         if (!connection) {
1031             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
1032             hci_release_packet_buffer();
1033             hci_emit_transport_packet_sent();
1034             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1035         }
1036 
1037         if (hci_have_usb_transport()){
1038             // token used
1039             hci_stack->sco_can_send_now = false;
1040         } else {
1041             if (hci_stack->synchronous_flow_control_enabled){
1042                 connection->num_packets_sent++;
1043             } else {
1044                 connection->sco_tx_ready--;
1045             }
1046         }
1047     }
1048 
1049     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
1050 
1051 #ifdef HAVE_SCO_TRANSPORT
1052     hci_stack->sco_transport->send_packet(packet, size);
1053     hci_release_packet_buffer();
1054     hci_emit_transport_packet_sent();
1055 
1056     return 0;
1057 #else
1058     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
1059     if (hci_transport_synchronous()){
1060         hci_release_packet_buffer();
1061         hci_emit_transport_packet_sent();
1062     }
1063 
1064     if (err != 0){
1065         return ERROR_CODE_HARDWARE_FAILURE;
1066     }
1067     return ERROR_CODE_SUCCESS;
1068 #endif
1069 }
1070 #endif
1071 
1072 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
1073 static uint8_t hci_send_iso_packet_fragments(void){
1074 
1075     uint16_t max_iso_data_packet_length = hci_stack->le_iso_packets_length;
1076     uint8_t status = ERROR_CODE_SUCCESS;
1077     // multiple packets could be send on a synchronous HCI transport
1078     while (true){
1079 
1080         // get current data
1081         const uint16_t iso_header_pos = hci_stack->iso_fragmentation_pos - 4u;
1082         int current_iso_data_packet_length = hci_stack->iso_fragmentation_total_size - hci_stack->iso_fragmentation_pos;
1083         bool more_fragments = false;
1084 
1085         // if ISO packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
1086         if (current_iso_data_packet_length > max_iso_data_packet_length){
1087             more_fragments = true;
1088             current_iso_data_packet_length = max_iso_data_packet_length;
1089         }
1090 
1091         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
1092         uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1093         uint8_t pb_flags;
1094         if (iso_header_pos == 0u){
1095             // first fragment, keep TS field
1096             pb_flags = more_fragments ? 0x00 : 0x02;
1097             handle_and_flags = (handle_and_flags & 0x4fffu) | (pb_flags << 12u);
1098         } else {
1099             // later fragment, drop TS field
1100             pb_flags = more_fragments ? 0x01 : 0x03;
1101             handle_and_flags = (handle_and_flags & 0x0fffu) | (pb_flags << 12u);
1102         }
1103         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos, handle_and_flags);
1104 
1105         // update header len
1106         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos + 2u, current_iso_data_packet_length);
1107 
1108         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
1109         if (more_fragments){
1110             // update start of next fragment to send
1111             hci_stack->iso_fragmentation_pos += current_iso_data_packet_length;
1112         } else {
1113             // done
1114             hci_stack->iso_fragmentation_pos = 0;
1115             hci_stack->iso_fragmentation_total_size = 0;
1116         }
1117 
1118         // send packet
1119         uint8_t * packet = &hci_stack->hci_packet_buffer[iso_header_pos];
1120         const int size = current_iso_data_packet_length + 4;
1121         hci_dump_packet(HCI_ISO_DATA_PACKET, 0, packet, size);
1122         hci_stack->iso_fragmentation_tx_active = true;
1123         int err = hci_stack->hci_transport->send_packet(HCI_ISO_DATA_PACKET, packet, size);
1124         if (err != 0){
1125             // no error from HCI Transport expected
1126             status = ERROR_CODE_HARDWARE_FAILURE;
1127         }
1128 
1129         // done yet?
1130         if (!more_fragments) break;
1131 
1132         // can send more?
1133         if (!hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)) return false;
1134     }
1135 
1136     // release buffer now for synchronous transport
1137     if (hci_transport_synchronous()){
1138         hci_stack->iso_fragmentation_tx_active = false;
1139         hci_release_packet_buffer();
1140         hci_emit_transport_packet_sent();
1141     }
1142 
1143     return status;
1144 }
1145 
1146 uint8_t hci_send_iso_packet_buffer(uint16_t size){
1147     btstack_assert(hci_stack->hci_packet_buffer_reserved);
1148 
1149     hci_con_handle_t con_handle = (hci_con_handle_t) little_endian_read_16(hci_stack->hci_packet_buffer, 0) & 0xfff;
1150     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(con_handle);
1151     if (iso_stream == NULL){
1152         hci_release_packet_buffer();
1153         hci_iso_notify_can_send_now();
1154         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1155     }
1156 
1157     // TODO: check for space on controller
1158 
1159     // skip iso packets if needed
1160     if (iso_stream->num_packets_to_skip > 0){
1161         iso_stream->num_packets_to_skip--;
1162         // pretend it was processed and trigger next one
1163         hci_release_packet_buffer();
1164         hci_iso_notify_can_send_now();
1165         return ERROR_CODE_SUCCESS;
1166     }
1167 
1168     // track outgoing packet sent
1169     log_info("Outgoing ISO packet for con handle 0x%04x", con_handle);
1170     iso_stream->num_packets_sent++;
1171 
1172     // setup data
1173     hci_stack->iso_fragmentation_total_size = size;
1174     hci_stack->iso_fragmentation_pos = 4;   // start of L2CAP packet
1175 
1176     return hci_send_iso_packet_fragments();
1177 }
1178 #endif
1179 
1180 static void acl_handler(uint8_t *packet, uint16_t size){
1181 
1182     // get info
1183     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
1184     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
1185     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
1186     uint16_t acl_length         = READ_ACL_LENGTH(packet);
1187 
1188     // ignore non-registered handle
1189     if (!conn){
1190         log_error("acl_handler called with non-registered handle %u!" , con_handle);
1191         return;
1192     }
1193 
1194     // assert packet is complete
1195     if ((acl_length + 4u) != size){
1196         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
1197         return;
1198     }
1199 
1200 #ifdef ENABLE_CLASSIC
1201     // update idle timestamp
1202     hci_connection_timestamp(conn);
1203 #endif
1204 
1205 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1206     hci_stack->host_completed_packets = 1;
1207     conn->num_packets_completed++;
1208 #endif
1209 
1210     // handle different packet types
1211     switch (acl_flags & 0x03u) {
1212 
1213         case 0x01: // continuation fragment
1214 
1215             // sanity checks
1216             if (conn->acl_recombination_pos == 0u) {
1217                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
1218                 return;
1219             }
1220             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
1221                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
1222                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
1223                 conn->acl_recombination_pos = 0;
1224                 return;
1225             }
1226 
1227             // append fragment payload (header already stored)
1228             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
1229                          &packet[4], acl_length);
1230             conn->acl_recombination_pos += acl_length;
1231 
1232             // forward complete L2CAP packet if complete.
1233             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
1234                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
1235                 // reset recombination buffer
1236                 conn->acl_recombination_length = 0;
1237                 conn->acl_recombination_pos = 0;
1238             }
1239             break;
1240 
1241         case 0x02: { // first fragment
1242 
1243             // sanity check
1244             if (conn->acl_recombination_pos) {
1245                 // we just received the first fragment, but still have data. Only warn if the packet wasn't a flushable packet
1246                 if ((conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE+1] >> 4) != 0x02){
1247                     log_error( "ACL First Fragment but %u bytes in buffer for handle 0x%02x, dropping stale fragments", conn->acl_recombination_pos, con_handle);
1248                 }
1249                 conn->acl_recombination_pos = 0;
1250             }
1251 
1252             // peek into L2CAP packet!
1253             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
1254 
1255             // compare fragment size to L2CAP packet size
1256             if (acl_length >= (l2cap_length + 4u)){
1257                 // forward fragment as L2CAP packet
1258                 hci_emit_acl_packet(packet, acl_length + 4u);
1259             } else {
1260 
1261                 if (acl_length > HCI_ACL_BUFFER_SIZE){
1262                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
1263                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
1264                     return;
1265                 }
1266 
1267                 // store first fragment and tweak acl length for complete package
1268                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
1269                              packet, acl_length + 4u);
1270                 conn->acl_recombination_pos    = acl_length + 4u;
1271                 conn->acl_recombination_length = l2cap_length;
1272                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
1273             }
1274             break;
1275 
1276         }
1277         default:
1278             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
1279             return;
1280     }
1281 
1282     // execute main loop
1283     hci_run();
1284 }
1285 
1286 static void hci_connection_stop_timer(hci_connection_t * conn){
1287     btstack_run_loop_remove_timer(&conn->timeout);
1288 #ifdef ENABLE_CLASSIC
1289     btstack_run_loop_remove_timer(&conn->timeout_sco);
1290 #endif
1291 }
1292 
1293 static void hci_shutdown_connection(hci_connection_t *conn){
1294     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
1295 
1296 #ifdef ENABLE_CLASSIC
1297 #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1298     bd_addr_type_t addr_type = conn->address_type;
1299 #endif
1300 #ifdef HAVE_SCO_TRANSPORT
1301     hci_con_handle_t con_handle = conn->con_handle;
1302 #endif
1303 #endif
1304 
1305     hci_connection_stop_timer(conn);
1306 
1307     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1308     btstack_memory_hci_connection_free( conn );
1309 
1310     // now it's gone
1311     hci_emit_nr_connections_changed();
1312 
1313 #ifdef ENABLE_CLASSIC
1314 #ifdef ENABLE_SCO_OVER_HCI
1315     // update SCO
1316     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1317         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1318     }
1319 #endif
1320 #ifdef HAVE_SCO_TRANSPORT
1321     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1322         hci_stack->sco_transport->close(con_handle);
1323     }
1324 #endif
1325 #endif
1326 }
1327 
1328 #ifdef ENABLE_CLASSIC
1329 
1330 static const uint16_t hci_acl_packet_type_sizes[] = {
1331     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
1332     HCI_ACL_DH1_SIZE, 0, 0, 0,
1333     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
1334     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
1335 };
1336 static const uint8_t hci_acl_packet_type_feature_requirement_bit[] = {
1337      0, // 3 slot packets
1338      1, // 5 slot packets
1339     25, // EDR 2 mpbs
1340     26, // EDR 3 mbps
1341     39, // 3 slot EDR packts
1342     40, // 5 slot EDR packet
1343 };
1344 static const uint16_t hci_acl_packet_type_feature_packet_mask[] = {
1345     0x0f00, // 3 slot packets
1346     0xf000, // 5 slot packets
1347     0x1102, // EDR 2 mpbs
1348     0x2204, // EDR 3 mbps
1349     0x0300, // 3 slot EDR packts
1350     0x3000, // 5 slot EDR packet
1351 };
1352 
1353 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
1354     // enable packet types based on size
1355     uint16_t packet_types = 0;
1356     unsigned int i;
1357     for (i=0;i<16;i++){
1358         if (hci_acl_packet_type_sizes[i] == 0) continue;
1359         if (hci_acl_packet_type_sizes[i] <= buffer_size){
1360             packet_types |= 1 << i;
1361         }
1362     }
1363     // disable packet types due to missing local supported features
1364     for (i=0;i<sizeof(hci_acl_packet_type_feature_requirement_bit); i++){
1365         unsigned int bit_idx = hci_acl_packet_type_feature_requirement_bit[i];
1366         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1367         if (feature_set) continue;
1368         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, hci_acl_packet_type_feature_packet_mask[i]);
1369         packet_types &= ~hci_acl_packet_type_feature_packet_mask[i];
1370     }
1371     return packet_types;
1372 }
1373 
1374 uint16_t hci_usable_acl_packet_types(void){
1375     uint16_t active_packet_types = (hci_stack->usable_packet_types_acl &  hci_stack->enabled_packet_types_acl);
1376     // flip bits for "may not be used"
1377     return  active_packet_types ^ 0x3306;
1378 }
1379 
1380 void hci_enable_acl_packet_types(uint16_t packet_types){
1381     hci_stack->enabled_packet_types_acl = packet_types;
1382 }
1383 
1384 static const struct {
1385     uint8_t feature_index;
1386     uint16_t feature_packet_mask;
1387 } hci_sco_packet_type_feature_requirements[] = {
1388         { 12, SCO_PACKET_TYPES_HV2 },                           // HV2 packets
1389         { 13, SCO_PACKET_TYPES_HV3 },                           // HV3 packets
1390         { 31, SCO_PACKET_TYPES_ESCO },                          // eSCO links (EV3 packets)
1391         { 32, SCO_PACKET_TYPES_EV4 },                           // EV4 packets
1392         { 45, SCO_PACKET_TYPES_2EV3 | SCO_PACKET_TYPES_2EV5 },  // EDR eSCO 2 Mb/s
1393         { 46, SCO_PACKET_TYPES_3EV3 | SCO_PACKET_TYPES_3EV5 },  // EDR eSCO 3 Mb/s
1394         { 47, SCO_PACKET_TYPES_2EV5 | SCO_PACKET_TYPES_3EV5 },  // 3-slot EDR eSCO packets, 2-EV3/3-EV3 use single slot
1395 };
1396 
1397 // map packet types to payload length, prefer eSCO over SCO and large over small packets
1398 static const struct {
1399     uint16_t type;
1400     uint16_t payload_length;
1401 } hci_sco_packet_type_to_payload_length[] = {
1402         {SCO_PACKET_TYPES_3EV5, HCI_SCO_3EV5_SIZE}, // 540
1403         {SCO_PACKET_TYPES_2EV5, HCI_SCO_2EV5_SIZE}, // 360
1404         {SCO_PACKET_TYPES_EV5,  HCI_SCO_EV5_SIZE},  // 180
1405         {SCO_PACKET_TYPES_EV4,  HCI_SCO_EV4_SIZE},  // 120
1406         {SCO_PACKET_TYPES_3EV3, HCI_SCO_3EV3_SIZE}, //  90
1407         {SCO_PACKET_TYPES_2EV3, HCI_SCO_2EV3_SIZE}, //  60
1408         {SCO_PACKET_TYPES_EV3,  HCI_SCO_EV3_SIZE},  //  30
1409         {SCO_PACKET_TYPES_HV3,  HCI_SCO_HV3_SIZE},  //  30
1410         {SCO_PACKET_TYPES_HV2,  HCI_SCO_HV2_SIZE},  //  20
1411         {SCO_PACKET_TYPES_HV1,  HCI_SCO_HV1_SIZE}   //  10
1412 };
1413 
1414 static uint16_t hci_sco_packet_types_for_features(const uint8_t * local_supported_features){
1415     uint16_t packet_types = SCO_PACKET_TYPES_ALL;
1416     unsigned int i;
1417     // disable packet types due to missing local supported features
1418     for (i=0;i<(sizeof(hci_sco_packet_type_feature_requirements)/sizeof(hci_sco_packet_type_feature_requirements[0])); i++){
1419         unsigned int bit_idx = hci_sco_packet_type_feature_requirements[i].feature_index;
1420         bool feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1421         if (feature_set) continue;
1422         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, hci_sco_packet_type_feature_requirements[i].feature_packet_mask);
1423         packet_types &= ~hci_sco_packet_type_feature_requirements[i].feature_packet_mask;
1424     }
1425     return packet_types;
1426 }
1427 
1428 uint16_t hci_usable_sco_packet_types(void){
1429     return hci_stack->usable_packet_types_sco;
1430 }
1431 
1432 static uint16_t hci_sco_payload_length_for_packet_types(uint16_t packet_types){
1433     uint8_t i;
1434     for (i=0;i<sizeof(hci_sco_packet_type_to_payload_length)/sizeof(hci_sco_packet_type_to_payload_length[0]);i++){
1435         if ((hci_sco_packet_type_to_payload_length[i].type & packet_types) != 0){
1436             return hci_sco_packet_type_to_payload_length[i].payload_length;
1437         }
1438     }
1439     return 0;
1440 }
1441 
1442 #endif
1443 
1444 uint8_t* hci_get_outgoing_packet_buffer(void){
1445     // hci packet buffer is >= acl data packet length
1446     return hci_stack->hci_packet_buffer;
1447 }
1448 
1449 uint16_t hci_max_acl_data_packet_length(void){
1450     return hci_stack->acl_data_packet_length;
1451 }
1452 
1453 #ifdef ENABLE_CLASSIC
1454 bool hci_extended_sco_link_supported(void){
1455     // No. 31, byte 3, bit 7
1456     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
1457 }
1458 #endif
1459 
1460 bool hci_non_flushable_packet_boundary_flag_supported(void){
1461     // No. 54, byte 6, bit 6
1462     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
1463 }
1464 
1465 #ifdef ENABLE_CLASSIC
1466 static bool gap_ssp_supported(void){
1467     // No. 51, byte 6, bit 3
1468     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1469 }
1470 #endif
1471 
1472 bool hci_classic_supported(void){
1473 #ifdef ENABLE_CLASSIC
1474     // No. 37, byte 4, bit 5, = No BR/EDR Support
1475     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
1476 #else
1477     return false;
1478 #endif
1479 }
1480 
1481 bool hci_le_supported(void){
1482 #ifdef ENABLE_BLE
1483     // No. 37, byte 4, bit 6 = LE Supported (Controller)
1484     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1485 #else
1486     return false;
1487 #endif
1488 }
1489 
1490 static bool hci_command_supported(uint8_t command_index){
1491     return (hci_stack->local_supported_commands & (1LU << command_index)) != 0;
1492 }
1493 
1494 #ifdef ENABLE_BLE
1495 
1496 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1497 bool hci_le_extended_advertising_supported(void){
1498     return hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE);
1499 }
1500 #endif
1501 
1502 static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
1503     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
1504         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
1505     } else {
1506         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
1507     }
1508 }
1509 
1510 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
1511     *addr_type = hci_stack->le_own_addr_type;
1512     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
1513 }
1514 
1515 #ifdef ENABLE_LE_PERIPHERAL
1516 void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
1517     *addr_type = hci_stack->le_advertisements_own_addr_type;
1518     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
1519 };
1520 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1521 void gap_le_get_own_advertising_set_address(uint8_t * addr_type, bd_addr_t addr, uint8_t advertising_handle){
1522     if (advertising_handle == 0){
1523         gap_le_get_own_advertisements_address(addr_type, addr);
1524     } else {
1525         le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
1526         if (advertising_set != NULL){
1527             switch (advertising_set->extended_params.own_address_type){
1528                 case BD_ADDR_TYPE_LE_PUBLIC:
1529                     *addr_type = BD_ADDR_TYPE_LE_PUBLIC;
1530                     memcpy(addr, hci_stack->local_bd_addr, 6);
1531                     break;
1532                 case BD_ADDR_TYPE_LE_RANDOM:
1533                     *addr_type = BD_ADDR_TYPE_LE_RANDOM;
1534                     memcpy(addr, advertising_set->random_address, 6);
1535                     break;
1536                 case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
1537                 case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
1538                     // do nothing as random address was already set from enhanced connection complete
1539                     break;
1540                 default:
1541                     break;
1542             }
1543         }
1544     }
1545 };
1546 #endif
1547 #endif
1548 
1549 #ifdef ENABLE_LE_CENTRAL
1550 
1551 /**
1552  * @brief Get own addr type and address used for LE connections (Central)
1553  */
1554 void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
1555     *addr_type = hci_stack->le_connection_own_addr_type;
1556     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
1557 }
1558 
1559 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
1560 
1561     uint16_t offset = 3;
1562     uint8_t num_reports = packet[offset];
1563     offset += 1;
1564 
1565     uint16_t i;
1566     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1567     for (i=0; (i<num_reports) && (offset < size);i++){
1568         // sanity checks on data_length:
1569         uint8_t data_length = packet[offset + 8];
1570         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1571         if ((offset + 9u + data_length + 1u) > size)    return;
1572         // setup event
1573         uint8_t event_size = 10u + data_length;
1574         uint16_t pos = 0;
1575         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1576         event[pos++] = event_size;
1577         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1578         offset += 8;
1579         pos += 8;
1580         event[pos++] = packet[offset + 1 + data_length]; // rssi
1581         event[pos++] = data_length;
1582         offset++;
1583         (void)memcpy(&event[pos], &packet[offset], data_length);
1584         pos +=    data_length;
1585         offset += data_length + 1u; // rssi
1586         hci_emit_event(event, pos, 1);
1587     }
1588 }
1589 
1590 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1591 void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size) {
1592     uint16_t offset = 3;
1593     uint8_t num_reports = packet[offset++];
1594     uint8_t event[2 + 255]; // use upper bound to avoid var size automatic var
1595     uint8_t i;
1596     for (i=0; (i<num_reports) && (offset < size);i++){
1597         // sanity checks on data_length:
1598         uint16_t data_length = packet[offset + 23];
1599         if (data_length > LE_EXTENDED_ADVERTISING_DATA_SIZE) return;
1600         if ((offset + 24u + data_length) > size)    return;
1601         uint16_t event_type = little_endian_read_16(packet, offset);
1602         offset += 2;
1603         if ((event_type & 0x10) != 0) {
1604            // setup legacy event
1605             uint8_t legacy_event_type;
1606             switch (event_type){
1607                 case 0b0010011:
1608                     // ADV_IND
1609                     legacy_event_type = 0;
1610                     break;
1611                 case 0b0010101:
1612                     // ADV_DIRECT_IND
1613                     legacy_event_type = 1;
1614                     break;
1615                 case 0b0010010:
1616                     // ADV_SCAN_IND
1617                     legacy_event_type = 2;
1618                     break;
1619                 case 0b0010000:
1620                     // ADV_NONCONN_IND
1621                     legacy_event_type = 3;
1622                     break;
1623                 case 0b0011011:
1624                 case 0b0011010:
1625                     // SCAN_RSP
1626                     legacy_event_type = 4;
1627                     break;
1628                 default:
1629                     legacy_event_type = 0;
1630                     break;
1631             }
1632             uint16_t pos = 0;
1633             event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1634             event[pos++] = 10u + data_length;
1635             event[pos++] = legacy_event_type;
1636             // copy address type + address
1637             (void) memcpy(&event[pos], &packet[offset], 1 + 6);
1638             offset += 7;
1639             pos += 7;
1640             // skip primary_phy, secondary_phy, advertising_sid, tx_power
1641             offset += 4;
1642             // copy rssi
1643             event[pos++] = packet[offset++];
1644             // skip periodic advertising interval and direct address
1645             offset += 9;
1646             // copy data len + data;
1647             (void) memcpy(&event[pos], &packet[offset], 1 + data_length);
1648             pos    += 1 +data_length;
1649             offset += 1+ data_length;
1650             hci_emit_event(event, pos, 1);
1651         } else {
1652             event[0] = GAP_EVENT_EXTENDED_ADVERTISING_REPORT;
1653             uint8_t report_len = 24 + data_length;
1654             event[1] = report_len;
1655             little_endian_store_16(event, 2, event_type);
1656             memcpy(&event[4], &packet[offset], report_len);
1657             offset += report_len;
1658             hci_emit_event(event, 2 + report_len, 1);
1659         }
1660     }
1661 }
1662 #endif
1663 
1664 #endif
1665 #endif
1666 
1667 #ifdef ENABLE_BLE
1668 #ifdef ENABLE_LE_PERIPHERAL
1669 static void hci_update_advertisements_enabled_for_current_roles(void){
1670     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ENABLED) != 0){
1671         // get number of active le slave connections
1672         int num_slave_connections = 0;
1673         btstack_linked_list_iterator_t it;
1674         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
1675         while (btstack_linked_list_iterator_has_next(&it)){
1676             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
1677             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
1678             if (con->state != OPEN) continue;
1679             if (con->role  != HCI_ROLE_SLAVE) continue;
1680             if (!hci_is_le_connection(con)) continue;
1681             num_slave_connections++;
1682         }
1683         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1684         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1685     } else {
1686         hci_stack->le_advertisements_enabled_for_current_roles = false;
1687     }
1688 }
1689 #endif
1690 #endif
1691 
1692 #ifdef ENABLE_CLASSIC
1693 static void gap_run_set_local_name(void){
1694     hci_reserve_packet_buffer();
1695     uint8_t * packet = hci_stack->hci_packet_buffer;
1696     // construct HCI Command and send
1697     uint16_t opcode = hci_write_local_name.opcode;
1698     hci_stack->last_cmd_opcode = opcode;
1699     packet[0] = opcode & 0xff;
1700     packet[1] = opcode >> 8;
1701     packet[2] = DEVICE_NAME_LEN;
1702     memset(&packet[3], 0, DEVICE_NAME_LEN);
1703     uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1704     uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
1705     // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
1706     (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
1707     // expand '00:00:00:00:00:00' in name with bd_addr
1708     btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
1709     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1710 }
1711 
1712 static void gap_run_set_eir_data(void){
1713     hci_reserve_packet_buffer();
1714     uint8_t * packet = hci_stack->hci_packet_buffer;
1715     // construct HCI Command in-place and send
1716     uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1717     hci_stack->last_cmd_opcode = opcode;
1718     uint16_t offset = 0;
1719     packet[offset++] = opcode & 0xff;
1720     packet[offset++] = opcode >> 8;
1721     packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
1722     packet[offset++] = 0;  // FEC not required
1723     memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1724     if (hci_stack->eir_data){
1725         // copy items and expand '00:00:00:00:00:00' in name with bd_addr
1726         ad_context_t context;
1727         for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
1728             uint8_t data_type   = ad_iterator_get_data_type(&context);
1729             uint8_t size        = ad_iterator_get_data_len(&context);
1730             const uint8_t *data = ad_iterator_get_data(&context);
1731             // copy item
1732             packet[offset++] = size + 1;
1733             packet[offset++] = data_type;
1734             memcpy(&packet[offset], data, size);
1735             // update name item
1736             if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
1737                 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
1738             }
1739             offset += size;
1740         }
1741     } else {
1742         uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1743         uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
1744         packet[offset++] = bytes_to_copy + 1;
1745         packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1746         (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
1747         // expand '00:00:00:00:00:00' in name with bd_addr
1748         btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
1749     }
1750     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1751 }
1752 
1753 static void hci_run_gap_tasks_classic(void){
1754     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
1755         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
1756         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1757         return;
1758     }
1759     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_LOCAL_NAME) != 0) {
1760         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_LOCAL_NAME;
1761         gap_run_set_local_name();
1762         return;
1763     }
1764     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_EIR_DATA) != 0) {
1765         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_EIR_DATA;
1766         gap_run_set_eir_data();
1767         return;
1768     }
1769     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
1770         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
1771         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1772         return;
1773     }
1774     // write page scan activity
1775     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) {
1776         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
1777         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
1778         return;
1779     }
1780     // write page scan type
1781     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) {
1782         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE;
1783         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
1784         return;
1785     }
1786     // write page timeout
1787     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_TIMEOUT) != 0) {
1788         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_TIMEOUT;
1789         hci_send_cmd(&hci_write_page_timeout, hci_stack->page_timeout);
1790         return;
1791     }
1792     // send scan enable
1793     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_SCAN_ENABLE) != 0) {
1794         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_SCAN_ENABLE;
1795         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1796         return;
1797     }
1798     // send write scan activity
1799     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY) != 0) {
1800         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
1801         hci_send_cmd(&hci_write_inquiry_scan_activity, hci_stack->inquiry_scan_interval, hci_stack->inquiry_scan_window);
1802         return;
1803     }
1804     // send write inquiry transmit power level
1805     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL) != 0) {
1806         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
1807         hci_send_cmd(&hci_write_inquiry_transmit_power_level, hci_stack->inquiry_tx_power_level);
1808         return;
1809     }
1810 }
1811 #endif
1812 
1813 #ifndef HAVE_HOST_CONTROLLER_API
1814 
1815 static uint32_t hci_transport_uart_get_main_baud_rate(void){
1816     if (!hci_stack->config) return 0;
1817     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1818     // Limit baud rate for Broadcom chipsets to 3 mbps
1819     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
1820         baud_rate = 3000000;
1821     }
1822     return baud_rate;
1823 }
1824 
1825 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
1826     UNUSED(ds);
1827 
1828     switch (hci_stack->substate){
1829         case HCI_INIT_W4_SEND_RESET:
1830             log_info("Resend HCI Reset");
1831             hci_stack->substate = HCI_INIT_SEND_RESET;
1832             hci_stack->num_cmd_packets = 1;
1833             hci_run();
1834             break;
1835         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
1836             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
1837             if (hci_stack->hci_transport->reset_link){
1838                 hci_stack->hci_transport->reset_link();
1839             }
1840 
1841             /* fall through */
1842 
1843         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1844             log_info("Resend HCI Reset - CSR Warm Boot");
1845             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1846             hci_stack->num_cmd_packets = 1;
1847             hci_run();
1848             break;
1849         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1850             if (hci_stack->hci_transport->set_baudrate){
1851                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1852                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
1853                 hci_stack->hci_transport->set_baudrate(baud_rate);
1854             }
1855             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
1856             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1857                 if (hci_stack->hci_transport->reset_link){
1858                     log_info("Link Reset");
1859                     hci_stack->hci_transport->reset_link();
1860                 }
1861                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1862                 hci_run();
1863             }
1864             break;
1865         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1866             // otherwise continue
1867             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1868             hci_send_cmd(&hci_read_local_supported_commands);
1869             break;
1870         default:
1871             break;
1872     }
1873 }
1874 #endif
1875 
1876 static void hci_initializing_next_state(void){
1877     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
1878 }
1879 
1880 static void hci_init_done(void){
1881     // done. tell the app
1882     log_info("hci_init_done -> HCI_STATE_WORKING");
1883     hci_stack->state = HCI_STATE_WORKING;
1884     hci_emit_state();
1885 }
1886 
1887 // assumption: hci_can_send_command_packet_now() == true
1888 static void hci_initializing_run(void){
1889     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1890 
1891     if (!hci_can_send_command_packet_now()) return;
1892 
1893 #ifndef HAVE_HOST_CONTROLLER_API
1894     bool need_baud_change = hci_stack->config
1895             && hci_stack->chipset
1896             && hci_stack->chipset->set_baudrate_command
1897             && hci_stack->hci_transport->set_baudrate
1898             && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1899 #endif
1900 
1901     switch (hci_stack->substate){
1902         case HCI_INIT_SEND_RESET:
1903             hci_state_reset();
1904 
1905 #ifndef HAVE_HOST_CONTROLLER_API
1906             // prepare reset if command complete not received in 100ms
1907             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1908             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1909             btstack_run_loop_add_timer(&hci_stack->timeout);
1910 #endif
1911             // send command
1912             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1913             hci_send_cmd(&hci_reset);
1914             break;
1915         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1916             hci_send_cmd(&hci_read_local_version_information);
1917             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1918             break;
1919 
1920 #ifndef HAVE_HOST_CONTROLLER_API
1921         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1922             hci_state_reset();
1923             // prepare reset if command complete not received in 100ms
1924             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1925             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1926             btstack_run_loop_add_timer(&hci_stack->timeout);
1927             // send command
1928             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1929             hci_send_cmd(&hci_reset);
1930             break;
1931         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1932             hci_state_reset();
1933             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1934             hci_send_cmd(&hci_reset);
1935             break;
1936         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1937             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1938             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1939             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1940             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1941             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1942             break;
1943         }
1944         case HCI_INIT_SET_BD_ADDR:
1945             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1946             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1947             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1948             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1949             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1950             break;
1951         case HCI_INIT_SEND_READ_LOCAL_NAME:
1952 #ifdef ENABLE_CLASSIC
1953             hci_send_cmd(&hci_read_local_name);
1954             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1955             break;
1956 #endif
1957             /* fall through */
1958 
1959         case HCI_INIT_SEND_BAUD_CHANGE:
1960             if (need_baud_change) {
1961                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1962                 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1963                 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1964                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1965                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1966                 // STLC25000D: baudrate change happens within 0.5 s after command was send,
1967                 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1968                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1969                     btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1970                     btstack_run_loop_add_timer(&hci_stack->timeout);
1971                }
1972                break;
1973             }
1974             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1975 
1976             /* fall through */
1977 
1978         case HCI_INIT_CUSTOM_INIT:
1979         case HCI_INIT_CUSTOM_PRE_INIT:
1980             // Custom initialization
1981             if (hci_stack->chipset && hci_stack->chipset->next_command){
1982                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1983                 bool send_cmd = false;
1984                 switch (hci_stack->chipset_result){
1985                     case BTSTACK_CHIPSET_VALID_COMMAND:
1986                         send_cmd = true;
1987                         switch (hci_stack->substate){
1988                             case HCI_INIT_CUSTOM_INIT:
1989                                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1990                                 break;
1991                             case HCI_INIT_CUSTOM_PRE_INIT:
1992                                 hci_stack->substate = HCI_INIT_W4_CUSTOM_PRE_INIT;
1993                                 break;
1994                             default:
1995                                 btstack_assert(false);
1996                                 break;
1997                         }
1998                         break;
1999                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
2000                         send_cmd = true;
2001                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
2002                         log_info("CSR Warm Boot");
2003                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
2004                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
2005                         btstack_run_loop_add_timer(&hci_stack->timeout);
2006                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
2007                             && hci_stack->config
2008                             && hci_stack->chipset
2009                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
2010                             && hci_stack->hci_transport->set_baudrate
2011                             && hci_transport_uart_get_main_baud_rate()){
2012                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
2013                         } else {
2014                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
2015                         }
2016                         break;
2017                     default:
2018                         break;
2019                 }
2020 
2021                 if (send_cmd){
2022                     int size = 3u + hci_stack->hci_packet_buffer[2u];
2023                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
2024                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
2025                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
2026                     break;
2027                 }
2028                 log_info("Init script done");
2029 
2030                 // Custom Pre-Init complete, start regular init with HCI Reset
2031                 if (hci_stack->substate == HCI_INIT_CUSTOM_PRE_INIT){
2032                     hci_stack->substate = HCI_INIT_W4_SEND_RESET;
2033                     hci_send_cmd(&hci_reset);
2034                     break;
2035                 }
2036 
2037                 // Init script download on Broadcom chipsets causes:
2038                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2039                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
2040                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
2041 
2042                     // - baud rate to reset, restore UART baud rate if needed
2043                     if (need_baud_change) {
2044                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
2045                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
2046                         hci_stack->hci_transport->set_baudrate(baud_rate);
2047                     }
2048 
2049                     uint16_t bcm_delay_ms = 300;
2050                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
2051                     //   -> Work around: wait here.
2052                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
2053                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
2054                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
2055                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
2056                     btstack_run_loop_add_timer(&hci_stack->timeout);
2057                     break;
2058                 }
2059             }
2060 #endif
2061             /* fall through */
2062 
2063         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
2064             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
2065             hci_send_cmd(&hci_read_local_supported_commands);
2066             break;
2067         case HCI_INIT_READ_BD_ADDR:
2068             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
2069             hci_send_cmd(&hci_read_bd_addr);
2070             break;
2071         case HCI_INIT_READ_BUFFER_SIZE:
2072             // only read buffer size if supported
2073             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE)){
2074                 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
2075                 hci_send_cmd(&hci_read_buffer_size);
2076                 break;
2077             }
2078 
2079             /* fall through */
2080 
2081         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
2082             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
2083             hci_send_cmd(&hci_read_local_supported_features);
2084             break;
2085 
2086 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2087         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
2088             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
2089             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
2090             break;
2091         case HCI_INIT_HOST_BUFFER_SIZE:
2092             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
2093             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
2094                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
2095             break;
2096 #endif
2097 
2098         case HCI_INIT_SET_EVENT_MASK:
2099             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
2100             if (hci_le_supported()){
2101                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
2102             } else {
2103                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
2104                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
2105             }
2106             break;
2107 
2108         case HCI_INIT_SET_EVENT_MASK_2:
2109             // On Bluettooth PTS dongle (BL 654) with PacketCraft HCI Firmware (LMP subversion) 0x5244,
2110             // setting Event Mask 2 causes Controller to drop Encryption Change events.
2111             if (hci_command_supported(SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2)
2112             && (hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC)){
2113                 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK_2;
2114                 // Encryption Change Event v2 - bit 25
2115                 hci_send_cmd(&hci_set_event_mask_2,0x02000000U, 0x0);
2116                 break;
2117             }
2118 
2119 #ifdef ENABLE_CLASSIC
2120             /* fall through */
2121 
2122         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
2123             if (hci_classic_supported() && gap_ssp_supported()){
2124                 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
2125                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
2126                 break;
2127             }
2128 
2129             /* fall through */
2130 
2131         case HCI_INIT_WRITE_INQUIRY_MODE:
2132             if (hci_classic_supported()){
2133                 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
2134                 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
2135                 break;
2136             }
2137 
2138             /* fall through */
2139 
2140         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
2141             // skip write secure connections host support if not supported or disabled
2142             if (hci_classic_supported() && hci_stack->secure_connections_enable
2143             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST)) {
2144                 hci_stack->secure_connections_active = true;
2145                 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
2146                 hci_send_cmd(&hci_write_secure_connections_host_support, 1);
2147                 break;
2148             }
2149 
2150             /* fall through */
2151 
2152         case HCI_INIT_SET_MIN_ENCRYPTION_KEY_SIZE:
2153             // skip set min encryption key size
2154             if (hci_classic_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE)) {
2155                 hci_stack->substate = HCI_INIT_W4_SET_MIN_ENCRYPTION_KEY_SIZE;
2156                 hci_send_cmd(&hci_set_min_encryption_key_size, hci_stack->gap_required_encyrption_key_size);
2157                 break;
2158             }
2159 
2160 #ifdef ENABLE_SCO_OVER_HCI
2161             /* fall through */
2162 
2163         // only sent if ENABLE_SCO_OVER_HCI is defined
2164         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2165             // skip write synchronous flow control if not supported
2166             if (hci_classic_supported()
2167             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)) {
2168                 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
2169                 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
2170                 break;
2171             }
2172             /* fall through */
2173 
2174         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
2175             // skip write default erroneous data reporting if not supported
2176             if (hci_classic_supported()
2177             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) {
2178                 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
2179                 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
2180                 break;
2181             }
2182 #endif
2183 
2184 #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM)
2185             /* fall through */
2186 
2187         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
2188         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
2189             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2190                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
2191 #ifdef ENABLE_SCO_OVER_HCI
2192                 log_info("BCM: Route SCO data via HCI transport");
2193                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
2194 #endif
2195 #ifdef ENABLE_SCO_OVER_PCM
2196                 log_info("BCM: Route SCO data via PCM interface");
2197 #ifdef ENABLE_BCM_PCM_WBS
2198                 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz
2199                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
2200 #else
2201                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
2202                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
2203 #endif
2204 #endif
2205                 break;
2206             }
2207 #endif
2208 
2209 #ifdef ENABLE_SCO_OVER_PCM
2210             /* fall through */
2211 
2212         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
2213             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2214                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
2215                 log_info("BCM: Config PCM interface for I2S");
2216 #ifdef ENABLE_BCM_PCM_WBS
2217                 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
2218                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
2219 #else
2220                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
2221                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
2222 #endif
2223                 break;
2224             }
2225         case HCI_INIT_BCM_WRITE_PCM_DATA_FORMAT_PARAM:
2226             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2227                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_PCM_DATA_FORMAT_PARAM;
2228                 log_info("BCM: Config PCM Data format");
2229                 // msb first, fill bits 0, left justified
2230                 hci_send_cmd(&hci_bcm_write_pcm_data_format_param, 0, 0, 3, 3, 0);
2231                 break;
2232             }
2233 #ifdef HAVE_BCM_PCM2
2234         case HCI_INIT_BCM_PCM2_SETUP:
2235             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)) {
2236                 hci_stack->substate = HCI_INIT_W4_BCM_PCM2_SETUP;
2237                 uint8_t  op_mode = 0;  // Op_Mode = 0 = PCM, 1 = I2S
2238                 uint32_t pcm_clock_freq;
2239                 uint8_t  ch_0_period;
2240 #ifdef ENABLE_BCM_PCM_WBS
2241                 // 512 kHz, resample 8 kHz to 16 khz
2242                 pcm_clock_freq = 512000;
2243                 ch_0_period = 1;
2244 #else
2245                 // 256 khz, 8 khz output
2246                 pcm_clock_freq = 256000;
2247                 ch_0_period = 0;
2248 #endif
2249                 log_info("BCM: Config PCM2 - op mode %u, pcm clock %" PRIu32 ", ch0_period %u", op_mode, pcm_clock_freq, ch_0_period);
2250                 hci_send_cmd(&hci_bcm_pcm2_setup,
2251                              0x00, // Action = Write
2252                              0x00, // Test_Options = None
2253                              op_mode, // Op_Mode
2254                              0x1D, // Sync_and_Clock_Options Sync = Signal | Sync Output Enable | Generate PCM_CLK | Tristate When Idle
2255                              pcm_clock_freq, // PCM_Clock_Freq
2256                              0x01, // Sync_Signal_Width
2257                              0x0F, // Slot_Width
2258                              0x01, // NumberOfSlots
2259                              0x00, // Bank_0_Fill_Mode = 0s
2260                              0x00, // Bank_0_Number_of_Fill_Bits
2261                              0x00, // Bank_0_Programmable_Fill_Data
2262                              0x00, // Bank_1_Fill_Mode = 0s
2263                              0x00, // Bank_1_Number_of_Fill_Bits
2264                              0x00, // Bank_1_Programmable_Fill_Data
2265                              0x00, // Data_Justify_And_Bit_Order_Options = Left Justify
2266                              0x00, // Ch_0_Slot_Number
2267                              0x01, // Ch_1_Slot_Number
2268                              0x02, // Ch_2_Slot_Number
2269                              0x03, // Ch_3_Slot_Number
2270                              0x04, // Ch_4_Slot_Number
2271                              ch_0_period, // Ch_0_Period
2272                              0x00, // Ch_1_Period
2273                              0x00  // Ch_2_Period
2274                 );
2275                 break;
2276             }
2277 #endif
2278 #endif /* ENABLE_SCO_OVER_PCM */
2279 #endif /* ENABLE_CLASSIC */
2280 
2281 #ifdef ENABLE_BLE
2282             /* fall through */
2283 
2284         // LE INIT
2285         case HCI_INIT_LE_READ_BUFFER_SIZE:
2286             if (hci_le_supported()){
2287                 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
2288                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2)){
2289                     hci_send_cmd(&hci_le_read_buffer_size_v2);
2290                 } else {
2291                     hci_send_cmd(&hci_le_read_buffer_size);
2292                 }
2293                 break;
2294             }
2295 
2296             /* fall through */
2297 
2298         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
2299             // skip write le host if not supported (e.g. on LE only EM9301)
2300             if (hci_le_supported()
2301             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED)) {
2302                 // LE Supported Host = 1, Simultaneous Host = 0
2303                 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
2304                 hci_send_cmd(&hci_write_le_host_supported, 1, 0);
2305                 break;
2306             }
2307 
2308             /* fall through */
2309 
2310         case HCI_INIT_LE_SET_EVENT_MASK:
2311             if (hci_le_supported()){
2312                 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
2313 #ifdef ENABLE_LE_ENHANCED_CONNECTION_COMPLETE_EVENT
2314                 hci_send_cmd(&hci_le_set_event_mask, 0xffffffff, 0x0107); // all events from core v5.3
2315 #else
2316                 hci_send_cmd(&hci_le_set_event_mask, 0xfffffdff, 0x0007); // all events from core v5.3 without LE Enhanced Connection Complete
2317 #endif
2318                 break;
2319             }
2320 #endif
2321 
2322 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2323             /* fall through */
2324 
2325         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
2326             if (hci_le_supported()
2327             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH)) {
2328                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
2329                 hci_send_cmd(&hci_le_read_maximum_data_length);
2330                 break;
2331             }
2332 
2333             /* fall through */
2334 
2335         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
2336             if (hci_le_supported()
2337             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH)) {
2338                 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
2339                 hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
2340                 break;
2341             }
2342 #endif
2343 
2344 #ifdef ENABLE_LE_CENTRAL
2345             /* fall through */
2346 
2347         case HCI_INIT_READ_WHITE_LIST_SIZE:
2348             if (hci_le_supported()){
2349                 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
2350                 hci_send_cmd(&hci_le_read_white_list_size);
2351                 break;
2352             }
2353 
2354 #endif
2355 
2356 #ifdef ENABLE_LE_PERIPHERAL
2357 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
2358             /* fall through */
2359 
2360         case HCI_INIT_LE_READ_MAX_ADV_DATA_LEN:
2361             if (hci_le_extended_advertising_supported()){
2362                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_ADV_DATA_LEN;
2363                 hci_send_cmd(&hci_le_read_maximum_advertising_data_length);
2364                 break;
2365             }
2366 #endif
2367 #endif
2368             /* fall through */
2369 
2370 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2371     case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS:
2372             if (hci_le_supported()) {
2373                 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS;
2374                 hci_send_cmd(&hci_le_set_host_feature, 32, 1);
2375                 break;
2376             }
2377 #endif
2378 
2379             /* fall through */
2380 
2381         case HCI_INIT_DONE:
2382             hci_stack->substate = HCI_INIT_DONE;
2383             // main init sequence complete
2384 #ifdef ENABLE_CLASSIC
2385             // check if initial Classic GAP Tasks are completed
2386             if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) {
2387                 hci_run_gap_tasks_classic();
2388                 break;
2389             }
2390 #endif
2391 #ifdef ENABLE_BLE
2392 #ifdef ENABLE_LE_CENTRAL
2393             // check if initial LE GAP Tasks are completed
2394             if (hci_le_supported() && hci_stack->le_scanning_param_update) {
2395                 hci_run_general_gap_le();
2396                 break;
2397             }
2398 #endif
2399 #endif
2400             hci_init_done();
2401             break;
2402 
2403         default:
2404             return;
2405     }
2406 }
2407 
2408 static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
2409     bool command_completed = false;
2410     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
2411         uint16_t opcode = little_endian_read_16(packet,3);
2412         if (opcode == hci_stack->last_cmd_opcode){
2413             command_completed = true;
2414             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
2415         } else {
2416             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
2417         }
2418     }
2419 
2420     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
2421         uint8_t  status = packet[2];
2422         uint16_t opcode = little_endian_read_16(packet,4);
2423         if (opcode == hci_stack->last_cmd_opcode){
2424             if (status){
2425                 command_completed = true;
2426                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
2427             } else {
2428                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
2429             }
2430         } else {
2431             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
2432         }
2433     }
2434 #ifndef HAVE_HOST_CONTROLLER_API
2435     // Vendor == CSR
2436     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2437         // TODO: track actual command
2438         command_completed = true;
2439     }
2440 
2441     // Vendor == Toshiba
2442     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2443         // TODO: track actual command
2444         command_completed = true;
2445         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
2446         hci_stack->num_cmd_packets = 1;
2447     }
2448 #endif
2449 
2450     return command_completed;
2451 }
2452 
2453 static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
2454 
2455     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
2456 
2457     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
2458 
2459 #ifndef HAVE_HOST_CONTROLLER_API
2460 
2461     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
2462     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
2463     //
2464     // HCI Reset
2465     // Timeout 100 ms
2466     // HCI Reset
2467     // Command Complete Reset
2468     // HCI Read Local Version Information
2469     // Command Complete Reset - but we expected Command Complete Read Local Version Information
2470     // hang...
2471     //
2472     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
2473     if (!command_completed
2474             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2475             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
2476 
2477         uint16_t opcode = little_endian_read_16(packet,3);
2478         if (opcode == hci_reset.opcode){
2479             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
2480             return;
2481         }
2482     }
2483 
2484     // CSR & H5
2485     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
2486     if (!command_completed
2487             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2488             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
2489 
2490         uint16_t opcode = little_endian_read_16(packet,3);
2491         if (opcode == hci_reset.opcode){
2492             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
2493             return;
2494         }
2495     }
2496 
2497     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
2498     // fix: Correct substate and behave as command below
2499     if (command_completed){
2500         switch (hci_stack->substate){
2501             case HCI_INIT_SEND_RESET:
2502                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
2503                 break;
2504             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
2505                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
2506                 break;
2507             default:
2508                 break;
2509         }
2510     }
2511 
2512 #endif
2513 
2514     if (!command_completed) return;
2515 
2516     bool need_baud_change = false;
2517     bool need_addr_change = false;
2518 
2519 #ifndef HAVE_HOST_CONTROLLER_API
2520     need_baud_change = hci_stack->config
2521                         && hci_stack->chipset
2522                         && hci_stack->chipset->set_baudrate_command
2523                         && hci_stack->hci_transport->set_baudrate
2524                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
2525 
2526     need_addr_change = hci_stack->custom_bd_addr_set
2527                         && hci_stack->chipset
2528                         && hci_stack->chipset->set_bd_addr_command;
2529 #endif
2530 
2531     switch(hci_stack->substate){
2532 
2533 #ifndef HAVE_HOST_CONTROLLER_API
2534         case HCI_INIT_SEND_RESET:
2535             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
2536             // fix: just correct substate and behave as command below
2537 
2538             /* fall through */
2539 #endif
2540 
2541         case HCI_INIT_W4_SEND_RESET:
2542             btstack_run_loop_remove_timer(&hci_stack->timeout);
2543             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
2544             return;
2545 
2546 #ifndef HAVE_HOST_CONTROLLER_API
2547         case HCI_INIT_W4_SEND_BAUD_CHANGE:
2548             // for STLC2500D, baud rate change already happened.
2549             // for others, baud rate gets changed now
2550             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
2551                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2552                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
2553                 hci_stack->hci_transport->set_baudrate(baud_rate);
2554             }
2555             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2556             return;
2557         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
2558             btstack_run_loop_remove_timer(&hci_stack->timeout);
2559             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2560             return;
2561         case HCI_INIT_W4_CUSTOM_INIT:
2562             // repeat custom init
2563             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2564             return;
2565         case HCI_INIT_W4_CUSTOM_PRE_INIT:
2566             // repeat custom init
2567             hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
2568             return;
2569 #endif
2570 
2571         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
2572             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2573               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
2574                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
2575                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
2576                 return;
2577             }
2578             if (need_addr_change){
2579                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2580                 return;
2581             }
2582             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2583             return;
2584 #ifndef HAVE_HOST_CONTROLLER_API
2585         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
2586             if (need_baud_change){
2587                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2588                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
2589                 hci_stack->hci_transport->set_baudrate(baud_rate);
2590             }
2591             if (need_addr_change){
2592                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2593                 return;
2594             }
2595             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2596             return;
2597         case HCI_INIT_W4_SET_BD_ADDR:
2598             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
2599             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
2600             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
2601                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
2602                 return;
2603             }
2604             // skipping st warm boot
2605             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2606             return;
2607         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
2608             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2609             return;
2610 #endif
2611 
2612         case HCI_INIT_DONE:
2613             // set state if we came here by fall through
2614             hci_stack->substate = HCI_INIT_DONE;
2615             return;
2616 
2617         default:
2618             break;
2619     }
2620     hci_initializing_next_state();
2621 }
2622 
2623 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
2624     // CC2564C might emit Connection Complete for rejected incoming SCO connection
2625     // To prevent accidentally free'ing the HCI connection for the ACL connection,
2626     // check if we have been aware of the HCI connection
2627     switch (conn->state){
2628         case SENT_CREATE_CONNECTION:
2629         case RECEIVED_CONNECTION_REQUEST:
2630         case ACCEPTED_CONNECTION_REQUEST:
2631             break;
2632         default:
2633             return;
2634     }
2635 
2636     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
2637     bd_addr_t bd_address;
2638     (void)memcpy(&bd_address, conn->address, 6);
2639 
2640 #ifdef ENABLE_CLASSIC
2641     // cache needed data
2642     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
2643 #endif
2644 
2645     // connection failed, remove entry
2646     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2647     btstack_memory_hci_connection_free( conn );
2648 
2649 #ifdef ENABLE_CLASSIC
2650     // notify client if dedicated bonding
2651     if (notify_dedicated_bonding_failed){
2652         log_info("hci notify_dedicated_bonding_failed");
2653         hci_emit_dedicated_bonding_result(bd_address, status);
2654     }
2655 
2656     // if authentication error, also delete link key
2657     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
2658         gap_drop_link_key_for_bd_addr(bd_address);
2659     }
2660 #else
2661     UNUSED(status);
2662 #endif
2663 }
2664 
2665 #ifdef ENABLE_CLASSIC
2666 static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
2667     // SSP Controller
2668     if (features[6] & (1 << 3)){
2669         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
2670     }
2671     // eSCO
2672     if (features[3] & (1<<7)){
2673         conn->remote_supported_features[0] |= 1;
2674     }
2675     // Extended features
2676     if (features[7] & (1<<7)){
2677         conn->remote_supported_features[0] |= 2;
2678     }
2679     // SCO packet types
2680     conn->remote_supported_sco_packets = hci_sco_packet_types_for_features(features);
2681 }
2682 
2683 static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
2684     // SSP Host
2685     if (features[0] & (1 << 0)){
2686         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
2687     }
2688     // SC Host
2689     if (features[0] & (1 << 3)){
2690         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
2691     }
2692 }
2693 
2694 static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
2695     // SC Controller
2696     if (features[1] & (1 << 0)){
2697         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2698     }
2699 }
2700 
2701 static void hci_handle_remote_features_received(hci_connection_t * conn){
2702     conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE;
2703     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2704     log_info("Remote features %02x, bonding flags %" PRIx32, conn->remote_supported_features[0], conn->bonding_flags);
2705     if (conn->bonding_flags & BONDING_DEDICATED){
2706         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2707     }
2708 }
2709 static bool hci_remote_sc_enabled(hci_connection_t * connection){
2710     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2711     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2712 }
2713 
2714 #endif
2715 
2716 static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
2717     // handle BT initialization
2718     if (hci_stack->state == HCI_STATE_INITIALIZING) {
2719         hci_initializing_event_handler(packet, size);
2720     }
2721 
2722     // help with BT sleep
2723     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
2724         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
2725         && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2726         && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){
2727         hci_initializing_next_state();
2728     }
2729 }
2730 
2731 #ifdef ENABLE_CLASSIC
2732 static void hci_handle_mutual_authentication_completed(hci_connection_t * conn){
2733     // bonding complete if connection is authenticated (either initiated or BR/EDR SC)
2734     conn->requested_security_level = LEVEL_0;
2735     gap_security_level_t security_level = gap_security_level_for_connection(conn);
2736     hci_emit_security_level(conn->con_handle, security_level);
2737 
2738     // dedicated bonding
2739     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
2740         conn->bonding_flags &= ~BONDING_DEDICATED;
2741         conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS;
2742 #ifdef ENABLE_EXPLICIT_DEDICATED_BONDING_DISCONNECT
2743         // emit dedicated bonding complete, don't disconnect
2744         hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
2745 #else
2746         // request disconnect, event is emitted after disconnect
2747         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2748 #endif
2749     }
2750 }
2751 
2752 static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
2753     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2754     conn->encryption_key_size = encryption_key_size;
2755 
2756     // mutual authentication complete if authenticated and we have retrieved the encryption key size
2757     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
2758         hci_handle_mutual_authentication_completed(conn);
2759     } else {
2760         // otherwise trigger remote feature request and send authentication request
2761         hci_trigger_remote_features_for_connection(conn);
2762         if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) == 0) {
2763             conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2764         }
2765     }
2766 }
2767 #endif
2768 
2769 static void hci_store_local_supported_commands(const uint8_t * packet){
2770     // create mapping table
2771 #define X(name, offset, bit) { offset, bit },
2772     static struct {
2773         uint8_t byte_offset;
2774         uint8_t bit_position;
2775     } supported_hci_commands_map [] = {
2776         SUPPORTED_HCI_COMMANDS
2777     };
2778 #undef X
2779 
2780     // create names for debug purposes
2781 #ifdef ENABLE_LOG_DEBUG
2782 #define X(name, offset, bit) #name,
2783     static const char * command_names[] = {
2784         SUPPORTED_HCI_COMMANDS
2785     };
2786 #undef X
2787 #endif
2788 
2789     hci_stack->local_supported_commands = 0;
2790     const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1];
2791     uint16_t i;
2792     for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){
2793         if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){
2794 #ifdef ENABLE_LOG_DEBUG
2795             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);
2796 #else
2797             log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
2798 #endif
2799             hci_stack->local_supported_commands |= (1LU << i);
2800         }
2801     }
2802     log_info("Local supported commands summary %08" PRIx32, hci_stack->local_supported_commands);
2803 }
2804 
2805 static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2806     UNUSED(size);
2807 
2808     uint8_t status = 0;
2809     if( size > OFFSET_OF_DATA_IN_COMMAND_COMPLETE ) {
2810         status = hci_event_command_complete_get_return_parameters(packet)[0];
2811     }
2812     uint16_t manufacturer;
2813 #ifdef ENABLE_CLASSIC
2814     hci_connection_t * conn;
2815 #endif
2816 #if defined(ENABLE_CLASSIC) || (defined(ENABLE_BLE) && defined(ENABLE_LE_ISOCHRONOUS_STREAMS))
2817     hci_con_handle_t handle;
2818 #endif
2819 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2820     le_audio_cig_t * cig;
2821 #endif
2822 #if defined(ENABLE_BLE) && defined(ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
2823     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
2824 #endif
2825 
2826     // get num cmd packets - limit to 1 to reduce complexity
2827     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
2828 
2829     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2830     switch (opcode){
2831         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2832             if (status) break;
2833             // terminate, name 248 chars
2834             packet[6+248] = 0;
2835             log_info("local name: %s", &packet[6]);
2836             break;
2837         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
2838             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2839             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2840                 uint16_t acl_len = little_endian_read_16(packet, 6);
2841                 uint16_t sco_len = packet[8];
2842 
2843                 // determine usable ACL/SCO payload size
2844                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2845                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2846 
2847                 hci_stack->acl_packets_total_num = (uint8_t) btstack_min(little_endian_read_16(packet,  9), MAX_NR_CONTROLLER_ACL_BUFFERS);
2848                 hci_stack->sco_packets_total_num = (uint8_t) btstack_min(little_endian_read_16(packet, 11), MAX_NR_CONTROLLER_SCO_PACKETS);
2849 
2850                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2851                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
2852                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2853             }
2854             break;
2855         case HCI_OPCODE_HCI_READ_RSSI:
2856             if (status == ERROR_CODE_SUCCESS){
2857                 uint8_t event[5];
2858                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2859                 event[1] = 3;
2860                 (void)memcpy(&event[2], &packet[6], 3);
2861                 hci_emit_event(event, sizeof(event), 1);
2862             }
2863             break;
2864 #ifdef ENABLE_BLE
2865         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2:
2866             hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9);
2867             hci_stack->le_iso_packets_total_num = packet[11];
2868             log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u",
2869                      hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num);
2870 
2871             /* fall through */
2872 
2873         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2874             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2875             hci_stack->le_acl_packets_total_num = packet[8];
2876             // determine usable ACL payload size
2877             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
2878                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
2879             }
2880             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);
2881             break;
2882 #endif
2883 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2884         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2885             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2886             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2887             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);
2888             break;
2889 #endif
2890 #ifdef ENABLE_LE_CENTRAL
2891         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2892             hci_stack->le_whitelist_capacity = packet[6];
2893             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2894             break;
2895 #endif
2896 #ifdef ENABLE_LE_PERIPHERAL
2897 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
2898         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH:
2899             hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6);
2900             break;
2901         case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS:
2902             if (hci_stack->le_advertising_set_in_current_command != 0) {
2903                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2904                 hci_stack->le_advertising_set_in_current_command = 0;
2905                 if (advertising_set == NULL) break;
2906                 uint8_t adv_status = packet[6];
2907                 uint8_t tx_power   = packet[7];
2908                 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 };
2909                 if (adv_status == 0){
2910                     advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
2911                 }
2912                 hci_emit_event(event, sizeof(event), 1);
2913             }
2914             break;
2915         case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET:
2916             if (hci_stack->le_advertising_set_in_current_command != 0) {
2917                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2918                 hci_stack->le_advertising_set_in_current_command = 0;
2919                 if (advertising_set == NULL) break;
2920                 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, status };
2921                 if (status == 0){
2922                     btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set);
2923                 }
2924                 hci_emit_event(event, sizeof(event), 1);
2925             }
2926             break;
2927 #endif
2928 #endif
2929         case HCI_OPCODE_HCI_READ_BD_ADDR:
2930             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2931             log_info("Local Address, Status: 0x%02x: Addr: %s", status, bd_addr_to_str(hci_stack->local_bd_addr));
2932 #ifdef ENABLE_CLASSIC
2933             if (hci_stack->link_key_db){
2934                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
2935             }
2936 #endif
2937             break;
2938 #ifdef ENABLE_CLASSIC
2939         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
2940             hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
2941             break;
2942         case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE:
2943             if (status == ERROR_CODE_SUCCESS) {
2944                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC;
2945             } else {
2946                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2947             }
2948             break;
2949         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2950         case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE:
2951             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2952                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2953                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2954                 hci_emit_event(event, sizeof(event), 1);
2955             }
2956             break;
2957 #endif
2958         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
2959             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
2960 
2961 #ifdef ENABLE_CLASSIC
2962             // determine usable ACL packet types based on host buffer size and supported features
2963             hci_stack->usable_packet_types_acl = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
2964             log_info("ACL Packet types %04x", hci_stack->usable_packet_types_acl);
2965             // determine usable SCO packet types based on supported features
2966             hci_stack->usable_packet_types_sco = hci_sco_packet_types_for_features(
2967                     &hci_stack->local_supported_features[0]);
2968             log_info("SCO Packet types %04x - eSCO %u", hci_stack->usable_packet_types_sco, hci_extended_sco_link_supported());
2969 #endif
2970             // Classic/LE
2971             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2972             break;
2973         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2974             manufacturer = little_endian_read_16(packet, 10);
2975             // map Cypress & Infineon to Broadcom
2976             switch (manufacturer){
2977                 case BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR:
2978                 case BLUETOOTH_COMPANY_ID_INFINEON_TECHNOLOGIES_AG:
2979                     log_info("Treat Cypress/Infineon as Broadcom");
2980                     manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2981                     little_endian_store_16(packet, 10, manufacturer);
2982                     break;
2983                 default:
2984                     break;
2985             }
2986             hci_stack->manufacturer = manufacturer;
2987             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2988             break;
2989         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2990             hci_store_local_supported_commands(packet);
2991             break;
2992 #ifdef ENABLE_CLASSIC
2993         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2994             if (status) return;
2995             hci_stack->synchronous_flow_control_enabled = 1;
2996             break;
2997         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2998             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2999             conn   = hci_connection_for_handle(handle);
3000             if (conn != NULL) {
3001                 uint8_t key_size = 0;
3002                 if (status == 0){
3003                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
3004                     log_info("Handle %04x key Size: %u", handle, key_size);
3005                 } else {
3006                     key_size = 1;
3007                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
3008                 }
3009                 hci_handle_read_encryption_key_size_complete(conn, key_size);
3010             }
3011             break;
3012         // assert pairing complete event is emitted.
3013         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
3014         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
3015         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
3016         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
3017             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3018             // lookup connection by gap pairing addr
3019             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
3020             if (conn == NULL) break;
3021             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
3022             break;
3023 
3024 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3025         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
3026         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
3027             uint8_t event[67];
3028             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
3029             event[1] = 65;
3030             (void)memset(&event[2], 0, 65);
3031             if (status == ERROR_CODE_SUCCESS){
3032                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
3033                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
3034                     event[2] = 3;
3035                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
3036                 } else {
3037                     event[2] = 1;
3038                 }
3039             }
3040             hci_emit_event(event, sizeof(event), 0);
3041             break;
3042         }
3043 
3044         // note: only needed if user does not provide OOB data
3045         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
3046             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
3047             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
3048             if (conn == NULL) break;
3049             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
3050             break;
3051 #endif
3052 #endif
3053 #ifdef ENABLE_BLE
3054 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3055         case HCI_OPCODE_HCI_LE_SET_CIG_PARAMETERS:
3056             // lookup CIG
3057             cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
3058             if (cig != NULL){
3059                 uint8_t i = 0;
3060                 if (status == ERROR_CODE_SUCCESS){
3061                     // assign CIS handles to pre-allocated CIS
3062                     btstack_linked_list_iterator_t it;
3063                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3064                     while (btstack_linked_list_iterator_has_next(&it) && (i < cig->num_cis)) {
3065                         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3066                         if ((iso_stream->group_id == hci_stack->iso_active_operation_group_id) &&
3067                             (iso_stream->iso_type == HCI_ISO_TYPE_CIS)){
3068                             hci_con_handle_t cis_handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3+(2*i));
3069                             iso_stream->cis_handle  = cis_handle;
3070                             cig->cis_con_handles[i] = cis_handle;
3071                             i++;
3072                         }
3073                     }
3074                     cig->state = LE_AUDIO_CIG_STATE_W4_CIS_REQUEST;
3075                     hci_emit_cig_created(cig, status);
3076                 } else {
3077                     hci_emit_cig_created(cig, status);
3078                     btstack_linked_list_remove(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
3079                 }
3080             }
3081             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3082             break;
3083         case HCI_OPCODE_HCI_LE_CREATE_CIS:
3084             if (status != ERROR_CODE_SUCCESS){
3085                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3086             }
3087             break;
3088         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
3089             if (status != ERROR_CODE_SUCCESS){
3090                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3091             }
3092             break;
3093         case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: {
3094             // lookup BIG by state
3095             btstack_linked_list_iterator_t it;
3096             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
3097             while (btstack_linked_list_iterator_has_next(&it)) {
3098                 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
3099                 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
3100                     if (status == ERROR_CODE_SUCCESS){
3101                         big->state_vars.next_bis++;
3102                         if (big->state_vars.next_bis == big->num_bis){
3103                             big->state = LE_AUDIO_BIG_STATE_ACTIVE;
3104                             hci_emit_big_created(big, ERROR_CODE_SUCCESS);
3105                         } else {
3106                             big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
3107                         }
3108                     } else {
3109                         big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
3110                         big->state_vars.status = status;
3111                     }
3112                     return;
3113                 }
3114             }
3115             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
3116             while (btstack_linked_list_iterator_has_next(&it)) {
3117                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
3118                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
3119                     if (status == ERROR_CODE_SUCCESS){
3120                         big_sync->state_vars.next_bis++;
3121                         if (big_sync->state_vars.next_bis == big_sync->num_bis){
3122                             big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE;
3123                             hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS);
3124                         } else {
3125                             big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
3126                         }
3127                     } else {
3128                         big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
3129                         big_sync->state_vars.status = status;
3130                     }
3131                     return;
3132                 }
3133             }
3134             // Lookup CIS via active group operation
3135             if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
3136                 if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
3137                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3138 
3139                     // lookup CIS by state
3140                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3141                     while (btstack_linked_list_iterator_has_next(&it)){
3142                         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3143                         handle = iso_stream->cis_handle;
3144                         bool emit_cis_created = false;
3145                         switch (iso_stream->state){
3146                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT:
3147                                 if (status != ERROR_CODE_SUCCESS){
3148                                     emit_cis_created = true;
3149                                     break;
3150                                 }
3151                                 if (iso_stream->max_sdu_c_to_p > 0){
3152                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
3153                                 } else {
3154                                     emit_cis_created = true;
3155                                 }
3156                                 break;
3157                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT:
3158                                 emit_cis_created = true;
3159                                 break;
3160                             default:
3161                                 break;
3162                         }
3163                         if (emit_cis_created){
3164                             hci_cis_handle_created(iso_stream, status);
3165                         }
3166                     }
3167                 } else {
3168                     cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
3169                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3170                     if (cig != NULL) {
3171                         // emit cis created if all ISO Paths have been created
3172                         // assume we are central
3173                         uint8_t cis_index     = cig->state_vars.next_cis >> 1;
3174                         uint8_t cis_direction = cig->state_vars.next_cis & 1;
3175                         bool outgoing_needed  = cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
3176                         // if outgoing has been setup, or incoming was setup but outgoing not required
3177                         if ((cis_direction == 1) || (outgoing_needed == false)){
3178                             // lookup iso stream by cig/cis
3179                             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3180                             while (btstack_linked_list_iterator_has_next(&it)) {
3181                                 hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3182                                 if ((iso_stream->group_id == cig->cig_id) && (iso_stream->stream_id == cis_index)){
3183                                     hci_cis_handle_created(iso_stream, status);
3184                                 }
3185                             }
3186                         }
3187                         // next state
3188                         cig->state_vars.next_cis++;
3189                         cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
3190                     }
3191                 }
3192             }
3193             break;
3194         }
3195         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
3196             // lookup BIG by state
3197             btstack_linked_list_iterator_t it;
3198             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
3199             while (btstack_linked_list_iterator_has_next(&it)) {
3200                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
3201                 uint8_t big_handle = big_sync->big_handle;
3202                 switch (big_sync->state){
3203                     case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
3204                         btstack_linked_list_iterator_remove(&it);
3205                         hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
3206                         return;
3207                     default:
3208                         btstack_linked_list_iterator_remove(&it);
3209                         hci_emit_big_sync_stopped(big_handle);
3210                         return;
3211                 }
3212             }
3213             break;
3214         }
3215 #endif
3216 #endif
3217         default:
3218             break;
3219     }
3220 }
3221 
3222 static void handle_command_status_event(uint8_t * packet, uint16_t size) {
3223     UNUSED(size);
3224 
3225     // get num cmd packets - limit to 1 to reduce complexity
3226     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
3227 
3228     // get opcode and command status
3229     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
3230 
3231 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
3232     uint8_t status = hci_event_command_status_get_status(packet);
3233 #endif
3234 
3235 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3236     bd_addr_type_t addr_type;
3237     bd_addr_t addr;
3238 #endif
3239 
3240 #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
3241     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
3242 #endif
3243 
3244     switch (opcode){
3245 #ifdef ENABLE_CLASSIC
3246         case HCI_OPCODE_HCI_CREATE_CONNECTION:
3247         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
3248         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
3249 #endif
3250 #ifdef ENABLE_LE_CENTRAL
3251         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
3252 #endif
3253 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3254             addr_type = hci_stack->outgoing_addr_type;
3255             memcpy(addr, hci_stack->outgoing_addr, 6);
3256 
3257             // reset outgoing address info
3258             memset(hci_stack->outgoing_addr, 0, 6);
3259             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
3260 
3261             // on error
3262             if (status != ERROR_CODE_SUCCESS){
3263 #ifdef ENABLE_LE_CENTRAL
3264                 if (hci_is_le_connection_type(addr_type)){
3265                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3266                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3267                 }
3268 #endif
3269                 // error => outgoing connection failed
3270                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3271                 if (conn != NULL){
3272                     hci_handle_connection_failed(conn, status);
3273                 }
3274             }
3275             break;
3276 #endif
3277 #ifdef ENABLE_CLASSIC
3278         case HCI_OPCODE_HCI_INQUIRY:
3279             if (status == ERROR_CODE_SUCCESS) {
3280                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3281             } else {
3282                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3283             }
3284             break;
3285 #endif
3286 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3287         case HCI_OPCODE_HCI_LE_CREATE_CIS:
3288         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
3289             if (status == ERROR_CODE_SUCCESS){
3290                 hci_iso_stream_requested_confirm(HCI_ISO_GROUP_ID_INVALID);
3291             } else {
3292                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3293             }
3294             break;
3295 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
3296         default:
3297             break;
3298     }
3299 }
3300 
3301 #ifdef ENABLE_BLE
3302 static void hci_create_gap_connection_complete_event(const uint8_t * hci_event, uint8_t * gap_event) {
3303     gap_event[0] = HCI_EVENT_META_GAP;
3304     gap_event[1] = 36 - 2;
3305     gap_event[2] = GAP_SUBEVENT_LE_CONNECTION_COMPLETE;
3306     switch (hci_event_le_meta_get_subevent_code(hci_event)){
3307         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3308             memcpy(&gap_event[3], &hci_event[3], 11);
3309             memset(&gap_event[14], 0, 12);
3310             memcpy(&gap_event[26], &hci_event[14], 7);
3311             memset(&gap_event[33], 0xff, 3);
3312             break;
3313         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
3314             memcpy(&gap_event[3], &hci_event[3], 30);
3315             memset(&gap_event[33], 0xff, 3);
3316             break;
3317         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
3318             memcpy(&gap_event[3], &hci_event[3], 33);
3319             break;
3320         default:
3321             btstack_unreachable();
3322             break;
3323     }
3324 }
3325 
3326 static void hci_handle_le_connection_complete_event(const uint8_t * hci_event){
3327 	bd_addr_t addr;
3328 	bd_addr_type_t addr_type;
3329 	hci_connection_t * conn;
3330 
3331     // create GAP_SUBEVENT_LE_CONNECTION_COMPLETE
3332     uint8_t gap_event[36];
3333     hci_create_gap_connection_complete_event(hci_event, gap_event);
3334 
3335     // read fields
3336     uint8_t status = gap_subevent_le_connection_complete_get_status(gap_event);
3337     hci_role_t role = (hci_role_t) gap_subevent_le_connection_complete_get_role(gap_event);
3338     uint16_t conn_interval = gap_subevent_le_connection_complete_get_conn_interval(gap_event);
3339 
3340 	// Connection management
3341     gap_subevent_le_connection_complete_get_peer_address(gap_event, addr);
3342 	addr_type = (bd_addr_type_t) gap_subevent_le_connection_complete_get_peer_address_type(gap_event);
3343     log_info("LE Connection_complete (status=%u) type %u, %s", status, addr_type, bd_addr_to_str(addr));
3344 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3345 
3346 #ifdef ENABLE_LE_CENTRAL
3347 	// handle error: error is reported only to the initiator -> outgoing connection
3348 	if (status){
3349 
3350 		// handle cancelled outgoing connection
3351 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
3352 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
3353 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
3354 		if (status == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
3355 		    // reset state
3356             hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3357 			// get outgoing connection conn struct for direct connect
3358             if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
3359                 conn = gap_get_outgoing_le_connection();
3360                 conn->state = SEND_CREATE_CONNECTION;
3361             }
3362 		}
3363 
3364 		// free connection if cancelled by user (request == IDLE)
3365 		if ((conn != NULL) && (hci_stack->le_connecting_request == LE_CONNECTING_IDLE)){
3366 			// remove entry
3367 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3368 			btstack_memory_hci_connection_free( conn );
3369 		}
3370 		return;
3371 	}
3372 #endif
3373 
3374 	// on success, both hosts receive connection complete event
3375     if (role == HCI_ROLE_MASTER){
3376 #ifdef ENABLE_LE_CENTRAL
3377 		// if we're master, it was an outgoing connection
3378 		// note: no hci_connection_t object exists yet for connect with whitelist
3379 
3380         // if a identity addresses was used without enhanced connection complete event,
3381         // the connection complete event contains the current random address of the peer device.
3382         // This random address is needed in the case of a re-pairing
3383         if (hci_event_le_meta_get_subevent_code(hci_event) == HCI_SUBEVENT_LE_CONNECTION_COMPLETE){
3384             conn = gap_get_outgoing_le_connection();
3385             // if outgoing connection object is available, check if identity address was used.
3386             // if yes, track resolved random address and provide rpa
3387             // note: we don't update hci le subevent connection complete
3388             if (conn != NULL){
3389                 if (hci_is_le_identity_address_type(conn->address_type)){
3390                     memcpy(&gap_event[20], &gap_event[8], 6);
3391                     gap_event[7] = conn->address_type;
3392                     reverse_bd_addr(conn->address, &gap_event[8]);
3393                 }
3394             }
3395         }
3396 
3397         // we're done with it
3398         hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
3399         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3400 #endif
3401 	} else {
3402 #ifdef ENABLE_LE_PERIPHERAL
3403 		// if we're slave, it was an incoming connection, advertisements have stopped
3404         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
3405 #endif
3406 	}
3407 
3408 	// LE connections are auto-accepted, so just create a connection if there isn't one already
3409 	if (!conn){
3410 		conn = create_connection_for_bd_addr_and_type(addr, addr_type, role);
3411 	}
3412 
3413 	// no memory, sorry.
3414 	if (!conn){
3415 		return;
3416 	}
3417 
3418 	conn->state = OPEN;
3419 	conn->con_handle             = gap_subevent_le_connection_complete_get_connection_handle(gap_event);
3420     conn->le_connection_interval = conn_interval;
3421 
3422     // workaround: PAST doesn't work without LE Read Remote Features on PacketCraft Controller with LMP 568B
3423     conn->gap_connection_tasks = GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
3424 
3425 #ifdef ENABLE_LE_PERIPHERAL
3426 	if (role == HCI_ROLE_SLAVE){
3427 		hci_update_advertisements_enabled_for_current_roles();
3428 	}
3429 #endif
3430 
3431     // init unenhanced att bearer mtu
3432     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3433     conn->att_connection.mtu_exchanged = false;
3434 
3435     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
3436 
3437 	// restart timer
3438 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3439 	// btstack_run_loop_add_timer(&conn->timeout);
3440 
3441 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3442 
3443     // emit GAP_SUBEVENT_LE_CONNECTION_COMPLETE
3444     hci_emit_event(gap_event, sizeof(gap_event), 1);
3445 
3446     // emit BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3447 	hci_emit_nr_connections_changed();
3448 }
3449 #endif
3450 
3451 #ifdef ENABLE_CLASSIC
3452 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){
3453     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
3454     // LEVEL_4 is tested by l2cap
3455     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
3456     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
3457     if (level >= LEVEL_3){
3458         // MITM not possible without keyboard or display
3459         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3460         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3461 
3462         // MITM possible if one side has keyboard and the other has keyboard or display
3463         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3464         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3465 
3466         // MITM not possible if one side has only display and other side has no keyboard
3467         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3468         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3469     }
3470     // LEVEL 2 requires SSP, which is a given
3471     return true;
3472 }
3473 
3474 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
3475     // get requested security level
3476     gap_security_level_t requested_security_level = conn->requested_security_level;
3477     if (hci_stack->gap_secure_connections_only_mode){
3478         requested_security_level = LEVEL_4;
3479     }
3480 
3481     // assess security: LEVEL 4 requires SC
3482     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
3483     if ((requested_security_level == LEVEL_4) &&
3484         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
3485         !hci_remote_sc_enabled(conn)){
3486         log_info("Level 4 required, but SC not supported -> abort");
3487         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3488         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3489         return;
3490     }
3491 
3492     // assess bonding requirements: abort if remote in dedicated bonding mode but we are non-bonding
3493     // - GAP/MOD/NBON/BV-02-C
3494     // - GAP/DM/NBON/BV-01-C
3495     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3496         switch (conn->io_cap_response_auth_req){
3497             case SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING:
3498             case SSP_IO_AUTHREQ_MITM_PROTECTION_REQUIRED_DEDICATED_BONDING:
3499                 if (hci_stack->bondable == false){
3500                     log_info("Dedicated vs. non-bondable -> abort");
3501                     hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3502                     connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3503                     return;
3504                 }
3505             default:
3506                 break;
3507         }
3508     }
3509 
3510     // assess security based on io capabilities
3511     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3512         // responder: fully validate io caps of both sides as well as OOB data
3513         bool security_possible = false;
3514         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3515 
3516 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3517         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3518         // so we merge the OOB data availability
3519         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3520         if (conn->classic_oob_c_192 != NULL){
3521             have_oob_data |= 1;
3522         }
3523         if (conn->classic_oob_c_256 != NULL){
3524             have_oob_data |= 2;
3525         }
3526         // for up to Level 3, either P-192 as well as P-256 will do
3527         // 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
3528         // if remote does not SC, we should not receive P-256 data either
3529         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3530             security_possible = true;
3531         }
3532         // for Level 4, P-256 is needed
3533         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3534             security_possible = true;
3535         }
3536 #endif
3537 
3538         if (security_possible == false){
3539             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3540             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3541             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3542             return;
3543         }
3544     } else {
3545         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
3546 #ifndef ENABLE_CLASSIC_PAIRING_OOB
3547 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3548         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3549             log_info("Level 3+ required, but no input/output -> abort");
3550             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3551             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3552             return;
3553         }
3554 #endif
3555 #endif
3556     }
3557 
3558 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3559     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3560         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3561     } else {
3562         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3563     }
3564 #endif
3565 }
3566 
3567 #endif
3568 
3569 static void event_handler(uint8_t *packet, uint16_t size){
3570 
3571     uint16_t event_length = packet[1];
3572 
3573     // assert packet is complete
3574     if (size != (event_length + 2u)){
3575         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
3576         return;
3577     }
3578 
3579     hci_con_handle_t handle;
3580     hci_connection_t * conn;
3581     int i;
3582 
3583 #ifdef ENABLE_CLASSIC
3584     hci_link_type_t link_type;
3585     bd_addr_t addr;
3586     bd_addr_type_t addr_type;
3587 #endif
3588 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3589     hci_iso_stream_t * iso_stream;
3590     le_audio_big_t   * big;
3591     le_audio_big_sync_t * big_sync;
3592 #endif
3593 #if defined(ENABLE_LE_ISOCHRONOUS_STREAMS) || defined(ENABLE_LE_EXTENDED_ADVERTISING)
3594     btstack_linked_list_iterator_t it;
3595 #endif
3596 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3597     uint8_t advertising_handle;
3598 #endif
3599 
3600     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
3601 
3602     switch (hci_event_packet_get_type(packet)) {
3603 
3604         case HCI_EVENT_COMMAND_COMPLETE:
3605             handle_command_complete_event(packet, size);
3606             break;
3607 
3608         case HCI_EVENT_COMMAND_STATUS:
3609             handle_command_status_event(packet, size);
3610             break;
3611 
3612         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
3613             if (size < 3) return;
3614             uint16_t num_handles = packet[2];
3615             if (size != (3u + num_handles * 4u)) return;
3616 #ifdef ENABLE_CLASSIC
3617             bool notify_sco = false;
3618 #endif
3619 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3620             bool notify_iso = false;
3621 #endif
3622             uint16_t offset = 3;
3623             for (i=0; i<num_handles;i++){
3624                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
3625                 offset += 2u;
3626                 uint16_t num_packets = little_endian_read_16(packet, offset);
3627                 offset += 2u;
3628 
3629                 conn = hci_connection_for_handle(handle);
3630                 if (conn != NULL) {
3631 
3632                     if (conn->num_packets_sent >= num_packets) {
3633                         conn->num_packets_sent -= num_packets;
3634                     } else {
3635                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3636                         conn->num_packets_sent = 0;
3637                     }
3638                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3639 #ifdef ENABLE_CLASSIC
3640                     if (conn->address_type == BD_ADDR_TYPE_SCO){
3641                         notify_sco = true;
3642                     }
3643 #endif
3644                 }
3645 
3646 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
3647                 hci_controller_dump_packets();
3648 #endif
3649 
3650 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3651                 if (conn == NULL){
3652                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle);
3653                     if (iso_stream != NULL){
3654                         if (iso_stream->num_packets_sent >= num_packets) {
3655                             iso_stream->num_packets_sent -= num_packets;
3656                         } else {
3657                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3658                             iso_stream->num_packets_sent = 0;
3659                         }
3660                         if (iso_stream->iso_type == HCI_ISO_TYPE_BIS){
3661                             le_audio_big_t * big = hci_big_for_handle(iso_stream->group_id);
3662                             if (big != NULL){
3663                                 big->num_completed_timestamp_current_valid = true;
3664                                 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms();
3665                             }
3666                         }
3667                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3668                                  num_packets, handle, iso_stream->num_packets_sent);
3669                         notify_iso = true;
3670                     }
3671                 }
3672 #endif
3673             }
3674 
3675 #ifdef ENABLE_CLASSIC
3676             if (notify_sco){
3677                 hci_notify_if_sco_can_send_now();
3678             }
3679 #endif
3680 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3681             if (notify_iso){
3682                 hci_iso_notify_can_send_now();
3683             }
3684 #endif
3685             break;
3686         }
3687 
3688 #ifdef ENABLE_CLASSIC
3689         case HCI_EVENT_FLUSH_OCCURRED:
3690             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
3691             handle = hci_event_flush_occurred_get_handle(packet);
3692             conn = hci_connection_for_handle(handle);
3693             if (conn) {
3694                 log_info("Flush occurred, disconnect 0x%04x", handle);
3695                 conn->state = SEND_DISCONNECT;
3696             }
3697             break;
3698 
3699         case HCI_EVENT_INQUIRY_COMPLETE:
3700             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3701                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3702                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
3703                 hci_emit_event(event, sizeof(event), 1);
3704             }
3705             break;
3706         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3707             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3708                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3709             }
3710             break;
3711         case HCI_EVENT_CONNECTION_REQUEST:
3712             reverse_bd_addr(&packet[2], addr);
3713             link_type = (hci_link_type_t) packet[11];
3714 
3715             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
3716             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
3717                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
3718                 bd_addr_copy(hci_stack->decline_addr, addr);
3719                 break;
3720             }
3721 
3722             if (hci_stack->gap_classic_accept_callback != NULL){
3723                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3724                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
3725                     bd_addr_copy(hci_stack->decline_addr, addr);
3726                     break;
3727                 }
3728             }
3729 
3730             // TODO: eval COD 8-10
3731             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
3732             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
3733             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3734             if (!conn) {
3735                 conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_SLAVE);
3736             }
3737             if (!conn) {
3738                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
3739                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3740                 bd_addr_copy(hci_stack->decline_addr, addr);
3741                 hci_run();
3742                 // avoid event to higher layer
3743                 return;
3744             }
3745             conn->state = RECEIVED_CONNECTION_REQUEST;
3746             // store info about eSCO
3747             if (link_type == HCI_LINK_TYPE_ESCO){
3748                 conn->remote_supported_features[0] |= 1;
3749             }
3750             // propagate remote supported sco packet packets from existing ACL to new SCO connection
3751             if (addr_type == BD_ADDR_TYPE_SCO){
3752                 const hci_connection_t * acl_conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3753                 // ACL exists unless fuzzing
3754                 if (acl_conn != NULL) {
3755                     conn->remote_supported_sco_packets = acl_conn->remote_supported_sco_packets;
3756                 }
3757             }
3758             hci_run();
3759             break;
3760 
3761         case HCI_EVENT_CONNECTION_COMPLETE:
3762             // Connection management
3763             reverse_bd_addr(&packet[5], addr);
3764             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3765             addr_type = BD_ADDR_TYPE_ACL;
3766             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3767             if (conn) {
3768                 switch (conn->state){
3769                     // expected states
3770                     case ACCEPTED_CONNECTION_REQUEST:
3771                     case SENT_CREATE_CONNECTION:
3772                         break;
3773                     // unexpected state -> ignore
3774                     default:
3775                         // don't forward event to app
3776                         return;
3777                 }
3778                 if (!packet[2]){
3779                     conn->state = OPEN;
3780                     conn->con_handle = little_endian_read_16(packet, 3);
3781 
3782                     // trigger write supervision timeout if we're master
3783                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
3784                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
3785                     }
3786 
3787                     // trigger write automatic flush timeout
3788                     if (hci_stack->automatic_flush_timeout != 0){
3789                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
3790                     }
3791 
3792                     // restart timer
3793                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3794                     btstack_run_loop_add_timer(&conn->timeout);
3795 
3796                     // trigger remote features for dedicated bonding
3797                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3798                         hci_trigger_remote_features_for_connection(conn);
3799                     }
3800 
3801                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3802 
3803                     hci_emit_nr_connections_changed();
3804                 } else {
3805                     // connection failed
3806                     hci_handle_connection_failed(conn, packet[2]);
3807                 }
3808             }
3809             break;
3810 
3811         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3812             reverse_bd_addr(&packet[5], addr);
3813             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3814             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3815 
3816             // SCO exists unless fuzzer
3817             if (conn == NULL) break;
3818 
3819             if (packet[2] != ERROR_CODE_SUCCESS){
3820                 // connection failed, remove entry
3821                 hci_handle_connection_failed(conn, packet[2]);
3822                 break;
3823             }
3824 
3825             conn->state = OPEN;
3826             conn->con_handle = little_endian_read_16(packet, 3);
3827 
3828             // update sco payload length for eSCO connections
3829             if (hci_event_synchronous_connection_complete_get_tx_packet_length(packet) > 0){
3830                 conn->sco_payload_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet);
3831                 log_info("eSCO Complete, set payload len %u", conn->sco_payload_length);
3832             }
3833 
3834 #ifdef ENABLE_SCO_OVER_HCI
3835             // update SCO
3836             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3837                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3838             }
3839             // trigger can send now
3840             if (hci_have_usb_transport()){
3841                 hci_stack->sco_can_send_now = true;
3842             }
3843 
3844             // setup implict sco flow control
3845             conn->sco_tx_ready = 0;
3846             conn->sco_tx_active  = 0;
3847             conn->sco_established_ms = btstack_run_loop_get_time_ms();
3848 
3849 #endif
3850 #ifdef HAVE_SCO_TRANSPORT
3851             // configure sco transport
3852             if (hci_stack->sco_transport != NULL){
3853                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3854                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3855             }
3856 #endif
3857             break;
3858 
3859         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3860             handle = little_endian_read_16(packet, 3);
3861             conn = hci_connection_for_handle(handle);
3862             if (!conn) break;
3863             if (!packet[2]){
3864                 const uint8_t * features = &packet[5];
3865                 hci_handle_remote_features_page_0(conn, features);
3866 
3867                 // read extended features if possible
3868                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
3869                 && ((conn->remote_supported_features[0] & 2) != 0)) {
3870                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
3871                     break;
3872                 }
3873             }
3874             hci_handle_remote_features_received(conn);
3875             break;
3876 
3877         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3878             handle = little_endian_read_16(packet, 3);
3879             conn = hci_connection_for_handle(handle);
3880             if (!conn) break;
3881             // status = ok, page = 1
3882             if (!packet[2]) {
3883                 uint8_t page_number = packet[5];
3884                 uint8_t maximum_page_number = packet[6];
3885                 const uint8_t * features = &packet[7];
3886                 bool done = false;
3887                 switch (page_number){
3888                     case 1:
3889                         hci_handle_remote_features_page_1(conn, features);
3890                         if (maximum_page_number >= 2){
3891                             // get Secure Connections (Controller) from Page 2 if available
3892                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
3893                         } else {
3894                             // otherwise, assume SC (Controller) == SC (Host)
3895                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
3896                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
3897                             }
3898                             done = true;
3899                         }
3900                         break;
3901                     case 2:
3902                         hci_handle_remote_features_page_2(conn, features);
3903                         done = true;
3904                         break;
3905                     default:
3906                         break;
3907                 }
3908                 if (!done) break;
3909             }
3910             hci_handle_remote_features_received(conn);
3911             break;
3912 
3913         case HCI_EVENT_LINK_KEY_REQUEST:
3914 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
3915             hci_event_link_key_request_get_bd_addr(packet, addr);
3916             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3917             if (!conn) break;
3918 
3919             // lookup link key in db if not cached
3920             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
3921                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
3922             }
3923 
3924             // response sent by hci_run()
3925             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
3926 #endif
3927             break;
3928 
3929         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
3930             hci_event_link_key_request_get_bd_addr(packet, addr);
3931             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3932             if (!conn) break;
3933 
3934             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
3935 
3936             // CVE-2020-26555: ignore NULL link key
3937             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
3938             if (btstack_is_null(&packet[8], 16)) break;
3939 
3940             link_key_type_t link_key_type = (link_key_type_t)packet[24];
3941             // Change Connection Encryption keeps link key type
3942             if (link_key_type != CHANGED_COMBINATION_KEY){
3943                 conn->link_key_type = link_key_type;
3944             }
3945 
3946             // cache link key. link keys stored in little-endian format for legacy reasons
3947             memcpy(&conn->link_key, &packet[8], 16);
3948 
3949             // only store link key:
3950             // - if bondable enabled
3951             if (hci_stack->bondable == false) break;
3952             // - if security level sufficient
3953             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
3954             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
3955             break;
3956         }
3957 
3958         case HCI_EVENT_PIN_CODE_REQUEST:
3959             hci_event_pin_code_request_get_bd_addr(packet, addr);
3960             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3961             if (!conn) break;
3962 
3963             hci_pairing_started(conn, false);
3964             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
3965             if (!hci_stack->bondable ){
3966                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3967                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3968                 hci_run();
3969                 return;
3970             }
3971             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3972             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3973                 log_info("Level 4 required, but SC not supported -> abort");
3974                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3975                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3976                 hci_run();
3977                 return;
3978             }
3979             break;
3980 
3981         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
3982             hci_event_io_capability_response_get_bd_addr(packet, addr);
3983             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3984             if (!conn) break;
3985 
3986             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
3987             hci_pairing_started(conn, true);
3988             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3989             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3990 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3991             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3992 #endif
3993             break;
3994 
3995         case HCI_EVENT_IO_CAPABILITY_REQUEST:
3996             hci_event_io_capability_response_get_bd_addr(packet, addr);
3997             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3998             if (!conn) break;
3999 
4000             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
4001             hci_connection_timestamp(conn);
4002             hci_pairing_started(conn, true);
4003             break;
4004 
4005 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4006         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
4007             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
4008             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4009             if (!conn) break;
4010 
4011             hci_connection_timestamp(conn);
4012 
4013             hci_pairing_started(conn, true);
4014 
4015             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
4016             break;
4017 #endif
4018 
4019         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
4020             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
4021             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4022             if (!conn) break;
4023             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
4024                 if (hci_stack->ssp_auto_accept){
4025                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4026                 };
4027             } else {
4028                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
4029                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4030                 // don't forward event to app
4031                 hci_run();
4032                 return;
4033             }
4034             break;
4035 
4036         case HCI_EVENT_USER_PASSKEY_REQUEST:
4037             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
4038             if (hci_stack->ssp_auto_accept){
4039                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4040             };
4041             break;
4042 
4043         case HCI_EVENT_MODE_CHANGE:
4044             handle = hci_event_mode_change_get_handle(packet);
4045             conn = hci_connection_for_handle(handle);
4046             if (!conn) break;
4047             conn->connection_mode = hci_event_mode_change_get_mode(packet);
4048             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
4049             break;
4050 #endif
4051 
4052         case HCI_EVENT_ENCRYPTION_CHANGE:
4053         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
4054             handle = hci_event_encryption_change_get_connection_handle(packet);
4055             conn = hci_connection_for_handle(handle);
4056             if (!conn) break;
4057             if (hci_event_encryption_change_get_status(packet) == ERROR_CODE_SUCCESS) {
4058                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
4059                 if (encryption_enabled){
4060                     if (hci_is_le_connection(conn)){
4061                         // For LE, we accept connection as encrypted
4062                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
4063                     }
4064 #ifdef ENABLE_CLASSIC
4065                     else {
4066 
4067                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
4068                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
4069                         bool connected_uses_aes_ccm = encryption_enabled == 2;
4070                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
4071 #ifdef ENABLE_TESTING_SUPPORT
4072                             // The following tests require to reject L2CAP connection as SC has been disabled on the remote
4073                             // - GAP/SEC/SEM/BI-31-C
4074                             // - GAP/SEC/SEM/BI-32-C
4075                             // - GAP/SEC/SEM/BI-33-C
4076 
4077                             // Our release code (aggressively) disconnects the HCI connection, without a chance to respond to PTS
4078                             // To pass the tests, we only downgrade the link key type instead of the more secure disconnect
4079                             link_key_type_t new_link_key_type = UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
4080                             if (conn->link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256){
4081                                 new_link_key_type = AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
4082                             }
4083                             log_info("SC during pairing, but only E0 now -> downgrade link key type from %u to %u",
4084                                      conn->link_key_type, new_link_key_type);
4085                             conn->link_key_type = new_link_key_type;
4086 #else
4087                             log_info("SC during pairing, but only E0 now -> abort");
4088                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
4089                             break;
4090 #endif
4091                         }
4092 
4093 #ifdef ENABLE_MUTUAL_AUTHENTICATION_FOR_LEGACY_SECURE_CONNECTIONS
4094                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
4095                         if (connected_uses_aes_ccm){
4096                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4097                         }
4098 #else
4099                         // We consider even Legacy Secure Connections as authenticated as BTstack mandates encryption
4100                         // with encryption key size > hci_stack->gap_required_encyrption_key_size
4101                         // for all operations that require any security. See BIAS attacks.
4102                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4103 #endif
4104                         // validate encryption key size
4105                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
4106                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
4107                             // already got encryption key size
4108                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
4109                         } else {
4110                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
4111                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
4112                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4113                             } else {
4114                                 // if not, pretend everything is perfect
4115                                 hci_handle_read_encryption_key_size_complete(conn, 16);
4116                             }
4117                         }
4118                     }
4119 #endif
4120                 } else {
4121                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
4122                 }
4123             } else {
4124 #ifdef ENABLE_CLASSIC
4125                 if (!hci_is_le_connection(conn)){
4126                     uint8_t status = hci_event_encryption_change_get_status(packet);
4127                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
4128                         conn->bonding_flags &= ~BONDING_DEDICATED;
4129                         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
4130                         conn->bonding_status = status;
4131                     }
4132                     // trigger security update -> level 0
4133                     hci_handle_mutual_authentication_completed(conn);
4134                 }
4135 #endif
4136             }
4137 
4138             break;
4139 
4140 #ifdef ENABLE_CLASSIC
4141         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
4142             handle = hci_event_authentication_complete_get_connection_handle(packet);
4143             conn = hci_connection_for_handle(handle);
4144             if (!conn) break;
4145 
4146             // clear authentication active flag
4147             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
4148             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
4149 
4150             // authenticated only if auth status == 0
4151             if (hci_event_authentication_complete_get_status(packet) == 0){
4152                 // authenticated
4153                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4154 
4155                 // If not already encrypted, start encryption
4156                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
4157                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4158                     break;
4159                 }
4160             }
4161 
4162             // emit updated security level (will be 0 if not authenticated)
4163             hci_handle_mutual_authentication_completed(conn);
4164             break;
4165 
4166         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
4167             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
4168             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4169             if (!conn) break;
4170 
4171             // treat successfully paired connection as authenticated
4172             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
4173                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4174             }
4175 
4176             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
4177             break;
4178 #endif
4179 
4180         // HCI_EVENT_DISCONNECTION_COMPLETE
4181         // has been split, to first notify stack before shutting connection down
4182         // see end of function, too.
4183         case HCI_EVENT_DISCONNECTION_COMPLETE:
4184             if (packet[2]) break;   // status != 0
4185             handle = little_endian_read_16(packet, 3);
4186             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
4187             if (hci_stack->acl_fragmentation_total_size > 0u) {
4188                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4189                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
4190                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
4191                     hci_stack->acl_fragmentation_total_size = 0;
4192                     hci_stack->acl_fragmentation_pos = 0;
4193                     if (release_buffer){
4194                         hci_release_packet_buffer();
4195                     }
4196                 }
4197             }
4198 
4199 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4200             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
4201             if (hci_stack->iso_fragmentation_total_size > 0u) {
4202                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4203                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
4204                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
4205                     hci_stack->iso_fragmentation_total_size = 0;
4206                     hci_stack->iso_fragmentation_pos = 0;
4207                     if (release_buffer){
4208                         hci_release_packet_buffer();
4209                     }
4210                 }
4211             }
4212 
4213             // finalize iso stream for CIS handle
4214             iso_stream = hci_iso_stream_for_con_handle(handle);
4215             if (iso_stream != NULL){
4216                 hci_iso_stream_finalize(iso_stream);
4217                 break;
4218             }
4219 
4220             // finalize iso stream(s) for ACL handle
4221             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4222             while (btstack_linked_list_iterator_has_next(&it)){
4223                 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4224                 if (iso_stream->acl_handle == handle ) {
4225                     hci_iso_stream_finalize(iso_stream);
4226                 }
4227             }
4228 #endif
4229 
4230 #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
4231             if ((handle != HCI_CON_HANDLE_INVALID) && (handle == hci_stack->hci_command_con_handle)){
4232                 // we did not receive a HCI Command Complete or HCI Command Status event for the disconnected connection
4233                 // if needed, we could also track the hci command opcode and simulate a hci command complete with status
4234                 // but the connection has failed anyway, so for now, we only set the num hci commands back to 1
4235                 log_info("Disconnect for conn handle 0x%04x in pending HCI command, assume command failed", handle);
4236                 hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4237                 hci_stack->num_cmd_packets = 1;
4238             }
4239 #endif
4240 
4241             conn = hci_connection_for_handle(handle);
4242             if (!conn) break;
4243 #ifdef ENABLE_CLASSIC
4244             // pairing failed if it was ongoing
4245             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4246 #endif
4247 
4248             // emit dedicatd bonding event
4249             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
4250                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
4251             }
4252 
4253             // mark connection for shutdown, stop timers, reset state
4254             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
4255             hci_connection_stop_timer(conn);
4256             hci_connection_init(conn);
4257 
4258 #ifdef ENABLE_BLE
4259 #ifdef ENABLE_LE_PERIPHERAL
4260             // re-enable advertisements for le connections if active
4261             if (hci_is_le_connection(conn)){
4262                 hci_update_advertisements_enabled_for_current_roles();
4263             }
4264 #endif
4265 #endif
4266             break;
4267 
4268         case HCI_EVENT_HARDWARE_ERROR:
4269             log_error("Hardware Error: 0x%02x", packet[2]);
4270             if (hci_stack->hardware_error_callback){
4271                 (*hci_stack->hardware_error_callback)(packet[2]);
4272             } else {
4273                 // if no special requests, just reboot stack
4274                 hci_power_control_off();
4275                 hci_power_control_on();
4276             }
4277             break;
4278 
4279 #ifdef ENABLE_CLASSIC
4280         case HCI_EVENT_ROLE_CHANGE:
4281             if (packet[2]) break;   // status != 0
4282             reverse_bd_addr(&packet[3], addr);
4283             addr_type = BD_ADDR_TYPE_ACL;
4284             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4285             if (!conn) break;
4286             conn->role = (hci_role_t) packet[9];
4287             break;
4288 #endif
4289 
4290         case HCI_EVENT_TRANSPORT_PACKET_SENT:
4291             // release packet buffer only for asynchronous transport and if there are not further fragments
4292             if (hci_transport_synchronous()) {
4293                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
4294                 return; // instead of break: to avoid re-entering hci_run()
4295             }
4296             hci_stack->acl_fragmentation_tx_active = 0;
4297 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4298             hci_stack->iso_fragmentation_tx_active = 0;
4299             if (hci_stack->iso_fragmentation_total_size) break;
4300 #endif
4301             if (hci_stack->acl_fragmentation_total_size) break;
4302             hci_release_packet_buffer();
4303 
4304 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4305             hci_iso_notify_can_send_now();
4306 #endif
4307             // L2CAP receives this event via the hci_emit_event below
4308 
4309 #ifdef ENABLE_CLASSIC
4310             // For SCO, we do the can_send_now_check here
4311             hci_notify_if_sco_can_send_now();
4312 #endif
4313             break;
4314 
4315 #ifdef ENABLE_CLASSIC
4316         case HCI_EVENT_SCO_CAN_SEND_NOW:
4317             // For SCO, we do the can_send_now_check here
4318             hci_stack->sco_can_send_now = true;
4319             hci_notify_if_sco_can_send_now();
4320             return;
4321 
4322         // explode inquriy results for easier consumption
4323         case HCI_EVENT_INQUIRY_RESULT:
4324         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4325         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4326             gap_inquiry_explode(packet, size);
4327             break;
4328 #endif
4329 
4330 #ifdef ENABLE_BLE
4331         case HCI_EVENT_LE_META:
4332             switch (packet[2]){
4333 #ifdef ENABLE_LE_CENTRAL
4334                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
4335                     if (!hci_stack->le_scanning_enabled) break;
4336                     le_handle_advertisement_report(packet, size);
4337                     break;
4338 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4339                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
4340                     if (!hci_stack->le_scanning_enabled) break;
4341                     le_handle_extended_advertisement_report(packet, size);
4342                     break;
4343                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
4344                     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
4345                     hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE;
4346                     break;
4347                 case HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED:
4348                     advertising_handle = hci_subevent_le_advertising_set_terminated_get_advertising_handle(packet);
4349                     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4350                     while (btstack_linked_list_iterator_has_next(&it)) {
4351                         le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
4352                         if (advertising_set->advertising_handle == advertising_handle){
4353                             advertising_set->state &= ~(LE_ADVERTISEMENT_STATE_ACTIVE | LE_ADVERTISEMENT_STATE_ENABLED);
4354                         }
4355                     }
4356                     break;
4357 #endif
4358 #endif
4359                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
4360                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
4361                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
4362                     hci_handle_le_connection_complete_event(packet);
4363                     break;
4364 
4365                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
4366                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
4367                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
4368                     conn = hci_connection_for_handle(handle);
4369                     if (!conn) break;
4370                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
4371                     break;
4372 
4373                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
4374                     // connection
4375                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
4376                     conn = hci_connection_for_handle(handle);
4377                     if (conn) {
4378                         // read arguments
4379                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
4380                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
4381                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
4382                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
4383 
4384                         // validate against current connection parameter range
4385                         le_connection_parameter_range_t existing_range;
4386                         gap_get_connection_parameter_range(&existing_range);
4387                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4388                         if (update_parameter){
4389                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
4390                             conn->le_conn_interval_min = le_conn_interval_min;
4391                             conn->le_conn_interval_max = le_conn_interval_max;
4392                             conn->le_conn_latency = le_conn_latency;
4393                             conn->le_supervision_timeout = le_supervision_timeout;
4394                         } else {
4395                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
4396                         }
4397                     }
4398                     break;
4399 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
4400                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
4401                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
4402                     conn = hci_connection_for_handle(handle);
4403                     if (conn) {
4404                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
4405                     }
4406                     break;
4407 #endif
4408 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4409                 case HCI_SUBEVENT_LE_CIS_REQUEST:
4410                     // incoming CIS request, allocate iso stream object and cache metadata
4411                     iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_ISO_STREAM_W4_USER,
4412                                                        hci_subevent_le_cis_request_get_cig_id(packet),
4413                                                        hci_subevent_le_cis_request_get_cis_id(packet));
4414                     // if there's no memory, gap_cis_accept/gap_cis_reject will fail
4415                     if (iso_stream != NULL){
4416                         iso_stream->cis_handle = hci_subevent_le_cis_request_get_cis_connection_handle(packet);
4417                         iso_stream->acl_handle = hci_subevent_le_cis_request_get_acl_connection_handle(packet);
4418                     }
4419                     break;
4420                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
4421                     if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
4422                         handle = hci_subevent_le_cis_established_get_connection_handle(packet);
4423                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
4424                         iso_stream = hci_iso_stream_for_con_handle(handle);
4425                         btstack_assert(iso_stream != NULL);
4426                         // track connection info
4427                         iso_stream->number_of_subevents  = hci_subevent_le_cis_established_get_nse(packet);
4428                         iso_stream->burst_number_c_to_p  = hci_subevent_le_cis_established_get_bn_c_to_p(packet);
4429                         iso_stream->burst_number_p_to_c  = hci_subevent_le_cis_established_get_bn_p_to_c(packet);
4430                         iso_stream->flush_timeout_c_to_p = hci_subevent_le_cis_established_get_ft_c_to_p(packet);
4431                         iso_stream->flush_timeout_p_to_c = hci_subevent_le_cis_established_get_ft_p_to_c(packet);
4432                         iso_stream->max_sdu_c_to_p       = hci_subevent_le_cis_established_get_max_pdu_c_to_p(packet);
4433                         iso_stream->max_sdu_p_to_c       = hci_subevent_le_cis_established_get_max_pdu_p_to_c(packet);
4434                         iso_stream->iso_interval_1250us  = hci_subevent_le_cis_established_get_iso_interval(packet);
4435                         if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
4436                             // CIS Accept by Peripheral
4437                             if (status == ERROR_CODE_SUCCESS){
4438                                 if (iso_stream->max_sdu_p_to_c > 0){
4439                                     // we're peripheral and we will send data
4440                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT;
4441                                 } else {
4442                                     // we're peripheral and we will only receive data
4443                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
4444                                 }
4445                             } else {
4446                                 hci_cis_handle_created(iso_stream, status);
4447                             }
4448                             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4449                         } else {
4450                             // CIG Setup by Central
4451                             le_audio_cig_t * cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
4452                             btstack_assert(cig != NULL);
4453                             // update iso stream state
4454                             if (status == ERROR_CODE_SUCCESS){
4455                                 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4456                             } else {
4457                                 iso_stream->state = HCI_ISO_STREAM_STATE_IDLE;
4458                             }
4459                             // update cig state
4460                             uint8_t i;
4461                             for (i=0;i<cig->num_cis;i++){
4462                                 if (cig->cis_con_handles[i] == handle){
4463                                     cig->cis_setup_active[i] = false;
4464                                     if (status == ERROR_CODE_SUCCESS){
4465                                         cig->cis_established[i] = true;
4466                                     } else {
4467                                         hci_cis_handle_created(iso_stream, status);
4468                                     }
4469                                 }
4470                             }
4471 
4472                             // trigger iso path setup if complete
4473                             bool cis_setup_active = false;
4474                             for (i=0;i<cig->num_cis;i++){
4475                                 cis_setup_active |= cig->cis_setup_active[i];
4476                             }
4477                             if (cis_setup_active == false){
4478                                 cig->state_vars.next_cis = 0;
4479                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
4480                                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4481                             }
4482                         }
4483                     }
4484                     break;
4485                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
4486                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4487                     big = hci_big_for_handle(packet[4]);
4488                     if (big != NULL){
4489                         uint8_t status = packet[3];
4490                         if (status == ERROR_CODE_SUCCESS){
4491                             // store bis_con_handles and trigger iso path setup
4492                             uint8_t num_bis = btstack_min(big->num_bis, packet[20]);
4493                             uint8_t i;
4494                             for (i=0;i<num_bis;i++){
4495                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4496                                 big->bis_con_handles[i] = bis_handle;
4497                                 // assign bis handle
4498                                 btstack_linked_list_iterator_t it;
4499                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4500                                 while (btstack_linked_list_iterator_has_next(&it)){
4501                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4502                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4503                                         (iso_stream->group_id == big->big_handle)){
4504                                         iso_stream->cis_handle = bis_handle;
4505                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4506                                         break;
4507                                     }
4508                                 }
4509                             }
4510                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4511                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4512                                 big->state_vars.next_bis = 0;
4513                             }
4514                         } else {
4515                             // create BIG failed or has been stopped by us
4516                             hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
4517                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4518                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
4519                                 hci_emit_big_created(big, status);
4520                             } else {
4521                                 hci_emit_big_terminated(big);
4522                             }
4523                         }
4524                     }
4525                     break;
4526                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4527                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4528                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
4529                     if (big != NULL){
4530                         // finalize associated ISO streams
4531                         btstack_linked_list_iterator_t it;
4532                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4533                         while (btstack_linked_list_iterator_has_next(&it)){
4534                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4535                             if (iso_stream->group_id == big->big_handle){
4536                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->cis_handle);
4537                                 btstack_linked_list_iterator_remove(&it);
4538                                 btstack_memory_hci_iso_stream_free(iso_stream);
4539                             }
4540                         }
4541                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4542                         switch (big->state){
4543                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
4544                                 hci_emit_big_created(big, big->state_vars.status);
4545                                 break;
4546                             default:
4547                                 hci_emit_big_terminated(big);
4548                                 break;
4549                         }
4550                     }
4551                     break;
4552                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4553                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4554                     big_sync = hci_big_sync_for_handle(packet[4]);
4555                     if (big_sync != NULL){
4556                         uint8_t status = packet[3];
4557                         uint8_t big_handle = packet[4];
4558                         if (status == ERROR_CODE_SUCCESS){
4559                             // store bis_con_handles and trigger iso path setup
4560                             uint8_t num_bis = btstack_min(big_sync->num_bis, packet[16]);
4561                             uint8_t i;
4562                             for (i=0;i<num_bis;i++){
4563                                 hci_con_handle_t bis_handle = little_endian_read_16(packet, 17 + (2 * i));
4564                                 big_sync->bis_con_handles[i] = bis_handle;
4565                                 // setup iso_stream_t
4566                                 btstack_linked_list_iterator_t it;
4567                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4568                                 while (btstack_linked_list_iterator_has_next(&it)){
4569                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4570                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4571                                         (iso_stream->group_id == big_sync->big_handle)){
4572                                         iso_stream->cis_handle = bis_handle;
4573                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4574                                         break;
4575                                     }
4576                                 }
4577                             }
4578                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4579                                 // trigger iso path setup
4580                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4581                                 big_sync->state_vars.next_bis = 0;
4582                             }
4583                         } else {
4584                             // create BIG Sync failed or has been stopped by us
4585                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4586                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4587                                 hci_emit_big_sync_created(big_sync, status);
4588                             } else {
4589                                 hci_emit_big_sync_stopped(big_handle);
4590                             }
4591                         }
4592                     }
4593                     break;
4594                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4595                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4596                     big_sync = hci_big_sync_for_handle(packet[4]);
4597                     if (big_sync != NULL){
4598                         uint8_t big_handle = packet[4];
4599                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4600                         hci_emit_big_sync_stopped(big_handle);
4601                     }
4602                     break;
4603 #endif
4604                 default:
4605                     break;
4606             }
4607             break;
4608 #endif
4609         case HCI_EVENT_VENDOR_SPECIFIC:
4610             // Vendor specific commands often create vendor specific event instead of num completed packets
4611             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
4612             switch (hci_stack->manufacturer){
4613                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
4614                     hci_stack->num_cmd_packets = 1;
4615                     break;
4616                 default:
4617                     break;
4618             }
4619             break;
4620         default:
4621             break;
4622     }
4623 
4624     handle_event_for_current_stack_state(packet, size);
4625 
4626     // notify upper stack
4627 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
4628 
4629     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4630     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4631 		handle = little_endian_read_16(packet, 3);
4632 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4633 		// discard connection if app did not trigger a reconnect in the event handler
4634 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
4635 			hci_shutdown_connection(aConn);
4636 		}
4637 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
4638         hci_controller_dump_packets();
4639 #endif
4640     }
4641 
4642 	// execute main loop
4643 	hci_run();
4644 }
4645 
4646 #ifdef ENABLE_CLASSIC
4647 
4648 static void sco_handler(uint8_t * packet, uint16_t size){
4649     // lookup connection struct
4650     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
4651     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
4652     if (!conn) return;
4653 
4654 #ifdef ENABLE_SCO_OVER_HCI
4655     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4656     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4657         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4658             packet[2] = 0x3c;
4659             memmove(&packet[3], &packet[23], 63);
4660             size = 63;
4661         }
4662     }
4663 
4664     if (hci_have_usb_transport()){
4665         // Nothing to do
4666     } else {
4667         // 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);
4668         if (hci_stack->synchronous_flow_control_enabled == 0){
4669             // ignore received SCO packets for the first 10 ms, then allow for max two HCI_SCO_2EV3_SIZE packets
4670             uint16_t max_sco_packets = btstack_min(2 * HCI_SCO_2EV3_SIZE / conn->sco_payload_length, hci_stack->sco_packets_total_num);
4671             if (conn->sco_tx_active == 0){
4672                 if (btstack_time_delta(btstack_run_loop_get_time_ms(), conn->sco_established_ms) > 10){
4673                     conn->sco_tx_active = 1;
4674                     conn->sco_tx_ready = max_sco_packets;
4675                     log_info("Start SCO sending, %u packets", conn->sco_tx_ready);
4676                     hci_notify_if_sco_can_send_now();
4677                 }
4678             } else {
4679                 if (conn->sco_tx_ready < max_sco_packets){
4680                     conn->sco_tx_ready++;
4681                 }
4682                 hci_notify_if_sco_can_send_now();
4683             }
4684         }
4685     }
4686 #endif
4687 
4688     // deliver to app
4689     if (hci_stack->sco_packet_handler) {
4690         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
4691     }
4692 
4693 #ifdef HAVE_SCO_TRANSPORT
4694     // We can send one packet for each received packet
4695     conn->sco_tx_ready++;
4696     hci_notify_if_sco_can_send_now();
4697 #endif
4698 
4699 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4700     conn->num_packets_completed++;
4701     hci_stack->host_completed_packets = 1;
4702     hci_run();
4703 #endif
4704 }
4705 #endif
4706 
4707 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
4708 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4709     // propagate ISO packets received as ACL
4710     hci_iso_stream_t * iso_stream = NULL;
4711     if ((packet_type == HCI_ACL_DATA_PACKET) && (size >= HCI_ACL_HEADER_SIZE)){
4712         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
4713         iso_stream = hci_iso_stream_for_con_handle(con_handle);
4714         if (iso_stream != NULL){
4715             packet_type = HCI_ISO_DATA_PACKET;
4716         }
4717     }
4718 #endif
4719 
4720     hci_dump_packet(packet_type, 1, packet, size);
4721     switch (packet_type) {
4722         case HCI_EVENT_PACKET:
4723             event_handler(packet, size);
4724             break;
4725         case HCI_ACL_DATA_PACKET:
4726             acl_handler(packet, size);
4727             break;
4728 #ifdef ENABLE_CLASSIC
4729         case HCI_SCO_DATA_PACKET:
4730             sco_handler(packet, size);
4731             break;
4732 #endif
4733 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4734         case HCI_ISO_DATA_PACKET:
4735             if ((iso_stream == NULL) && (size >= HCI_ISO_HEADER_SIZE)){
4736                 hci_con_handle_t con_handle = READ_ISO_CONNECTION_HANDLE(packet);
4737                 iso_stream = hci_iso_stream_for_con_handle(con_handle);
4738             }
4739             hci_iso_packet_handler(iso_stream, packet, size);
4740             break;
4741 #endif
4742         default:
4743             break;
4744     }
4745 }
4746 
4747 /**
4748  * @brief Add event packet handler.
4749  */
4750 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4751     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4752 }
4753 
4754 /**
4755  * @brief Remove event packet handler.
4756  */
4757 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
4758     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4759 }
4760 
4761 /** Register HCI packet handlers */
4762 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4763     hci_stack->acl_packet_handler = handler;
4764 }
4765 
4766 #ifdef ENABLE_CLASSIC
4767 /**
4768  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
4769  */
4770 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
4771     hci_stack->sco_packet_handler = handler;
4772 }
4773 #endif
4774 
4775 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4776 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
4777     hci_stack->iso_packet_handler = handler;
4778 }
4779 #endif
4780 
4781 static void hci_state_reset(void){
4782     // no connections yet
4783     hci_stack->connections = NULL;
4784 
4785     // keep discoverable/connectable as this has been requested by the client(s)
4786     // hci_stack->discoverable = 0;
4787     // hci_stack->connectable = 0;
4788     // hci_stack->bondable = 1;
4789     // hci_stack->own_addr_type = 0;
4790 
4791     // buffer is free
4792     hci_stack->hci_packet_buffer_reserved = false;
4793 
4794     // no pending cmds
4795     hci_stack->decline_reason = 0;
4796 
4797     hci_stack->secure_connections_active = false;
4798 
4799 #ifdef ENABLE_CLASSIC
4800     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
4801     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
4802 
4803     hci_stack->gap_tasks_classic =
4804             GAP_TASK_SET_DEFAULT_LINK_POLICY |
4805             GAP_TASK_SET_CLASS_OF_DEVICE |
4806             GAP_TASK_SET_LOCAL_NAME |
4807             GAP_TASK_SET_EIR_DATA |
4808             GAP_TASK_WRITE_SCAN_ENABLE |
4809             GAP_TASK_WRITE_PAGE_TIMEOUT;
4810 #endif
4811 
4812 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4813     hci_stack->classic_read_local_oob_data = false;
4814     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4815 #endif
4816 
4817     // LE
4818 #ifdef ENABLE_BLE
4819     memset(hci_stack->le_random_address, 0, 6);
4820     hci_stack->le_random_address_set = 0;
4821 #endif
4822 #ifdef ENABLE_LE_CENTRAL
4823     hci_stack->le_scanning_active  = false;
4824     hci_stack->le_scanning_param_update = true;
4825     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4826     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4827     hci_stack->le_whitelist_capacity = 0;
4828 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4829     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
4830 #endif
4831 #endif
4832 #ifdef ENABLE_LE_PERIPHERAL
4833     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4834     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4835         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4836     }
4837     if (hci_stack->le_advertisements_data != NULL){
4838         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4839     }
4840 #endif
4841 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4842     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION;
4843 #endif
4844 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4845     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4846     hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID;
4847 #endif
4848 #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
4849     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4850 #endif
4851 }
4852 
4853 #ifdef ENABLE_CLASSIC
4854 /**
4855  * @brief Configure Bluetooth hardware control. Has to be called before power on.
4856  */
4857 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
4858     // store and open remote device db
4859     hci_stack->link_key_db = link_key_db;
4860     if (hci_stack->link_key_db) {
4861         hci_stack->link_key_db->open();
4862     }
4863 }
4864 #endif
4865 
4866 void hci_init(const hci_transport_t *transport, const void *config){
4867 
4868 #ifdef HAVE_MALLOC
4869     if (!hci_stack) {
4870         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
4871     }
4872 #else
4873     hci_stack = &hci_stack_static;
4874 #endif
4875     memset(hci_stack, 0, sizeof(hci_stack_t));
4876 
4877     // reference to use transport layer implementation
4878     hci_stack->hci_transport = transport;
4879 
4880     // reference to used config
4881     hci_stack->config = config;
4882 
4883     // setup pointer for outgoing packet buffer
4884     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
4885 
4886     // max acl payload size defined in config.h
4887     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4888 
4889     // register packet handlers with transport
4890     transport->register_packet_handler(&packet_handler);
4891 
4892     hci_stack->state = HCI_STATE_OFF;
4893 
4894     // class of device
4895     hci_stack->class_of_device = 0x007a020c; // Smartphone
4896 
4897     // bondable by default
4898     hci_stack->bondable = 1;
4899 
4900 #ifdef ENABLE_CLASSIC
4901     // classic name
4902     hci_stack->local_name = default_classic_name;
4903 
4904     // Master slave policy
4905     hci_stack->master_slave_policy = 1;
4906 
4907     // Allow Role Switch
4908     hci_stack->allow_role_switch = 1;
4909 
4910     // Default / minimum security level = 2
4911     hci_stack->gap_security_level = LEVEL_2;
4912 
4913     // Default Security Mode 4
4914     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
4915 
4916     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4917     hci_stack->gap_required_encyrption_key_size = 7;
4918 
4919     // Link Supervision Timeout
4920     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4921 
4922     // All ACL packet types are enabledh
4923     hci_stack->enabled_packet_types_acl = ACL_PACKET_TYPES_ALL;
4924 #endif
4925 
4926     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
4927     hci_stack->ssp_enable = 1;
4928     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
4929     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4930     hci_stack->ssp_auto_accept = 1;
4931 
4932     // Secure Connections: enable (requires support from Controller)
4933     hci_stack->secure_connections_enable = true;
4934 
4935     // voice setting - signed 16 bit pcm data with CVSD over the air
4936     hci_stack->sco_voice_setting = 0x60;
4937 
4938 #ifdef ENABLE_BLE
4939     hci_stack->le_connection_scan_interval = 0x0060;   //    60 ms
4940     hci_stack->le_connection_scan_window   = 0x0030;    //   30 ms
4941     hci_stack->le_connection_interval_min  = 0x0008;    //   10 ms
4942     hci_stack->le_connection_interval_max  = 0x0018;    //   30 ms
4943     hci_stack->le_connection_latency       =      4;    //    4
4944     hci_stack->le_supervision_timeout      = 0x0048;    //  720 ms
4945     hci_stack->le_minimum_ce_length        =      0;    //    0 ms
4946     hci_stack->le_maximum_ce_length        =      0;    //    0 ms
4947 #endif
4948 
4949 #ifdef ENABLE_LE_CENTRAL
4950     hci_stack->le_connection_phys          =   0x01;    // LE 1M PHY
4951 
4952     // default LE Scanning
4953     hci_stack->le_scan_type     =  0x01; // active
4954     hci_stack->le_scan_interval = 0x1e0; // 300 ms
4955     hci_stack->le_scan_window   =  0x30; //  30 ms
4956     hci_stack->le_scan_phys     =  0x01; // LE 1M PHY
4957 #endif
4958 
4959 #ifdef ENABLE_LE_PERIPHERAL
4960     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4961 
4962     // default advertising parameters from Core v5.4 -- needed to use random address without prior adv setup
4963     hci_stack->le_advertisements_interval_min =                         0x0800;
4964     hci_stack->le_advertisements_interval_max =                         0x0800;
4965     hci_stack->le_advertisements_type =                                      0;
4966     hci_stack->le_own_addr_type =                       BD_ADDR_TYPE_LE_PUBLIC;
4967     hci_stack->le_advertisements_direct_address_type =  BD_ADDR_TYPE_LE_PUBLIC;
4968     hci_stack->le_advertisements_channel_map =                            0x07;
4969     hci_stack->le_advertisements_filter_policy =                             0;
4970 #endif
4971 
4972     // connection parameter range used to answer connection parameter update requests in l2cap
4973     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4974     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4975     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4976     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4977     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4978     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4979 
4980 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4981     hci_stack->iso_packets_to_queue = 1;
4982 #endif
4983 
4984 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4985     hci_stack->le_privacy_mode = LE_PRIVACY_MODE_DEVICE;
4986 #endif
4987 
4988     hci_state_reset();
4989 }
4990 
4991 void hci_deinit(void){
4992     btstack_run_loop_remove_timer(&hci_stack->timeout);
4993 #ifdef HAVE_MALLOC
4994     if (hci_stack) {
4995         free(hci_stack);
4996     }
4997 #endif
4998     hci_stack = NULL;
4999 
5000 #ifdef ENABLE_CLASSIC
5001     disable_l2cap_timeouts = 0;
5002 #endif
5003 }
5004 
5005 /**
5006  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
5007  */
5008 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
5009     hci_stack->chipset = chipset_driver;
5010 
5011     // reset chipset driver - init is also called on power_up
5012     if (hci_stack->chipset && hci_stack->chipset->init){
5013         hci_stack->chipset->init(hci_stack->config);
5014     }
5015 }
5016 
5017 void hci_enable_custom_pre_init(void){
5018     hci_stack->chipset_pre_init = true;
5019 }
5020 
5021 /**
5022  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
5023  */
5024 void hci_set_control(const btstack_control_t *hardware_control){
5025     // references to used control implementation
5026     hci_stack->control = hardware_control;
5027     // init with transport config
5028     hardware_control->init(hci_stack->config);
5029 }
5030 
5031 static void hci_discard_connections(void){
5032     btstack_linked_list_iterator_t it;
5033     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5034     while (btstack_linked_list_iterator_has_next(&it)){
5035         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
5036         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
5037         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
5038         hci_shutdown_connection(connection);
5039     }
5040 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5041     while (hci_stack->iso_streams != NULL){
5042         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
5043     }
5044 #endif
5045 }
5046 
5047 void hci_close(void){
5048 
5049 #ifdef ENABLE_CLASSIC
5050     // close remote device db
5051     if (hci_stack->link_key_db) {
5052         hci_stack->link_key_db->close();
5053     }
5054 #endif
5055 
5056     hci_discard_connections();
5057 
5058     hci_power_control(HCI_POWER_OFF);
5059 
5060 #ifdef HAVE_MALLOC
5061     free(hci_stack);
5062 #endif
5063     hci_stack = NULL;
5064 }
5065 
5066 #ifdef HAVE_SCO_TRANSPORT
5067 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
5068     hci_stack->sco_transport = sco_transport;
5069     sco_transport->register_packet_handler(&packet_handler);
5070 }
5071 #endif
5072 
5073 #ifdef ENABLE_CLASSIC
5074 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
5075     // validate ranage and set
5076     if (encryption_key_size < 7)  return;
5077     if (encryption_key_size > 16) return;
5078     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
5079 }
5080 
5081 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
5082     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
5083         hci_stack->gap_security_mode = security_mode;
5084         return ERROR_CODE_SUCCESS;
5085     } else {
5086         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
5087     }
5088 }
5089 
5090 gap_security_mode_t gap_get_security_mode(void){
5091     return hci_stack->gap_security_mode;
5092 }
5093 
5094 void gap_set_security_level(gap_security_level_t security_level){
5095     hci_stack->gap_security_level = security_level;
5096 }
5097 
5098 gap_security_level_t gap_get_security_level(void){
5099     if (hci_stack->gap_secure_connections_only_mode){
5100         return LEVEL_4;
5101     }
5102     return hci_stack->gap_security_level;
5103 }
5104 
5105 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
5106     hci_stack->gap_minimal_service_security_level = security_level;
5107 }
5108 
5109 void gap_set_secure_connections_only_mode(bool enable){
5110     hci_stack->gap_secure_connections_only_mode = enable;
5111 }
5112 
5113 bool gap_get_secure_connections_only_mode(void){
5114     return hci_stack->gap_secure_connections_only_mode;
5115 }
5116 #endif
5117 
5118 #ifdef ENABLE_CLASSIC
5119 void gap_set_class_of_device(uint32_t class_of_device){
5120     hci_stack->class_of_device = class_of_device;
5121     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
5122     hci_run();
5123 }
5124 
5125 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
5126     hci_stack->default_link_policy_settings = default_link_policy_settings;
5127     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
5128     hci_run();
5129 }
5130 
5131 void gap_set_allow_role_switch(bool allow_role_switch){
5132     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
5133 }
5134 
5135 uint8_t hci_get_allow_role_switch(void){
5136     return  hci_stack->allow_role_switch;
5137 }
5138 
5139 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
5140     hci_stack->link_supervision_timeout = link_supervision_timeout;
5141 }
5142 
5143 void gap_enable_link_watchdog(uint16_t timeout_ms){
5144     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
5145 }
5146 
5147 uint16_t hci_automatic_flush_timeout(void){
5148     return hci_stack->automatic_flush_timeout;
5149 }
5150 
5151 void hci_disable_l2cap_timeout_check(void){
5152     disable_l2cap_timeouts = 1;
5153 }
5154 #endif
5155 
5156 #ifndef HAVE_HOST_CONTROLLER_API
5157 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
5158 void hci_set_bd_addr(bd_addr_t addr){
5159     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
5160     hci_stack->custom_bd_addr_set = 1;
5161 }
5162 #endif
5163 
5164 // State-Module-Driver overview
5165 // state                    module  low-level
5166 // HCI_STATE_OFF             off      close
5167 // HCI_STATE_INITIALIZING,   on       open
5168 // HCI_STATE_WORKING,        on       open
5169 // HCI_STATE_HALTING,        on       open
5170 // HCI_STATE_SLEEPING,    off/sleep   close
5171 // HCI_STATE_FALLING_ASLEEP  on       open
5172 
5173 static int hci_power_control_on(void){
5174 
5175     // power on
5176     int err = 0;
5177     if (hci_stack->control && hci_stack->control->on){
5178         err = (*hci_stack->control->on)();
5179     }
5180     if (err){
5181         log_error( "POWER_ON failed");
5182         hci_emit_hci_open_failed();
5183         return err;
5184     }
5185 
5186     // int chipset driver
5187     if (hci_stack->chipset && hci_stack->chipset->init){
5188         hci_stack->chipset->init(hci_stack->config);
5189     }
5190 
5191     // init transport
5192     if (hci_stack->hci_transport->init){
5193         hci_stack->hci_transport->init(hci_stack->config);
5194     }
5195 
5196     // open transport
5197     err = hci_stack->hci_transport->open();
5198     if (err){
5199         log_error( "HCI_INIT failed, turning Bluetooth off again");
5200         if (hci_stack->control && hci_stack->control->off){
5201             (*hci_stack->control->off)();
5202         }
5203         hci_emit_hci_open_failed();
5204         return err;
5205     }
5206     return 0;
5207 }
5208 
5209 static void hci_power_control_off(void){
5210 
5211     log_info("hci_power_control_off");
5212 
5213     // close low-level device
5214     hci_stack->hci_transport->close();
5215 
5216     log_info("hci_power_control_off - hci_transport closed");
5217 
5218     // power off
5219     if (hci_stack->control && hci_stack->control->off){
5220         (*hci_stack->control->off)();
5221     }
5222 
5223     log_info("hci_power_control_off - control closed");
5224 
5225     hci_stack->state = HCI_STATE_OFF;
5226 }
5227 
5228 static void hci_power_control_sleep(void){
5229 
5230     log_info("hci_power_control_sleep");
5231 
5232 #if 0
5233     // don't close serial port during sleep
5234 
5235     // close low-level device
5236     hci_stack->hci_transport->close(hci_stack->config);
5237 #endif
5238 
5239     // sleep mode
5240     if (hci_stack->control && hci_stack->control->sleep){
5241         (*hci_stack->control->sleep)();
5242     }
5243 
5244     hci_stack->state = HCI_STATE_SLEEPING;
5245 }
5246 
5247 static int hci_power_control_wake(void){
5248 
5249     log_info("hci_power_control_wake");
5250 
5251     // wake on
5252     if (hci_stack->control && hci_stack->control->wake){
5253         (*hci_stack->control->wake)();
5254     }
5255 
5256 #if 0
5257     // open low-level device
5258     int err = hci_stack->hci_transport->open(hci_stack->config);
5259     if (err){
5260         log_error( "HCI_INIT failed, turning Bluetooth off again");
5261         if (hci_stack->control && hci_stack->control->off){
5262             (*hci_stack->control->off)();
5263         }
5264         hci_emit_hci_open_failed();
5265         return err;
5266     }
5267 #endif
5268 
5269     return 0;
5270 }
5271 
5272 static void hci_power_enter_initializing_state(void){
5273     // set up state machine
5274     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
5275     hci_stack->hci_packet_buffer_reserved = false;
5276     hci_stack->state = HCI_STATE_INITIALIZING;
5277 
5278 #ifndef HAVE_HOST_CONTROLLER_API
5279     if (hci_stack->chipset_pre_init) {
5280         hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
5281     } else
5282 #endif
5283     {
5284         hci_stack->substate = HCI_INIT_SEND_RESET;
5285     }
5286 }
5287 
5288 static void hci_power_enter_halting_state(void){
5289 #ifdef ENABLE_BLE
5290     // drop entries scheduled for removal, mark others for re-adding
5291     btstack_linked_list_iterator_t it;
5292     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5293     while (btstack_linked_list_iterator_has_next(&it)){
5294         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5295         if ((entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)) == LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5296             btstack_linked_list_iterator_remove(&it);
5297             btstack_memory_whitelist_entry_free(entry);
5298         } else {
5299             entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5300         }
5301     }
5302 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5303     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
5304     const uint8_t mask = LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5305     while (btstack_linked_list_iterator_has_next(&it)){
5306         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
5307         if ((entry->state & mask) == LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER) {
5308             btstack_linked_list_iterator_remove(&it);
5309             btstack_memory_periodic_advertiser_list_entry_free(entry);
5310         } else {
5311             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5312             continue;
5313         }
5314     }
5315 #endif
5316 #endif
5317     // see hci_run
5318     hci_stack->state = HCI_STATE_HALTING;
5319     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
5320     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
5321     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
5322     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5323     btstack_run_loop_add_timer(&hci_stack->timeout);
5324 }
5325 
5326 // returns error
5327 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
5328     int err;
5329     switch (power_mode){
5330         case HCI_POWER_ON:
5331             err = hci_power_control_on();
5332             if (err != 0) {
5333                 log_error("hci_power_control_on() error %d", err);
5334                 return err;
5335             }
5336             hci_power_enter_initializing_state();
5337             break;
5338         case HCI_POWER_OFF:
5339             // do nothing
5340             break;
5341         case HCI_POWER_SLEEP:
5342             // do nothing (with SLEEP == OFF)
5343             break;
5344         default:
5345             btstack_assert(false);
5346             break;
5347     }
5348     return ERROR_CODE_SUCCESS;
5349 }
5350 
5351 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
5352     switch (power_mode){
5353         case HCI_POWER_ON:
5354             // do nothing
5355             break;
5356         case HCI_POWER_OFF:
5357             // no connections yet, just turn it off
5358             hci_power_control_off();
5359             break;
5360         case HCI_POWER_SLEEP:
5361             // no connections yet, just turn it off
5362             hci_power_control_sleep();
5363             break;
5364         default:
5365             btstack_assert(false);
5366             break;
5367     }
5368     return ERROR_CODE_SUCCESS;
5369 }
5370 
5371 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
5372     switch (power_mode){
5373         case HCI_POWER_ON:
5374             // do nothing
5375             break;
5376         case HCI_POWER_OFF:
5377             hci_power_enter_halting_state();
5378             break;
5379         case HCI_POWER_SLEEP:
5380             // see hci_run
5381             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5382             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5383             break;
5384         default:
5385             btstack_assert(false);
5386             break;
5387     }
5388     return ERROR_CODE_SUCCESS;
5389 }
5390 
5391 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
5392     switch (power_mode){
5393         case HCI_POWER_ON:
5394             hci_power_enter_initializing_state();
5395             break;
5396         case HCI_POWER_OFF:
5397             // do nothing
5398             break;
5399         case HCI_POWER_SLEEP:
5400             // see hci_run
5401             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5402             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5403             break;
5404         default:
5405             btstack_assert(false);
5406             break;
5407     }
5408     return ERROR_CODE_SUCCESS;
5409 }
5410 
5411 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
5412     switch (power_mode){
5413         case HCI_POWER_ON:
5414             hci_power_enter_initializing_state();
5415             break;
5416         case HCI_POWER_OFF:
5417             hci_power_enter_halting_state();
5418             break;
5419         case HCI_POWER_SLEEP:
5420             // do nothing
5421             break;
5422         default:
5423             btstack_assert(false);
5424             break;
5425     }
5426     return ERROR_CODE_SUCCESS;
5427 }
5428 
5429 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
5430     int err;
5431     switch (power_mode){
5432         case HCI_POWER_ON:
5433             err = hci_power_control_wake();
5434             if (err) return err;
5435             hci_power_enter_initializing_state();
5436             break;
5437         case HCI_POWER_OFF:
5438             hci_power_enter_halting_state();
5439             break;
5440         case HCI_POWER_SLEEP:
5441             // do nothing
5442             break;
5443         default:
5444             btstack_assert(false);
5445             break;
5446     }
5447     return ERROR_CODE_SUCCESS;
5448 }
5449 
5450 int hci_power_control(HCI_POWER_MODE power_mode){
5451     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
5452     btstack_run_loop_remove_timer(&hci_stack->timeout);
5453     int err = 0;
5454     switch (hci_stack->state){
5455         case HCI_STATE_OFF:
5456             err = hci_power_control_state_off(power_mode);
5457             break;
5458         case HCI_STATE_INITIALIZING:
5459             err = hci_power_control_state_initializing(power_mode);
5460             break;
5461         case HCI_STATE_WORKING:
5462             err = hci_power_control_state_working(power_mode);
5463             break;
5464         case HCI_STATE_HALTING:
5465             err = hci_power_control_state_halting(power_mode);
5466             break;
5467         case HCI_STATE_FALLING_ASLEEP:
5468             err = hci_power_control_state_falling_asleep(power_mode);
5469             break;
5470         case HCI_STATE_SLEEPING:
5471             err = hci_power_control_state_sleeping(power_mode);
5472             break;
5473         default:
5474             btstack_assert(false);
5475             break;
5476     }
5477     if (err != 0){
5478         return err;
5479     }
5480 
5481     // create internal event
5482 	hci_emit_state();
5483 
5484 	// trigger next/first action
5485 	hci_run();
5486 
5487     return 0;
5488 }
5489 
5490 
5491 static void hci_halting_run(void) {
5492 
5493     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5494 
5495     hci_connection_t *connection;
5496 #ifdef ENABLE_BLE
5497 #ifdef ENABLE_LE_PERIPHERAL
5498     bool stop_advertismenets;
5499 #endif
5500 #endif
5501 
5502     switch (hci_stack->substate) {
5503         case HCI_HALTING_CLASSIC_STOP:
5504 #ifdef ENABLE_CLASSIC
5505             if (!hci_can_send_command_packet_now()) return;
5506 
5507             if (hci_stack->connectable || hci_stack->discoverable){
5508                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5509                 hci_send_cmd(&hci_write_scan_enable, 0);
5510                 return;
5511             }
5512 #endif
5513             /* fall through */
5514 
5515         case HCI_HALTING_LE_ADV_STOP:
5516             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5517 
5518 #ifdef ENABLE_BLE
5519 #ifdef ENABLE_LE_PERIPHERAL
5520             if (!hci_can_send_command_packet_now()) return;
5521 
5522             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5523 
5524 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5525             if (hci_le_extended_advertising_supported()){
5526 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5527                 btstack_linked_list_iterator_t it;
5528                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5529                 // stop all periodic advertisements and check if an extended set is active
5530                 while (btstack_linked_list_iterator_has_next(&it)){
5531                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5532                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5533                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5534                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
5535                         return;
5536                     }
5537                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5538                         stop_advertismenets = true;
5539                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5540                     }
5541                 }
5542 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5543                 if (stop_advertismenets){
5544                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5545                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5546                     return;
5547                 }
5548             } else
5549 #else /* ENABLE_LE_PERIPHERAL */
5550             {
5551                 if (stop_advertismenets) {
5552                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5553                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5554                     return;
5555                 }
5556             }
5557 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5558 #endif  /* ENABLE_LE_PERIPHERAL */
5559 #endif  /* ENABLE_BLE */
5560 
5561             /* fall through */
5562 
5563         case HCI_HALTING_LE_SCAN_STOP:
5564             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5565             if (!hci_can_send_command_packet_now()) return;
5566 
5567 #ifdef ENABLE_BLE
5568 #ifdef ENABLE_LE_CENTRAL
5569             if (hci_stack->le_scanning_active){
5570                 hci_le_scan_stop();
5571                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5572                 return;
5573             }
5574 #endif
5575 #endif
5576 
5577             /* fall through */
5578 
5579         case HCI_HALTING_DISCONNECT_ALL:
5580             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5581             if (!hci_can_send_command_packet_now()) return;
5582 
5583             // close all open connections
5584             connection = (hci_connection_t *) hci_stack->connections;
5585             if (connection) {
5586                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5587 
5588                 log_info("HCI_STATE_HALTING, connection %p, handle %u, state %u", connection, con_handle, connection->state);
5589 
5590                 // check state
5591                 switch(connection->state) {
5592                     case SENT_DISCONNECT:
5593                     case RECEIVED_DISCONNECTION_COMPLETE:
5594                         // wait until connection is gone
5595                         return;
5596                     default:
5597                         break;
5598                 }
5599 
5600                 // finally, send the disconnect command
5601                 connection->state = SENT_DISCONNECT;
5602                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5603                 return;
5604             }
5605 
5606 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5607             // stop BIGs and BIG Syncs
5608             if (hci_stack->le_audio_bigs != NULL){
5609                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5610                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5611                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5612                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5613                 return;
5614             }
5615             if (hci_stack->le_audio_big_syncs != NULL){
5616                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5617                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5618                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5619                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5620                 return;
5621             }
5622 #endif
5623 
5624             btstack_run_loop_remove_timer(&hci_stack->timeout);
5625 
5626             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5627             log_info("HCI_STATE_HALTING: wait 50 ms");
5628             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5629             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5630             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5631             btstack_run_loop_add_timer(&hci_stack->timeout);
5632             break;
5633 
5634         case HCI_HALTING_W4_CLOSE_TIMER:
5635             // keep waiting
5636             break;
5637 
5638         case HCI_HALTING_CLOSE:
5639             // close left over connections (that had not been properly closed before)
5640             hci_stack->substate = HCI_HALTING_CLOSE_DISCARDING_CONNECTIONS;
5641             hci_discard_connections();
5642 
5643             log_info("HCI_STATE_HALTING, calling off");
5644 
5645             // switch mode
5646             hci_power_control_off();
5647 
5648             log_info("HCI_STATE_HALTING, emitting state");
5649             hci_emit_state();
5650             log_info("HCI_STATE_HALTING, done");
5651             break;
5652 
5653         default:
5654             break;
5655     }
5656 };
5657 
5658 static void hci_falling_asleep_run(void){
5659     hci_connection_t * connection;
5660     switch(hci_stack->substate) {
5661         case HCI_FALLING_ASLEEP_DISCONNECT:
5662             log_info("HCI_STATE_FALLING_ASLEEP");
5663             // close all open connections
5664             connection =  (hci_connection_t *) hci_stack->connections;
5665             if (connection){
5666 
5667                 // send disconnect
5668                 if (!hci_can_send_command_packet_now()) return;
5669 
5670                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5671                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5672 
5673                 // send disconnected event right away - causes higher layer connections to get closed, too.
5674                 hci_shutdown_connection(connection);
5675                 return;
5676             }
5677 
5678             if (hci_classic_supported()){
5679                 // disable page and inquiry scan
5680                 if (!hci_can_send_command_packet_now()) return;
5681 
5682                 log_info("HCI_STATE_HALTING, disabling inq scans");
5683                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5684 
5685                 // continue in next sub state
5686                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5687                 break;
5688             }
5689 
5690             /* fall through */
5691 
5692             case HCI_FALLING_ASLEEP_COMPLETE:
5693                 log_info("HCI_STATE_HALTING, calling sleep");
5694                 // switch mode
5695                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5696                 hci_emit_state();
5697                 break;
5698 
5699                 default:
5700                     break;
5701     }
5702 }
5703 
5704 #ifdef ENABLE_CLASSIC
5705 
5706 static void hci_update_scan_enable(void){
5707     // 2 = page scan, 1 = inq scan
5708     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5709     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5710     hci_run();
5711 }
5712 
5713 void gap_discoverable_control(uint8_t enable){
5714     if (enable) enable = 1; // normalize argument
5715 
5716     if (hci_stack->discoverable == enable){
5717         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5718         return;
5719     }
5720 
5721     hci_stack->discoverable = enable;
5722     hci_update_scan_enable();
5723 }
5724 
5725 void gap_connectable_control(uint8_t enable){
5726     if (enable) enable = 1; // normalize argument
5727 
5728     // don't emit event
5729     if (hci_stack->connectable == enable) return;
5730 
5731     hci_stack->connectable = enable;
5732     hci_update_scan_enable();
5733 }
5734 #endif
5735 
5736 void gap_local_bd_addr(bd_addr_t address_buffer){
5737     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5738 }
5739 
5740 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5741 static void hci_host_num_completed_packets(void){
5742 
5743     // create packet manually as arrays are not supported and num_commands should not get reduced
5744     hci_reserve_packet_buffer();
5745     uint8_t * packet = hci_get_outgoing_packet_buffer();
5746 
5747     uint16_t size = 0;
5748     uint16_t num_handles = 0;
5749     packet[size++] = 0x35;
5750     packet[size++] = 0x0c;
5751     size++;  // skip param len
5752     size++;  // skip num handles
5753 
5754     // add { handle, packets } entries
5755     btstack_linked_item_t * it;
5756     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5757         hci_connection_t * connection = (hci_connection_t *) it;
5758         if (connection->num_packets_completed){
5759             little_endian_store_16(packet, size, connection->con_handle);
5760             size += 2;
5761             little_endian_store_16(packet, size, connection->num_packets_completed);
5762             size += 2;
5763             //
5764             num_handles++;
5765             connection->num_packets_completed = 0;
5766         }
5767     }
5768 
5769     packet[2] = size - 3;
5770     packet[3] = num_handles;
5771 
5772     hci_stack->host_completed_packets = 0;
5773 
5774     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5775     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5776 
5777     // release packet buffer for synchronous transport implementations
5778     if (hci_transport_synchronous()){
5779         hci_release_packet_buffer();
5780         hci_emit_transport_packet_sent();
5781     }
5782 }
5783 #endif
5784 
5785 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5786     UNUSED(ds);
5787     hci_stack->substate = HCI_HALTING_CLOSE;
5788     hci_halting_run();
5789 }
5790 
5791 static bool hci_run_acl_fragments(void){
5792     if (hci_stack->acl_fragmentation_total_size > 0u) {
5793         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5794         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5795         if (connection) {
5796             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5797                 hci_send_acl_packet_fragments(connection);
5798                 return true;
5799             }
5800         } else {
5801             // connection gone -> discard further fragments
5802             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5803             hci_stack->acl_fragmentation_total_size = 0;
5804             hci_stack->acl_fragmentation_pos = 0;
5805         }
5806     }
5807     return false;
5808 }
5809 
5810 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5811 static bool hci_run_iso_fragments(void){
5812     if (hci_stack->iso_fragmentation_total_size > 0u) {
5813         // TODO: flow control
5814         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5815             hci_send_iso_packet_fragments();
5816             return true;
5817         }
5818     }
5819     return false;
5820 }
5821 #endif
5822 
5823 #ifdef ENABLE_CLASSIC
5824 
5825 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5826 static bool hci_classic_operation_active(void) {
5827     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5828         return true;
5829     }
5830     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5831         return true;
5832     }
5833     btstack_linked_item_t * it;
5834     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5835         hci_connection_t *connection = (hci_connection_t *) it;
5836         switch (connection->state) {
5837             case SENT_CREATE_CONNECTION:
5838             case SENT_CANCEL_CONNECTION:
5839             case SENT_DISCONNECT:
5840                 return true;
5841             default:
5842                 break;
5843         }
5844     }
5845     return false;
5846 }
5847 #endif
5848 
5849 static bool hci_run_general_gap_classic(void){
5850 
5851     // assert stack is working and classic is active
5852     if (hci_classic_supported() == false)      return false;
5853     if (hci_stack->state != HCI_STATE_WORKING) return false;
5854 
5855     // decline incoming connections
5856     if (hci_stack->decline_reason){
5857         uint8_t reason = hci_stack->decline_reason;
5858         hci_stack->decline_reason = 0;
5859         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5860         return true;
5861     }
5862 
5863     if (hci_stack->gap_tasks_classic != 0){
5864         hci_run_gap_tasks_classic();
5865         return true;
5866     }
5867 
5868     // start/stop inquiry
5869     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5870 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5871         if (hci_classic_operation_active() == false)
5872 #endif
5873         {
5874             uint8_t duration = hci_stack->inquiry_state;
5875             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5876             if (hci_stack->inquiry_max_period_length != 0){
5877                 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);
5878             } else {
5879                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5880             }
5881             return true;
5882         }
5883     }
5884     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5885         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5886         hci_send_cmd(&hci_inquiry_cancel);
5887         return true;
5888     }
5889 
5890     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5891         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5892         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5893         return true;
5894     }
5895 
5896     // remote name request
5897     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5898 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5899         if (hci_classic_operation_active() == false)
5900 #endif
5901         {
5902             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5903             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5904                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5905             return true;
5906         }
5907     }
5908 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5909     // Local OOB data
5910     if (hci_stack->classic_read_local_oob_data){
5911         hci_stack->classic_read_local_oob_data = false;
5912         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5913             hci_send_cmd(&hci_read_local_extended_oob_data);
5914         } else {
5915             hci_send_cmd(&hci_read_local_oob_data);
5916         }
5917     }
5918 #endif
5919     // pairing
5920     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5921         uint8_t state = hci_stack->gap_pairing_state;
5922         uint8_t pin_code[PIN_CODE_LEN];
5923         switch (state){
5924             case GAP_PAIRING_STATE_SEND_PIN:
5925                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5926                 memset(pin_code, 0, 16);
5927                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5928                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5929                 break;
5930             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5931                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5932                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5933                 break;
5934             case GAP_PAIRING_STATE_SEND_PASSKEY:
5935                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5936                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5937                 break;
5938             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5939                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5940                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5941                 break;
5942             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5943                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5944                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5945                 break;
5946             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5947                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5948                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5949                 break;
5950             default:
5951                 break;
5952         }
5953         return true;
5954     }
5955     return false;
5956 }
5957 #endif
5958 
5959 #ifdef ENABLE_BLE
5960 
5961 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5962 static uint8_t hci_le_num_phys(uint8_t phys){
5963     const uint8_t num_bits_set[] = { 0, 1, 1, 2, 1, 2, 2, 3 };
5964     btstack_assert(phys);
5965     return num_bits_set[phys];
5966 }
5967 #endif
5968 
5969 #ifdef ENABLE_LE_CENTRAL
5970 static void hci_le_scan_stop(void){
5971 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5972     if (hci_le_extended_advertising_supported()) {
5973             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5974     } else
5975 #endif
5976     {
5977         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5978     }
5979 }
5980 
5981 static void
5982 hci_send_le_create_connection(uint8_t initiator_filter_policy, bd_addr_type_t address_type, uint8_t *address) {
5983 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5984     if (hci_le_extended_advertising_supported()) {
5985         // prepare arrays for all phys (LE Coded, LE 1M, LE 2M PHY)
5986         uint16_t le_connection_scan_interval[3];
5987         uint16_t le_connection_scan_window[3];
5988         uint16_t le_connection_interval_min[3];
5989         uint16_t le_connection_interval_max[3];
5990         uint16_t le_connection_latency[3];
5991         uint16_t le_supervision_timeout[3];
5992         uint16_t le_minimum_ce_length[3];
5993         uint16_t le_maximum_ce_length[3];
5994 
5995         uint8_t i;
5996         uint8_t num_phys = hci_le_num_phys(hci_stack->le_connection_phys);
5997         for (i=0;i<num_phys;i++){
5998             le_connection_scan_interval[i] = hci_stack->le_connection_scan_interval;
5999             le_connection_scan_window[i]   = hci_stack->le_connection_scan_window;
6000             le_connection_interval_min[i]  = hci_stack->le_connection_interval_min;
6001             le_connection_interval_max[i]  = hci_stack->le_connection_interval_max;
6002             le_connection_latency[i]       = hci_stack->le_connection_latency;
6003             le_supervision_timeout[i]      = hci_stack->le_supervision_timeout;
6004             le_minimum_ce_length[i]        = hci_stack->le_minimum_ce_length;
6005             le_maximum_ce_length[i]        = hci_stack->le_maximum_ce_length;
6006         }
6007         hci_send_cmd(&hci_le_extended_create_connection,
6008                      initiator_filter_policy,
6009                      hci_stack->le_connection_own_addr_type,   // our addr type:
6010                      address_type,                  // peer address type
6011                      address,                       // peer bd addr
6012                      hci_stack->le_connection_phys, // initiating PHY
6013                      le_connection_scan_interval,   // conn scan interval
6014                      le_connection_scan_window,     // conn scan windows
6015                      le_connection_interval_min,    // conn interval min
6016                      le_connection_interval_max,    // conn interval max
6017                      le_connection_latency,         // conn latency
6018                      le_supervision_timeout,        // conn latency
6019                      le_minimum_ce_length,          // min ce length
6020                      le_maximum_ce_length           // max ce length
6021         );
6022     } else
6023 #endif
6024     {
6025         hci_send_cmd(&hci_le_create_connection,
6026                      hci_stack->le_connection_scan_interval,  // conn scan interval
6027                      hci_stack->le_connection_scan_window,    // conn scan windows
6028                      initiator_filter_policy,                 // don't use whitelist
6029                      address_type,                            // peer address type
6030                      address,                                 // peer bd addr
6031                      hci_stack->le_connection_own_addr_type,  // our addr type:
6032                      hci_stack->le_connection_interval_min,   // conn interval min
6033                      hci_stack->le_connection_interval_max,   // conn interval max
6034                      hci_stack->le_connection_latency,        // conn latency
6035                      hci_stack->le_supervision_timeout,       // conn latency
6036                      hci_stack->le_minimum_ce_length,         // min ce length
6037                      hci_stack->le_maximum_ce_length          // max ce length
6038         );
6039     }
6040 }
6041 #endif
6042 
6043 #ifdef ENABLE_LE_PERIPHERAL
6044 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6045 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
6046     uint8_t  operation = 0;
6047     if (pos == 0){
6048         // first fragment or complete data
6049         operation |= 1;
6050     }
6051     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
6052         // last fragment or complete data
6053         operation |= 2;
6054     }
6055     return operation;
6056 }
6057 #endif
6058 #endif
6059 
6060 static bool hci_run_general_gap_le(void){
6061 
6062     btstack_linked_list_iterator_t lit;
6063 
6064 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6065     if (hci_stack->le_resolvable_private_address_update_s > 0){
6066         uint16_t update_s = hci_stack->le_resolvable_private_address_update_s;
6067         hci_stack->le_resolvable_private_address_update_s = 0;
6068         hci_send_cmd(&hci_le_set_resolvable_private_address_timeout, update_s);
6069         return true;
6070     }
6071 #endif
6072 
6073     // Phase 1: collect what to stop
6074 
6075 #ifdef ENABLE_LE_CENTRAL
6076     bool scanning_stop = false;
6077     bool connecting_stop = false;
6078 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6079 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6080     bool periodic_sync_stop = false;
6081 #endif
6082 #endif
6083 #endif
6084 
6085 #ifdef ENABLE_LE_PERIPHERAL
6086     bool advertising_stop = false;
6087 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6088     le_advertising_set_t * advertising_stop_set = NULL;
6089 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6090     bool periodic_advertising_stop = false;
6091 #endif
6092 #endif
6093 #endif
6094 
6095     // check if own address changes
6096     uint8_t address_change_mask = LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
6097     bool random_address_change = (hci_stack->le_advertisements_todo & address_change_mask) != 0;
6098 
6099     // check if whitelist needs modification
6100     bool whitelist_modification_pending = false;
6101     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6102     while (btstack_linked_list_iterator_has_next(&lit)){
6103         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6104         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
6105             whitelist_modification_pending = true;
6106             break;
6107         }
6108     }
6109 
6110     // check if resolving list needs modification
6111     bool resolving_list_modification_pending = false;
6112 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6113     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
6114 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
6115         resolving_list_modification_pending = true;
6116     }
6117 #endif
6118 
6119 #ifdef ENABLE_LE_CENTRAL
6120 
6121 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6122     // check if periodic advertiser list needs modification
6123     bool periodic_list_modification_pending = false;
6124     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6125     while (btstack_linked_list_iterator_has_next(&lit)){
6126         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6127         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
6128             periodic_list_modification_pending = true;
6129             break;
6130         }
6131     }
6132 #endif
6133 
6134     // scanning control
6135     if (hci_stack->le_scanning_active) {
6136         // stop if:
6137         // - parameter change required
6138         // - it's disabled
6139         // - whitelist change required but used for scanning
6140         // - resolving list modified
6141         // - own address changes
6142         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
6143         if ((hci_stack->le_scanning_param_update) ||
6144             !hci_stack->le_scanning_enabled ||
6145             (scanning_uses_whitelist && whitelist_modification_pending) ||
6146             resolving_list_modification_pending ||
6147             random_address_change){
6148 
6149             scanning_stop = true;
6150         }
6151     }
6152 
6153     // connecting control
6154     bool connecting_with_whitelist;
6155     switch (hci_stack->le_connecting_state){
6156         case LE_CONNECTING_DIRECT:
6157         case LE_CONNECTING_WHITELIST:
6158             // stop connecting if:
6159             // - connecting uses white and whitelist modification pending
6160             // - if it got disabled
6161             // - resolving list modified
6162             // - own address changes
6163             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
6164             if ((connecting_with_whitelist && whitelist_modification_pending) ||
6165                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
6166                 resolving_list_modification_pending ||
6167                 random_address_change) {
6168 
6169                 connecting_stop = true;
6170             }
6171             break;
6172         default:
6173             break;
6174     }
6175 
6176 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6177 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6178     // periodic sync control
6179     bool sync_with_advertiser_list;
6180     switch(hci_stack->le_periodic_sync_state){
6181         case LE_CONNECTING_DIRECT:
6182         case LE_CONNECTING_WHITELIST:
6183             // stop sync if:
6184             // - sync with advertiser list and advertiser list modification pending
6185             // - if it got disabled
6186             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
6187             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
6188                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
6189                 periodic_sync_stop = true;
6190             }
6191             break;
6192         default:
6193             break;
6194     }
6195 #endif
6196 #endif
6197 
6198 #endif /* ENABLE_LE_CENTRAL */
6199 
6200 #ifdef ENABLE_LE_PERIPHERAL
6201     // le advertisement control
6202     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
6203         // stop if:
6204         // - parameter change required
6205         // - random address used in advertising and changes
6206         // - it's disabled
6207         // - whitelist change required but used for advertisement filter policy
6208         // - resolving list modified
6209         // - own address changes
6210         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
6211         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
6212         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
6213         if (advertising_change ||
6214             (advertising_uses_random_address && random_address_change) ||
6215             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
6216             (advertising_uses_whitelist && whitelist_modification_pending) ||
6217             resolving_list_modification_pending ||
6218             random_address_change) {
6219 
6220             advertising_stop = true;
6221         }
6222     }
6223 
6224 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6225     if (hci_le_extended_advertising_supported() && (advertising_stop == false)){
6226         btstack_linked_list_iterator_t it;
6227         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6228         while (btstack_linked_list_iterator_has_next(&it)){
6229             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6230             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
6231                 // stop if:
6232                 // - parameter change required
6233                 // - random address used in connectable advertising and changes
6234                 // - it's disabled
6235                 // - whitelist change required but used for advertisement filter policy
6236                 // - resolving list modified
6237                 // - own address changes
6238                 // - advertisement set will be removed
6239                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
6240                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
6241                 bool advertising_uses_random_address =
6242                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
6243                         advertising_connectable;
6244                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
6245                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
6246                 bool advertising_set_random_address_change =
6247                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
6248                 bool advertising_set_will_be_removed =
6249                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
6250                 if (advertising_parameter_change ||
6251                     (advertising_uses_random_address && advertising_set_random_address_change) ||
6252                     (advertising_enabled == false) ||
6253                     (advertising_uses_whitelist && whitelist_modification_pending) ||
6254                     resolving_list_modification_pending ||
6255                     advertising_set_will_be_removed) {
6256 
6257                     advertising_stop = true;
6258                     advertising_stop_set = advertising_set;
6259                     break;
6260                 }
6261             }
6262 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6263             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
6264                 // stop if:
6265                 // - it's disabled
6266                 // - parameter change required
6267                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
6268                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
6269                 if ((periodic_enabled == false) || periodic_parameter_change){
6270                     periodic_advertising_stop = true;
6271                     advertising_stop_set = advertising_set;
6272                 }
6273             }
6274 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6275         }
6276     }
6277 #endif
6278 
6279 #endif
6280 
6281 
6282     // Phase 2: stop everything that should be off during modifications
6283 
6284 
6285     // 2.1 Outgoing connection
6286 #ifdef ENABLE_LE_CENTRAL
6287     if (connecting_stop){
6288         hci_send_cmd(&hci_le_create_connection_cancel);
6289         return true;
6290     }
6291 #endif
6292 
6293     // 2.2 Scanning
6294 #ifdef ENABLE_LE_CENTRAL
6295     if (scanning_stop){
6296         hci_stack->le_scanning_active = false;
6297         hci_le_scan_stop();
6298         return true;
6299     }
6300 
6301     // 2.3 Periodic Sync
6302 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6303     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
6304         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
6305         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
6306         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
6307         return true;
6308     }
6309 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6310     if (periodic_sync_stop){
6311         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
6312         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
6313         return true;
6314     }
6315 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6316 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6317 #endif /* ENABLE_LE_CENTRAL */
6318 
6319     // 2.4 Advertising: legacy, extended, periodic
6320 #ifdef ENABLE_LE_PERIPHERAL
6321     if (advertising_stop){
6322 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6323         if (hci_le_extended_advertising_supported()) {
6324             uint8_t advertising_stop_handle;
6325             if (advertising_stop_set != NULL){
6326                 advertising_stop_handle = advertising_stop_set->advertising_handle;
6327                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6328             } else {
6329                 advertising_stop_handle = 0;
6330                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6331             }
6332             const uint8_t advertising_handles[] = { advertising_stop_handle };
6333             const uint16_t durations[] = { 0 };
6334             const uint16_t max_events[] = { 0 };
6335             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
6336         } else
6337 #endif
6338         {
6339             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6340             hci_send_cmd(&hci_le_set_advertise_enable, 0);
6341         }
6342         return true;
6343     }
6344 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6345 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6346     if (periodic_advertising_stop){
6347         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6348         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
6349         return true;
6350     }
6351 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6352 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6353 #endif /* ENABLE_LE_PERIPHERAL */
6354 
6355 
6356     // Phase 3: modify
6357 
6358     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY) {
6359         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
6360         // GAP Privacy, notify clients upon upcoming random address change
6361         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
6362         gap_privacy_clients_notify(hci_stack->le_random_address);
6363     }
6364 
6365     // - wait until privacy update completed
6366     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PRIVACY_PENDING) != 0){
6367         return false;
6368     }
6369 
6370     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS){
6371         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6372         hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
6373 #ifdef ENABLE_LE_SET_ADV_PARAMS_ON_RANDOM_ADDRESS_CHANGE
6374         // workaround: on some Controllers, address in advertisements is updated only after next dv params set
6375         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6376 #endif
6377         return true;
6378     }
6379 
6380 #ifdef ENABLE_LE_CENTRAL
6381     if (hci_stack->le_scanning_param_update){
6382         hci_stack->le_scanning_param_update = false;
6383 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6384         if (hci_le_extended_advertising_supported()){
6385             // prepare arrays for all phys (LE Coded and LE 1M PHY)
6386             uint8_t  scan_types[2];
6387             uint16_t scan_intervals[2];
6388             uint16_t scan_windows[2];
6389 
6390             uint8_t i;
6391             uint8_t num_phys = hci_le_num_phys(hci_stack->le_scan_phys);
6392             for (i=0;i<num_phys;i++){
6393                 scan_types[i]     = hci_stack->le_scan_type;
6394                 scan_intervals[i] = hci_stack->le_scan_interval;
6395                 scan_windows[i]   = hci_stack->le_scan_window;
6396             }
6397             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
6398                          hci_stack->le_scan_filter_policy, hci_stack->le_scan_phys, scan_types, scan_intervals, scan_windows);
6399         } else
6400 #endif
6401         {
6402             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
6403                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
6404         }
6405         return true;
6406     }
6407 #endif
6408 
6409 #ifdef ENABLE_LE_PERIPHERAL
6410     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
6411         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6412         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
6413 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6414         if (hci_le_extended_advertising_supported()){
6415             // map advertisment type to advertising event properties
6416             uint16_t adv_event_properties = 0;
6417             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
6418             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
6419                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
6420             }
6421             hci_stack->le_advertising_set_in_current_command = 0;
6422             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6423                          0,
6424                          adv_event_properties,
6425                          hci_stack->le_advertisements_interval_min,
6426                          hci_stack->le_advertisements_interval_max,
6427                          hci_stack->le_advertisements_channel_map,
6428                          hci_stack->le_advertisements_own_addr_type,
6429                          hci_stack->le_advertisements_direct_address_type,
6430                          hci_stack->le_advertisements_direct_address,
6431                          hci_stack->le_advertisements_filter_policy,
6432                          0x7f,  // tx power: no preference
6433                          0x01,  // primary adv phy: LE 1M
6434                          0,     // secondary adv max skip
6435                          0x01,  // secondary adv phy
6436                          0,     // adv sid
6437                          0      // scan request notification
6438                          );
6439         } else
6440 #endif
6441         {
6442             hci_send_cmd(&hci_le_set_advertising_parameters,
6443                          hci_stack->le_advertisements_interval_min,
6444                          hci_stack->le_advertisements_interval_max,
6445                          hci_stack->le_advertisements_type,
6446                          hci_stack->le_advertisements_own_addr_type,
6447                          hci_stack->le_advertisements_direct_address_type,
6448                          hci_stack->le_advertisements_direct_address,
6449                          hci_stack->le_advertisements_channel_map,
6450                          hci_stack->le_advertisements_filter_policy);
6451         }
6452         return true;
6453     }
6454 
6455 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6456     // assumption: only set if extended advertising is supported
6457     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0) != 0){
6458         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
6459         hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
6460         return true;
6461     }
6462 #endif
6463 
6464     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
6465         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6466         uint8_t adv_data_clean[31];
6467         memset(adv_data_clean, 0, sizeof(adv_data_clean));
6468         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
6469                      hci_stack->le_advertisements_data_len);
6470         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
6471 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6472         if (hci_le_extended_advertising_supported()){
6473             hci_stack->le_advertising_set_in_current_command = 0;
6474             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
6475         } else
6476 #endif
6477         {
6478             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
6479         }
6480         return true;
6481     }
6482 
6483     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
6484         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6485         uint8_t scan_data_clean[31];
6486         memset(scan_data_clean, 0, sizeof(scan_data_clean));
6487         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
6488                      hci_stack->le_scan_response_data_len);
6489         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6490 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6491         if (hci_le_extended_advertising_supported()){
6492             hci_stack->le_advertising_set_in_current_command = 0;
6493             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6494         } else
6495 #endif
6496         {
6497             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6498         }
6499         return true;
6500     }
6501 
6502 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6503     if (hci_le_extended_advertising_supported()) {
6504         btstack_linked_list_iterator_t it;
6505         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6506         while (btstack_linked_list_iterator_has_next(&it)){
6507             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6508             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6509                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6510                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6511                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6512                 return true;
6513             }
6514             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6515                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6516                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6517                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6518                              advertising_set->advertising_handle,
6519                              advertising_set->extended_params.advertising_event_properties,
6520                              advertising_set->extended_params.primary_advertising_interval_min,
6521                              advertising_set->extended_params.primary_advertising_interval_max,
6522                              advertising_set->extended_params.primary_advertising_channel_map,
6523                              advertising_set->extended_params.own_address_type,
6524                              advertising_set->extended_params.peer_address_type,
6525                              advertising_set->extended_params.peer_address,
6526                              advertising_set->extended_params.advertising_filter_policy,
6527                              advertising_set->extended_params.advertising_tx_power,
6528                              advertising_set->extended_params.primary_advertising_phy,
6529                              advertising_set->extended_params.secondary_advertising_max_skip,
6530                              advertising_set->extended_params.secondary_advertising_phy,
6531                              advertising_set->extended_params.advertising_sid,
6532                              advertising_set->extended_params.scan_request_notification_enable
6533                 );
6534                 return true;
6535             }
6536             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
6537                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6538                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
6539                 return true;
6540             }
6541             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6542                 uint16_t pos = advertising_set->adv_data_pos;
6543                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6544                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6545                 if ((operation & 0x02) != 0){
6546                     // last fragment or complete data
6547                     operation |= 2;
6548                     advertising_set->adv_data_pos = 0;
6549                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6550                 } else {
6551                     advertising_set->adv_data_pos += data_to_upload;
6552                 }
6553                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6554                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6555                 return true;
6556             }
6557             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6558                 uint16_t pos = advertising_set->scan_data_pos;
6559                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6560                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6561                 if ((operation & 0x02) != 0){
6562                     advertising_set->scan_data_pos = 0;
6563                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6564                 } else {
6565                     advertising_set->scan_data_pos += data_to_upload;
6566                 }
6567                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6568                 hci_send_cmd(&hci_le_set_extended_scan_response_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
6569                 return true;
6570             }
6571 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6572             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
6573                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
6574                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6575                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
6576                              advertising_set->advertising_handle,
6577                              advertising_set->periodic_params.periodic_advertising_interval_min,
6578                              advertising_set->periodic_params.periodic_advertising_interval_max,
6579                              advertising_set->periodic_params.periodic_advertising_properties);
6580                 return true;
6581             }
6582             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
6583                 uint16_t pos = advertising_set->periodic_data_pos;
6584                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
6585                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6586                 if ((operation & 0x02) != 0){
6587                     // last fragment or complete data
6588                     operation |= 2;
6589                     advertising_set->periodic_data_pos = 0;
6590                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
6591                 } else {
6592                     advertising_set->periodic_data_pos += data_to_upload;
6593                 }
6594                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6595                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
6596                 return true;
6597             }
6598 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6599         }
6600     }
6601 #endif
6602 
6603 #endif
6604 
6605 #ifdef ENABLE_LE_CENTRAL
6606     // if connect with whitelist was active and is not cancelled yet, wait until next time
6607     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
6608 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6609     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
6610     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
6611 #endif
6612 #endif
6613 
6614     // LE Whitelist Management
6615     if (whitelist_modification_pending){
6616         // add/remove entries
6617         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6618         while (btstack_linked_list_iterator_has_next(&lit)){
6619             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6620 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
6621 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6622                 entry->state &= ~LE_WHITELIST_ON_CONTROLLER;
6623                 bd_addr_type_t address_type = entry->address_type;
6624                 bd_addr_t address;
6625                 memcpy(address, entry->address, 6);
6626                 if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) == 0){
6627                     // remove from whitelist if not scheduled for re-addition
6628                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6629                     btstack_memory_whitelist_entry_free(entry);
6630                 }
6631 				hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
6632 				return true;
6633 			}
6634             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
6635 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
6636                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
6637                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
6638                 return true;
6639             }
6640         }
6641     }
6642 
6643 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6644     // LE Resolving List Management
6645     if (resolving_list_modification_pending) {
6646 		uint16_t i;
6647         uint8_t null_16[16];
6648         uint8_t local_irk_flipped[16];
6649         const uint8_t *local_irk;
6650 		switch (hci_stack->le_resolving_list_state) {
6651 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
6652 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6653 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
6654 				return true;
6655 			case LE_RESOLVING_LIST_READ_SIZE:
6656 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
6657 				hci_send_cmd(&hci_le_read_resolving_list_size);
6658 				return true;
6659 			case LE_RESOLVING_LIST_SEND_CLEAR:
6660 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SET_IRK;
6661 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6662 							  sizeof(hci_stack->le_resolving_list_add_entries));
6663                 (void) memset(hci_stack->le_resolving_list_set_privacy_mode, 0xff,
6664                               sizeof(hci_stack->le_resolving_list_set_privacy_mode));
6665 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6666 							  sizeof(hci_stack->le_resolving_list_remove_entries));
6667 				hci_send_cmd(&hci_le_clear_resolving_list);
6668 				return true;
6669             case LE_RESOLVING_LIST_SET_IRK:
6670                 // set IRK used by RPA for undirected advertising
6671                 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
6672                 local_irk = gap_get_persistent_irk();
6673                 reverse_128(local_irk, local_irk_flipped);
6674                 memset(null_16, 0, sizeof(null_16));
6675                 hci_send_cmd(&hci_le_add_device_to_resolving_list, BD_ADDR_TYPE_LE_PUBLIC, null_16,
6676                              null_16, local_irk_flipped);
6677                 return true;
6678 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
6679                 // first remove old entries
6680 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6681 					uint8_t offset = i >> 3;
6682 					uint8_t mask = 1 << (i & 7);
6683 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
6684 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
6685 					bd_addr_t peer_identity_addreses;
6686 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6687 					sm_key_t peer_irk;
6688 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6689 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6690 
6691 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6692 					// trigger whitelist entry 'update' (work around for controller bug)
6693 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6694 					while (btstack_linked_list_iterator_has_next(&lit)) {
6695 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6696 						if (entry->address_type != peer_identity_addr_type) continue;
6697 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6698 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6699 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6700 					}
6701 #endif
6702 
6703 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6704 								 peer_identity_addreses);
6705 					return true;
6706 				}
6707 
6708                 // then add new entries
6709 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6710 					uint8_t offset = i >> 3;
6711 					uint8_t mask = 1 << (i & 7);
6712 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
6713 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
6714 					bd_addr_t peer_identity_addreses;
6715 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6716 					sm_key_t peer_irk;
6717 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6718 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6719                     if (btstack_is_null(peer_irk, 16)) continue;
6720 					local_irk = gap_get_persistent_irk();
6721 					// command uses format specifier 'P' that stores 16-byte value without flip
6722 					uint8_t peer_irk_flipped[16];
6723 					reverse_128(local_irk, local_irk_flipped);
6724 					reverse_128(peer_irk, peer_irk_flipped);
6725 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6726 								 peer_irk_flipped, local_irk_flipped);
6727 					return true;
6728 				}
6729 
6730                 // finally, set privacy mode
6731                 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6732                     uint8_t offset = i >> 3;
6733                     uint8_t mask = 1 << (i & 7);
6734                     if ((hci_stack->le_resolving_list_set_privacy_mode[offset] & mask) == 0) continue;
6735                     hci_stack->le_resolving_list_set_privacy_mode[offset] &= ~mask;
6736                     if (hci_stack->le_privacy_mode == LE_PRIVACY_MODE_NETWORK) {
6737                         // Network Privacy Mode is default
6738                         continue;
6739                     }
6740                     bd_addr_t peer_identity_address;
6741                     int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6742                     sm_key_t peer_irk;
6743                     le_device_db_info(i, &peer_identity_addr_type, peer_identity_address, peer_irk);
6744                     if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6745                     if (btstack_is_null(peer_irk, 16)) continue;
6746                     // command uses format specifier 'P' that stores 16-byte value without flip
6747                     uint8_t peer_irk_flipped[16];
6748                     reverse_128(peer_irk, peer_irk_flipped);
6749                     hci_send_cmd(&hci_le_set_privacy_mode, peer_identity_addr_type, peer_identity_address, hci_stack->le_privacy_mode);
6750                     return true;
6751                 }
6752 				break;
6753 
6754 			default:
6755 				break;
6756 		}
6757         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6758 	}
6759 #endif
6760 
6761 #ifdef ENABLE_LE_CENTRAL
6762 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6763     // LE Whitelist Management
6764     if (periodic_list_modification_pending){
6765         // add/remove entries
6766         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6767         while (btstack_linked_list_iterator_has_next(&lit)){
6768             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6769             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6770                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6771                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6772                 return true;
6773             }
6774             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6775                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6776                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
6777                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6778                 return true;
6779             }
6780             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6781                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6782                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6783             }
6784         }
6785     }
6786 #endif
6787 #endif
6788 
6789 #ifdef ENABLE_LE_CENTRAL
6790 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6791 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6792     if (hci_stack->le_past_set_default_params){
6793         hci_stack->le_past_set_default_params = false;
6794         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
6795                      hci_stack->le_past_mode,
6796                      hci_stack->le_past_skip,
6797                      hci_stack->le_past_sync_timeout,
6798                      hci_stack->le_past_cte_type);
6799         return true;
6800     }
6801 #endif
6802 #endif
6803 #endif
6804 
6805     // post-pone all actions until stack is fully working
6806     if (hci_stack->state != HCI_STATE_WORKING) return false;
6807 
6808     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6809     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6810 
6811     // Phase 4: restore state
6812 
6813 #ifdef ENABLE_LE_CENTRAL
6814     // re-start scanning
6815     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6816         hci_stack->le_scanning_active = true;
6817 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6818         if (hci_le_extended_advertising_supported()){
6819             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
6820         } else
6821 #endif
6822         {
6823             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
6824         }
6825         return true;
6826     }
6827 #endif
6828 
6829 #ifdef ENABLE_LE_CENTRAL
6830     // re-start connecting
6831     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6832         bd_addr_t null_addr;
6833         memset(null_addr, 0, 6);
6834         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6835         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6836         hci_send_le_create_connection(1, 0, null_addr);
6837         return true;
6838     }
6839 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6840     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6841         switch(hci_stack->le_periodic_sync_request){
6842             case LE_CONNECTING_DIRECT:
6843             case LE_CONNECTING_WHITELIST:
6844                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6845                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6846                              hci_stack->le_periodic_sync_options,
6847                              hci_stack->le_periodic_sync_advertising_sid,
6848                              hci_stack->le_periodic_sync_advertiser_address_type,
6849                              hci_stack->le_periodic_sync_advertiser_address,
6850                              hci_stack->le_periodic_sync_skip,
6851                              hci_stack->le_periodic_sync_timeout,
6852                              hci_stack->le_periodic_sync_cte_type);
6853                 return true;
6854             default:
6855                 break;
6856         }
6857     }
6858 #endif
6859 #endif
6860 
6861 #ifdef ENABLE_LE_PERIPHERAL
6862     // re-start advertising
6863     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6864         // check if advertisements should be enabled given
6865         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6866         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6867 
6868 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6869         if (hci_le_extended_advertising_supported()){
6870             const uint8_t advertising_handles[] = { 0 };
6871             const uint16_t durations[] = { 0 };
6872             const uint16_t max_events[] = { 0 };
6873             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6874         } else
6875 #endif
6876         {
6877             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6878         }
6879         return true;
6880     }
6881 
6882 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6883     if (hci_le_extended_advertising_supported()) {
6884         btstack_linked_list_iterator_t it;
6885         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6886         while (btstack_linked_list_iterator_has_next(&it)) {
6887             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6888             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6889                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6890                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6891                 const uint16_t durations[] = { advertising_set->enable_timeout };
6892                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6893                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6894                 return true;
6895             }
6896 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6897             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6898                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6899                 uint8_t enable = 1;
6900                 if (advertising_set->periodic_include_adi){
6901                     enable |= 2;
6902                 }
6903                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6904                 return true;
6905             }
6906 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6907         }
6908     }
6909 #endif
6910 #endif
6911 
6912     return false;
6913 }
6914 
6915 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6916 static bool hci_run_iso_tasks(void){
6917     btstack_linked_list_iterator_t it;
6918 
6919     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
6920         return false;
6921     }
6922 
6923     // BIG
6924     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6925     while (btstack_linked_list_iterator_has_next(&it)){
6926         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6927         switch (big->state){
6928             case LE_AUDIO_BIG_STATE_CREATE:
6929                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
6930                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6931                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6932                 hci_send_cmd(&hci_le_create_big,
6933                              big->params->big_handle,
6934                              big->params->advertising_handle,
6935                              big->params->num_bis,
6936                              big->params->sdu_interval_us,
6937                              big->params->max_sdu,
6938                              big->params->max_transport_latency_ms,
6939                              big->params->rtn,
6940                              big->params->phy,
6941                              big->params->packing,
6942                              big->params->framing,
6943                              big->params->encryption,
6944                              big->params->broadcast_code);
6945                 return true;
6946             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6947                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6948                 hci_send_cmd(&hci_le_setup_iso_data_path, big->bis_con_handles[big->state_vars.next_bis], 0, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0,  0, 0, NULL);
6949                 return true;
6950             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6951                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6952                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6953                 return true;
6954             case LE_AUDIO_BIG_STATE_TERMINATE:
6955                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6956                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6957                 return true;
6958             default:
6959                 break;
6960         }
6961     }
6962 
6963     // BIG Sync
6964     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6965     while (btstack_linked_list_iterator_has_next(&it)){
6966         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6967         switch (big_sync->state){
6968             case LE_AUDIO_BIG_STATE_CREATE:
6969                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
6970                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6971                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6972                 hci_send_cmd(&hci_le_big_create_sync,
6973                              big_sync->params->big_handle,
6974                              big_sync->params->sync_handle,
6975                              big_sync->params->encryption,
6976                              big_sync->params->broadcast_code,
6977                              big_sync->params->mse,
6978                              big_sync->params->big_sync_timeout_10ms,
6979                              big_sync->params->num_bis,
6980                              big_sync->params->bis_indices);
6981                 return true;
6982             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6983                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6984                 hci_send_cmd(&hci_le_setup_iso_data_path, big_sync->bis_con_handles[big_sync->state_vars.next_bis], 1, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0, 0, 0, NULL);
6985                 return true;
6986             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6987                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6988                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6989                 return true;
6990             case LE_AUDIO_BIG_STATE_TERMINATE:
6991                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6992                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6993                 return true;
6994             default:
6995                 break;
6996         }
6997     }
6998 
6999     // CIG
7000     bool cig_active;
7001     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
7002     while (btstack_linked_list_iterator_has_next(&it)) {
7003         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
7004         uint8_t i;
7005         // Set CIG Parameters
7006         uint8_t cis_id[MAX_NR_CIS];
7007         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
7008         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
7009         uint8_t phy_c_to_p[MAX_NR_CIS];
7010         uint8_t phy_p_to_c[MAX_NR_CIS];
7011         uint8_t rtn_c_to_p[MAX_NR_CIS];
7012         uint8_t rtn_p_to_c[MAX_NR_CIS];
7013         switch (cig->state) {
7014             case LE_AUDIO_CIG_STATE_CREATE:
7015                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7016                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7017                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
7018                 le_audio_cig_params_t * params = cig->params;
7019                 for (i = 0; i < params->num_cis; i++) {
7020                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
7021                     cis_id[i]         = cis_params->cis_id;
7022                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
7023                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
7024                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
7025                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
7026                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
7027                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
7028                 }
7029                 hci_send_cmd(&hci_le_set_cig_parameters,
7030                              cig->cig_id,
7031                              params->sdu_interval_c_to_p,
7032                              params->sdu_interval_p_to_c,
7033                              params->worst_case_sca,
7034                              params->packing,
7035                              params->framing,
7036                              params->max_transport_latency_c_to_p,
7037                              params->max_transport_latency_p_to_c,
7038                              params->num_cis,
7039                              cis_id,
7040                              max_sdu_c_to_p,
7041                              max_sdu_p_to_c,
7042                              phy_c_to_p,
7043                              phy_p_to_c,
7044                              rtn_c_to_p,
7045                              rtn_p_to_c
7046                 );
7047                 return true;
7048             case LE_AUDIO_CIG_STATE_CREATE_CIS:
7049                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7050                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7051                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
7052                 for (i=0;i<cig->num_cis;i++){
7053                     cig->cis_setup_active[i] = true;
7054                 }
7055                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
7056                 return true;
7057             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
7058                 while (cig->state_vars.next_cis < (cig->num_cis * 2)){
7059                     // find next path to setup
7060                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
7061                     if (cig->cis_established[cis_index] == false) {
7062                         continue;
7063                     }
7064                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
7065                     bool setup = true;
7066                     if (cis_direction == 0){
7067                         // 0 - input - host to controller
7068                         // we are central => central to peripheral
7069                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
7070                     } else {
7071                         // 1 - output - controller to host
7072                         // we are central => peripheral to central
7073                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
7074                     }
7075                     if (setup){
7076                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7077                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7078                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
7079                         hci_send_cmd(&hci_le_setup_iso_data_path, cig->cis_con_handles[cis_index], cis_direction, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0, 0, 0, NULL);
7080                         return true;
7081                     }
7082                     cig->state_vars.next_cis++;
7083                 }
7084                 // emit done
7085                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
7086                 break;
7087             case LE_AUDIO_CIG_STATE_REMOVE:
7088                 // check if CIG Active
7089                 cig_active = false;
7090                 for (i = 0; i < cig->num_cis; i++) {
7091                     if (cig->cis_con_handles[i] != HCI_CON_HANDLE_INVALID){
7092                         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
7093                         if (stream != NULL){
7094                             cig_active = true;
7095                             break;
7096                         }
7097                     }
7098                 }
7099                 if (cig_active == false){
7100                     btstack_linked_list_iterator_remove(&it);
7101                     hci_send_cmd(&hci_le_remove_cig, cig->cig_id);
7102                     return true;
7103                 }
7104             default:
7105                 break;
7106         }
7107     }
7108 
7109     // CIS Accept/Reject/Setup ISO Path/Close
7110     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
7111     while (btstack_linked_list_iterator_has_next(&it)) {
7112         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
7113         hci_con_handle_t con_handle;
7114         switch (iso_stream->state){
7115             case HCI_ISO_STREAM_W2_ACCEPT:
7116                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
7117                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7118                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7119                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->cis_handle);
7120                 return true;
7121             case HCI_ISO_STREAM_W2_REJECT:
7122                 con_handle = iso_stream->cis_handle;
7123                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7124                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7125                 hci_iso_stream_finalize(iso_stream);
7126                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
7127                 return true;
7128             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
7129                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7130                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7131                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
7132                 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->cis_handle, 0, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0, 0, 0, NULL);
7133                 break;
7134             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
7135                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7136                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7137                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT;
7138                 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->cis_handle, 1, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0, 0, 0, NULL);
7139                 break;
7140             case HCI_ISO_STREAM_STATE_W2_CLOSE:
7141                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_DISCONNECTED;
7142                 hci_send_cmd(&hci_disconnect, iso_stream->cis_handle);
7143                 break;
7144             default:
7145                 break;
7146         }
7147     }
7148 
7149     return false;
7150 }
7151 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
7152 #endif
7153 
7154 static bool hci_run_general_pending_commands(void){
7155     btstack_linked_item_t * it;
7156     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7157         hci_connection_t * connection = (hci_connection_t *) it;
7158 
7159         switch(connection->state){
7160             case SEND_CREATE_CONNECTION:
7161                 switch(connection->address_type){
7162 #ifdef ENABLE_CLASSIC
7163                     case BD_ADDR_TYPE_ACL:
7164                         log_info("sending hci_create_connection");
7165                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
7166                         break;
7167 #endif
7168                     default:
7169 #ifdef ENABLE_BLE
7170 #ifdef ENABLE_LE_CENTRAL
7171                         log_info("sending hci_le_create_connection");
7172                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
7173                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
7174                         hci_send_le_create_connection(0, connection->address_type, connection->address);
7175                         connection->state = SENT_CREATE_CONNECTION;
7176 #endif
7177 #endif
7178                         break;
7179                 }
7180                 return true;
7181 
7182 #ifdef ENABLE_CLASSIC
7183             case RECEIVED_CONNECTION_REQUEST:
7184                 if (connection->address_type == BD_ADDR_TYPE_ACL){
7185                     log_info("sending hci_accept_connection_request");
7186                     connection->state = ACCEPTED_CONNECTION_REQUEST;
7187                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
7188                     return true;
7189                 }
7190                 break;
7191 #endif
7192             case SEND_DISCONNECT:
7193                 connection->state = SENT_DISCONNECT;
7194                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7195                 return true;
7196 
7197             default:
7198                 break;
7199         }
7200 
7201         // no further commands if connection is about to get shut down
7202         if (connection->state == SENT_DISCONNECT) continue;
7203 
7204 #ifdef ENABLE_CLASSIC
7205 
7206         // Handling link key request requires remote supported features
7207         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
7208             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
7209             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
7210 
7211             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
7212             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
7213             if (have_link_key && security_level_sufficient){
7214                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
7215             } else {
7216                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
7217             }
7218             return true;
7219         }
7220 
7221         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
7222             log_info("denying to pin request");
7223             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
7224             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
7225             return true;
7226         }
7227 
7228         // security assessment requires remote features
7229         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
7230             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
7231             hci_ssp_assess_security_on_io_cap_request(connection);
7232             // 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
7233         }
7234 
7235         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
7236             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7237             // set authentication requirements:
7238             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
7239             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
7240             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
7241             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
7242                 authreq |= 1;
7243             }
7244             bool bonding = hci_stack->bondable;
7245             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
7246                 // if we have received IO Cap Response, we're in responder role
7247                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7248                 if (bonding && !remote_bonding){
7249                     log_info("Remote not bonding, dropping local flag");
7250                     bonding = false;
7251                 }
7252             }
7253             if (bonding){
7254                 if (connection->bonding_flags & BONDING_DEDICATED){
7255                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7256                 } else {
7257                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
7258                 }
7259             }
7260             uint8_t have_oob_data = 0;
7261 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7262             if (connection->classic_oob_c_192 != NULL){
7263                     have_oob_data |= 1;
7264             }
7265             if (connection->classic_oob_c_256 != NULL){
7266                 have_oob_data |= 2;
7267             }
7268 #endif
7269             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
7270             return true;
7271         }
7272 
7273         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
7274             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
7275             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
7276             return true;
7277         }
7278 
7279 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7280         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
7281             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
7282             const uint8_t zero[16] = { 0 };
7283             const uint8_t * r_192 = zero;
7284             const uint8_t * c_192 = zero;
7285             const uint8_t * r_256 = zero;
7286             const uint8_t * c_256 = zero;
7287             // verify P-256 OOB
7288             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
7289                 c_256 = connection->classic_oob_c_256;
7290                 if (connection->classic_oob_r_256 != NULL) {
7291                     r_256 = connection->classic_oob_r_256;
7292                 }
7293             }
7294             // verify P-192 OOB
7295             if ((connection->classic_oob_c_192 != NULL)) {
7296                 c_192 = connection->classic_oob_c_192;
7297                 if (connection->classic_oob_r_192 != NULL) {
7298                     r_192 = connection->classic_oob_r_192;
7299                 }
7300             }
7301 
7302             // assess security
7303             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
7304             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
7305             if (need_level_4 && !can_reach_level_4){
7306                 log_info("Level 4 required, but not possible -> abort");
7307                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
7308                 // send oob negative reply
7309                 c_256 = NULL;
7310                 c_192 = NULL;
7311             }
7312 
7313             // Reply
7314             if (c_256 != zero) {
7315                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
7316             } else if (c_192 != zero){
7317                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
7318             } else {
7319                 hci_stack->classic_oob_con_handle = connection->con_handle;
7320                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
7321             }
7322             return true;
7323         }
7324 #endif
7325 
7326         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
7327             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
7328             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
7329             return true;
7330         }
7331 
7332         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
7333             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
7334             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
7335             return true;
7336         }
7337 
7338         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
7339             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
7340             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
7341             return true;
7342         }
7343 
7344         if ((connection->bonding_flags & (BONDING_DISCONNECT_DEDICATED_DONE | BONDING_DEDICATED_DEFER_DISCONNECT)) == BONDING_DISCONNECT_DEDICATED_DONE){
7345             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
7346             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
7347             connection->state = SENT_DISCONNECT;
7348             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7349             return true;
7350         }
7351 
7352         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
7353             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
7354             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
7355             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
7356             return true;
7357         }
7358 
7359         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
7360             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
7361             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
7362             return true;
7363         }
7364 
7365         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
7366             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
7367             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
7368             return true;
7369         }
7370 
7371         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
7372             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7373             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
7374             return true;
7375         }
7376 
7377         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
7378             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
7379             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
7380             return true;
7381         }
7382 
7383         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
7384             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
7385             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
7386             return true;
7387         }
7388 #endif
7389 
7390         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
7391             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
7392 #ifdef ENABLE_CLASSIC
7393             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
7394 #endif
7395             if (connection->state != SENT_DISCONNECT){
7396                 connection->state = SENT_DISCONNECT;
7397                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
7398                 return true;
7399             }
7400         }
7401 
7402 #ifdef ENABLE_CLASSIC
7403         uint16_t sniff_min_interval;
7404         switch (connection->sniff_min_interval){
7405             case 0:
7406                 break;
7407             case 0xffff:
7408                 connection->sniff_min_interval = 0;
7409                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
7410                 return true;
7411             default:
7412                 sniff_min_interval = connection->sniff_min_interval;
7413                 connection->sniff_min_interval = 0;
7414                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
7415                 return true;
7416         }
7417 
7418         if (connection->sniff_subrating_max_latency != 0xffff){
7419             uint16_t max_latency = connection->sniff_subrating_max_latency;
7420             connection->sniff_subrating_max_latency = 0;
7421             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
7422             return true;
7423         }
7424 
7425         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
7426             uint8_t service_type = (uint8_t) connection->qos_service_type;
7427             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
7428             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);
7429             return true;
7430         }
7431 
7432         if (connection->request_role != HCI_ROLE_INVALID){
7433             hci_role_t role = connection->request_role;
7434             connection->request_role = HCI_ROLE_INVALID;
7435             hci_send_cmd(&hci_switch_role_command, connection->address, role);
7436             return true;
7437         }
7438 #endif
7439 
7440         if (connection->gap_connection_tasks != 0){
7441 #ifdef ENABLE_CLASSIC
7442             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
7443                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
7444                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
7445                 return true;
7446             }
7447             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
7448                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
7449                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
7450                 return true;
7451             }
7452 #endif
7453             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
7454                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
7455                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
7456                 return true;
7457             }
7458 #ifdef ENABLE_BLE
7459             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
7460                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
7461                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
7462                 return true;
7463             }
7464 #endif
7465         }
7466 
7467 #ifdef ENABLE_BLE
7468         switch (connection->le_con_parameter_update_state){
7469             // response to L2CAP CON PARAMETER UPDATE REQUEST
7470             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
7471                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7472                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
7473                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7474                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7475                 return true;
7476             case CON_PARAMETER_UPDATE_REPLY:
7477                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7478                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
7479                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7480                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7481                 return true;
7482             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
7483                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7484                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
7485                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
7486                 return true;
7487             default:
7488                 break;
7489         }
7490         if (connection->le_phy_update_all_phys != 0xffu){
7491             uint8_t all_phys = connection->le_phy_update_all_phys;
7492             connection->le_phy_update_all_phys = 0xff;
7493             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);
7494             return true;
7495         }
7496 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7497         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
7498             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
7499             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
7500             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
7501             return true;
7502         }
7503         if (connection->le_past_advertising_handle != 0xff){
7504             uint8_t advertising_handle = connection->le_past_advertising_handle;
7505             connection->le_past_advertising_handle = 0xff;
7506             hci_send_cmd(&hci_le_periodic_advertising_set_info_transfer, connection->con_handle, connection->le_past_service_data, advertising_handle);
7507             return true;
7508         }
7509 #endif
7510 #endif
7511     }
7512     return false;
7513 }
7514 
7515 static void hci_run(void){
7516 
7517     // stack state sub statemachines
7518     switch (hci_stack->state) {
7519         case HCI_STATE_INITIALIZING:
7520             hci_initializing_run();
7521             break;
7522         case HCI_STATE_HALTING:
7523             hci_halting_run();
7524             break;
7525         case HCI_STATE_FALLING_ASLEEP:
7526             hci_falling_asleep_run();
7527             break;
7528         default:
7529             break;
7530     }
7531 
7532     // allow to run after initialization to working transition
7533     if (hci_stack->state != HCI_STATE_WORKING){
7534         return;
7535     }
7536 
7537     bool done;
7538 
7539     // send continuation fragments first, as they block the prepared packet buffer
7540     done = hci_run_acl_fragments();
7541     if (done) return;
7542 
7543 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7544     done = hci_run_iso_fragments();
7545     if (done) return;
7546 #endif
7547 
7548 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7549     // send host num completed packets next as they don't require num_cmd_packets > 0
7550     if (!hci_can_send_comand_packet_transport()) return;
7551     if (hci_stack->host_completed_packets){
7552         hci_host_num_completed_packets();
7553         return;
7554     }
7555 #endif
7556 
7557     if (!hci_can_send_command_packet_now()) return;
7558 
7559     // global/non-connection oriented commands
7560 
7561 
7562 #ifdef ENABLE_CLASSIC
7563     // general gap classic
7564     done = hci_run_general_gap_classic();
7565     if (done) return;
7566 #endif
7567 
7568 #ifdef ENABLE_BLE
7569     // general gap le
7570     done = hci_run_general_gap_le();
7571     if (done) return;
7572 
7573 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7574     // ISO related tasks, e.g. BIG create/terminate/sync
7575     done = hci_run_iso_tasks();
7576     if (done) return;
7577 #endif
7578 #endif
7579 
7580     // send pending HCI commands
7581     hci_run_general_pending_commands();
7582 }
7583 
7584 #ifdef ENABLE_CLASSIC
7585 static void hci_set_sco_payload_length_for_flipped_packet_types(hci_connection_t * hci_connection, uint16_t flipped_packet_types){
7586     // bits 6-9 are 'don't use'
7587     uint16_t packet_types = flipped_packet_types ^ 0x03c0;
7588 
7589     // restrict packet types to local and remote supported
7590     packet_types &= hci_connection->remote_supported_sco_packets & hci_stack->usable_packet_types_sco;
7591     hci_connection->sco_payload_length = hci_sco_payload_length_for_packet_types(packet_types);
7592     log_info("Possible SCO packet types 0x%04x => payload length %u", packet_types, hci_connection->sco_payload_length);
7593 }
7594 #endif
7595 
7596 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
7597     // house-keeping
7598 
7599 #ifdef ENABLE_CLASSIC
7600     bd_addr_t addr;
7601     hci_connection_t * conn;
7602 #endif
7603 #ifdef ENABLE_LE_CENTRAL
7604     uint8_t initiator_filter_policy;
7605 #endif
7606 
7607     uint16_t opcode = little_endian_read_16(packet, 0);
7608     switch (opcode) {
7609         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
7610             hci_stack->loopback_mode = packet[3];
7611             break;
7612 
7613 #ifdef ENABLE_CLASSIC
7614         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7615             reverse_bd_addr(&packet[3], addr);
7616             log_info("Create_connection to %s", bd_addr_to_str(addr));
7617 
7618             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
7619             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
7620                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
7621                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
7622             }
7623 
7624             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7625             if (!conn) {
7626                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
7627                 if (!conn) {
7628                     // notify client that alloc failed
7629                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7630                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
7631                 }
7632                 conn->state = SEND_CREATE_CONNECTION;
7633             }
7634 
7635             log_info("conn state %u", conn->state);
7636             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7637             switch (conn->state) {
7638                 // if connection active exists
7639                 case OPEN:
7640                     // and OPEN, emit connection complete command
7641                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
7642                     // packet not sent to controller
7643                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7644                 case RECEIVED_DISCONNECTION_COMPLETE:
7645                     // create connection triggered in disconnect complete event, let's do it now
7646                     break;
7647                 case SEND_CREATE_CONNECTION:
7648 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
7649                     if (hci_classic_operation_active()){
7650                         return ERROR_CODE_SUCCESS;
7651                     }
7652 #endif
7653                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7654                     break;
7655                 default:
7656                     // otherwise, just ignore as it is already in the open process
7657                     // packet not sent to controller
7658                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7659             }
7660             conn->state = SENT_CREATE_CONNECTION;
7661 
7662             // track outgoing connection
7663             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
7664             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7665             break;
7666 
7667         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
7668             conn = hci_connection_for_handle(little_endian_read_16(packet, 3));
7669             if (conn == NULL) {
7670                 // neither SCO nor ACL connection for con handle
7671                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7672             } else {
7673                 uint16_t remote_supported_sco_packets;
7674                 switch (conn->address_type){
7675                     case BD_ADDR_TYPE_ACL:
7676                         // assert SCO connection does not exit
7677                         if (hci_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO) != NULL){
7678                             return ERROR_CODE_COMMAND_DISALLOWED;
7679                         }
7680                         // cache remote sco packet types
7681                         remote_supported_sco_packets = conn->remote_supported_sco_packets;
7682 
7683                         // allocate connection struct
7684                         conn = create_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO,
7685                                                                       HCI_ROLE_MASTER);
7686                         if (!conn) {
7687                             return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7688                         }
7689                         conn->remote_supported_sco_packets = remote_supported_sco_packets;
7690                         break;
7691                     case BD_ADDR_TYPE_SCO:
7692                         // update of existing SCO connection
7693                         break;
7694                     default:
7695                         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7696                 }
7697             }
7698 
7699             // conn refers to hci connection of type sco now
7700 
7701             conn->state = SENT_CREATE_CONNECTION;
7702 
7703             // track outgoing connection to handle command status with error
7704             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7705             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7706 
7707             // setup_synchronous_connection? Voice setting at offset 22
7708             // TODO: compare to current setting if sco connection already active
7709             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7710 
7711             // derive sco payload length from packet types
7712             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 18));
7713             break;
7714 
7715         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
7716             // get SCO connection
7717             reverse_bd_addr(&packet[3], addr);
7718             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
7719             if (conn == NULL){
7720                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7721             }
7722 
7723             conn->state = ACCEPTED_CONNECTION_REQUEST;
7724 
7725             // track outgoing connection to handle command status with error
7726             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7727             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7728 
7729             // accept_synchronous_connection? Voice setting at offset 18
7730             // TODO: compare to current setting if sco connection already active
7731             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7732 
7733             // derive sco payload length from packet types
7734             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 22));
7735             break;
7736 #endif
7737 
7738 #ifdef ENABLE_BLE
7739 #ifdef ENABLE_LE_CENTRAL
7740         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7741             // white list used?
7742             initiator_filter_policy = packet[7];
7743             switch (initiator_filter_policy) {
7744                 case 0:
7745                     // whitelist not used
7746                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7747                     break;
7748                 case 1:
7749                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7750                     break;
7751                 default:
7752                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7753                     break;
7754             }
7755             // track outgoing connection
7756             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer address type
7757             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
7758             break;
7759 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7760         case HCI_OPCODE_HCI_LE_EXTENDED_CREATE_CONNECTION:
7761             // white list used?
7762             initiator_filter_policy = packet[3];
7763             switch (initiator_filter_policy) {
7764                 case 0:
7765                     // whitelist not used
7766                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7767                     break;
7768                 case 1:
7769                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7770                     break;
7771                 default:
7772                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7773                     break;
7774             }
7775             // track outgoing connection
7776             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[5]; // peer address type
7777             reverse_bd_addr( &packet[6], hci_stack->outgoing_addr); // peer address
7778             break;
7779 #endif
7780         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
7781             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
7782             break;
7783 #endif
7784 #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
7785         case HCI_OPCODE_HCI_LE_CONNECTION_UPDATE:
7786         case HCI_OPCODE_HCI_LE_READ_REMOTE_USED_FEATURES:
7787         case HCI_OPCODE_HCI_LE_START_ENCRYPTION:
7788         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_REQUEST_REPLY:
7789         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_NEGATIVE_REPLY:
7790         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY:
7791         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY:
7792         case HCI_OPCODE_HCI_LE_SET_DATA_LENGTH:
7793         case HCI_OPCODE_HCI_LE_READ_PHY:
7794         case HCI_OPCODE_HCI_LE_SET_PHY:
7795             // conection handle is first command parameter
7796             hci_stack->hci_command_con_handle = little_endian_read_16(packet, 3);
7797             break;
7798 #endif
7799 #endif /* ENABLE_BLE */
7800         default:
7801             break;
7802     }
7803 
7804     hci_stack->num_cmd_packets--;
7805 
7806     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
7807     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7808     if (err != 0){
7809         return ERROR_CODE_HARDWARE_FAILURE;
7810     }
7811     return ERROR_CODE_SUCCESS;
7812 }
7813 
7814 // disconnect because of security block
7815 void hci_disconnect_security_block(hci_con_handle_t con_handle){
7816     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7817     if (!connection) return;
7818     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
7819 }
7820 
7821 
7822 // Configure Secure Simple Pairing
7823 
7824 #ifdef ENABLE_CLASSIC
7825 
7826 // enable will enable SSP during init
7827 void gap_ssp_set_enable(int enable){
7828     hci_stack->ssp_enable = enable;
7829 }
7830 
7831 static int hci_local_ssp_activated(void){
7832     return gap_ssp_supported() && hci_stack->ssp_enable;
7833 }
7834 
7835 // if set, BTstack will respond to io capability request using authentication requirement
7836 void gap_ssp_set_io_capability(int io_capability){
7837     hci_stack->ssp_io_capability = io_capability;
7838 }
7839 void gap_ssp_set_authentication_requirement(int authentication_requirement){
7840     hci_stack->ssp_authentication_requirement = authentication_requirement;
7841 }
7842 
7843 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
7844 void gap_ssp_set_auto_accept(int auto_accept){
7845     hci_stack->ssp_auto_accept = auto_accept;
7846 }
7847 
7848 void gap_secure_connections_enable(bool enable){
7849     hci_stack->secure_connections_enable = enable;
7850 }
7851 bool gap_secure_connections_active(void){
7852     return hci_stack->secure_connections_active;
7853 }
7854 
7855 #endif
7856 
7857 // va_list part of hci_send_cmd
7858 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
7859     if (!hci_can_send_command_packet_now()){
7860         log_error("hci_send_cmd called but cannot send packet now");
7861         return ERROR_CODE_COMMAND_DISALLOWED;
7862     }
7863 
7864     // for HCI INITIALIZATION
7865     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
7866     hci_stack->last_cmd_opcode = cmd->opcode;
7867 
7868     hci_reserve_packet_buffer();
7869     uint8_t * packet = hci_stack->hci_packet_buffer;
7870     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
7871     uint8_t status = hci_send_cmd_packet(packet, size);
7872 
7873     // release packet buffer on error or for synchronous transport implementations
7874     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7875         hci_release_packet_buffer();
7876         hci_emit_transport_packet_sent();
7877     }
7878 
7879     return status;
7880 }
7881 
7882 /**
7883  * pre: numcmds >= 0 - it's allowed to send a command to the controller
7884  */
7885 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
7886     va_list argptr;
7887     va_start(argptr, cmd);
7888     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
7889     va_end(argptr);
7890     return status;
7891 }
7892 
7893 // Create various non-HCI events.
7894 // TODO: generalize, use table similar to hci_create_command
7895 
7896 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
7897     // dump packet
7898     if (dump) {
7899         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
7900     }
7901 
7902     // dispatch to all event handlers
7903     btstack_linked_list_iterator_t it;
7904     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
7905     while (btstack_linked_list_iterator_has_next(&it)){
7906         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
7907         entry->callback(HCI_EVENT_PACKET, 0, event, size);
7908     }
7909 }
7910 
7911 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
7912     if (!hci_stack->acl_packet_handler) return;
7913     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
7914 }
7915 
7916 #ifdef ENABLE_CLASSIC
7917 static void hci_notify_if_sco_can_send_now(void){
7918     // notify SCO sender if waiting
7919     if (!hci_stack->sco_waiting_for_can_send_now) return;
7920     if (hci_can_send_sco_packet_now()){
7921         hci_stack->sco_waiting_for_can_send_now = 0;
7922         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
7923         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
7924         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
7925     }
7926 }
7927 
7928 // parsing end emitting has been merged to reduce code size
7929 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
7930     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
7931 
7932     uint8_t * eir_data;
7933     ad_context_t context;
7934     const uint8_t * name;
7935     uint8_t         name_len;
7936 
7937     if (size < 3) return;
7938 
7939     int event_type = hci_event_packet_get_type(packet);
7940     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
7941     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
7942 
7943     switch (event_type){
7944         case HCI_EVENT_INQUIRY_RESULT:
7945         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7946             if (size != (3 + (num_responses * 14))) return;
7947             break;
7948         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7949             if (size != 257) return;
7950             if (num_responses != 1) return;
7951             break;
7952         default:
7953             return;
7954     }
7955 
7956     // event[1] is set at the end
7957     int i;
7958     for (i=0; i<num_responses;i++){
7959         memset(event, 0, sizeof(event));
7960         event[0] = GAP_EVENT_INQUIRY_RESULT;
7961         uint8_t event_size = 27;    // if name is not set by EIR
7962 
7963         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
7964         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
7965         (void)memcpy(&event[9],
7966                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
7967                      3); // class of device
7968         (void)memcpy(&event[12],
7969                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
7970                      2); // clock offset
7971 
7972         switch (event_type){
7973             case HCI_EVENT_INQUIRY_RESULT:
7974                 // 14,15,16,17 = 0, size 18
7975                 break;
7976             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7977                 event[14] = 1;
7978                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7979                 // 16,17 = 0, size 18
7980                 break;
7981             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7982                 event[14] = 1;
7983                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7984                 // EIR packets only contain a single inquiry response
7985                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
7986                 name = NULL;
7987                 // Iterate over EIR data
7988                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
7989                     uint8_t data_type    = ad_iterator_get_data_type(&context);
7990                     uint8_t data_size    = ad_iterator_get_data_len(&context);
7991                     const uint8_t * data = ad_iterator_get_data(&context);
7992                     // Prefer Complete Local Name over Shortened Local Name
7993                     switch (data_type){
7994                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
7995                             if (name) continue;
7996                             /* fall through */
7997                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
7998                             name = data;
7999                             name_len = data_size;
8000                             break;
8001                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
8002                             if (data_size != 8) break;
8003                             event[16] = 1;
8004                             memcpy(&event[17], data, 8);
8005                             break;
8006                         default:
8007                             break;
8008                     }
8009                 }
8010                 if (name){
8011                     event[25] = 1;
8012                     // truncate name if needed
8013                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
8014                     event[26] = len;
8015                     (void)memcpy(&event[27], name, len);
8016                     event_size += len;
8017                 }
8018                 break;
8019             default:
8020                 return;
8021         }
8022         event[1] = event_size - 2;
8023         hci_emit_event(event, event_size, 1);
8024     }
8025 }
8026 #endif
8027 
8028 void hci_emit_state(void){
8029     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
8030     uint8_t event[3];
8031     event[0] = BTSTACK_EVENT_STATE;
8032     event[1] = sizeof(event) - 2u;
8033     event[2] = hci_stack->state;
8034     hci_emit_event(event, sizeof(event), 1);
8035 }
8036 
8037 #ifdef ENABLE_CLASSIC
8038 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
8039     uint8_t event[13];
8040     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
8041     event[1] = sizeof(event) - 2;
8042     event[2] = status;
8043     little_endian_store_16(event, 3, con_handle);
8044     reverse_bd_addr(address, &event[5]);
8045     event[11] = 1; // ACL connection
8046     event[12] = 0; // encryption disabled
8047     hci_emit_event(event, sizeof(event), 1);
8048 }
8049 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
8050     if (disable_l2cap_timeouts) return;
8051     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
8052     uint8_t event[4];
8053     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
8054     event[1] = sizeof(event) - 2;
8055     little_endian_store_16(event, 2, conn->con_handle);
8056     hci_emit_event(event, sizeof(event), 1);
8057 }
8058 #endif
8059 
8060 #ifdef ENABLE_BLE
8061 #ifdef ENABLE_LE_CENTRAL
8062 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){
8063     uint8_t hci_event[21];
8064     hci_event[0] = HCI_EVENT_LE_META;
8065     hci_event[1] = sizeof(hci_event) - 2u;
8066     hci_event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
8067     hci_event[3] = status;
8068     little_endian_store_16(hci_event, 4, con_handle);
8069     hci_event[6] = 0; // TODO: role
8070     hci_event[7] = address_type;
8071     reverse_bd_addr(address, &hci_event[8]);
8072     little_endian_store_16(hci_event, 14, 0); // interval
8073     little_endian_store_16(hci_event, 16, 0); // latency
8074     little_endian_store_16(hci_event, 18, 0); // supervision timeout
8075     hci_event[20] = 0; // master clock accuracy
8076     hci_emit_event(hci_event, sizeof(hci_event), 1);
8077     // emit GAP event, too
8078     uint8_t gap_event[36];
8079     hci_create_gap_connection_complete_event(hci_event, gap_event);
8080     hci_emit_event(gap_event, sizeof(gap_event), 1);
8081 }
8082 #endif
8083 #endif
8084 
8085 static void hci_emit_transport_packet_sent(void){
8086     // notify upper stack that it might be possible to send again
8087     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
8088     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
8089 }
8090 
8091 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
8092     uint8_t event[6];
8093     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
8094     event[1] = sizeof(event) - 2u;
8095     event[2] = 0; // status = OK
8096     little_endian_store_16(event, 3, con_handle);
8097     event[5] = reason;
8098     hci_emit_event(event, sizeof(event), 1);
8099 }
8100 
8101 static void hci_emit_nr_connections_changed(void){
8102     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
8103     uint8_t event[3];
8104     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
8105     event[1] = sizeof(event) - 2u;
8106     event[2] = nr_hci_connections();
8107     hci_emit_event(event, sizeof(event), 1);
8108 }
8109 
8110 static void hci_emit_hci_open_failed(void){
8111     log_info("BTSTACK_EVENT_POWERON_FAILED");
8112     uint8_t event[2];
8113     event[0] = BTSTACK_EVENT_POWERON_FAILED;
8114     event[1] = sizeof(event) - 2u;
8115     hci_emit_event(event, sizeof(event), 1);
8116 }
8117 
8118 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
8119     log_info("hci_emit_dedicated_bonding_result %u ", status);
8120     uint8_t event[9];
8121     int pos = 0;
8122     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
8123     event[pos++] = sizeof(event) - 2u;
8124     event[pos++] = status;
8125     reverse_bd_addr(address, &event[pos]);
8126     hci_emit_event(event, sizeof(event), 1);
8127 }
8128 
8129 
8130 #ifdef ENABLE_CLASSIC
8131 
8132 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
8133     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
8134     uint8_t event[5];
8135     int pos = 0;
8136     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
8137     event[pos++] = sizeof(event) - 2;
8138     little_endian_store_16(event, 2, con_handle);
8139     pos += 2;
8140     event[pos++] = level;
8141     hci_emit_event(event, sizeof(event), 1);
8142 }
8143 
8144 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
8145     if (!connection) return LEVEL_0;
8146     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
8147     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
8148     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
8149     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
8150     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
8151     // LEVEL 4 always requires 128 bit encrytion key size
8152     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
8153         security_level = LEVEL_3;
8154     }
8155     return security_level;
8156 }
8157 
8158 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
8159     uint8_t event[4];
8160     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
8161     event[1] = sizeof(event) - 2;
8162     event[2] = discoverable;
8163     event[3] = connectable;
8164     hci_emit_event(event, sizeof(event), 1);
8165 }
8166 
8167 // query if remote side supports eSCO
8168 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
8169     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8170     if (!connection) return false;
8171     return (connection->remote_supported_features[0] & 1) != 0;
8172 }
8173 
8174 uint16_t hci_remote_sco_packet_types(hci_con_handle_t con_handle){
8175     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8176     if (!connection) return 0;
8177     return connection->remote_supported_sco_packets;
8178 }
8179 
8180 static bool hci_ssp_supported(hci_connection_t * connection){
8181     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
8182     return (connection->bonding_flags & mask) == mask;
8183 }
8184 
8185 // query if remote side supports SSP
8186 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
8187     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8188     if (!connection) return false;
8189     return hci_ssp_supported(connection) ? 1 : 0;
8190 }
8191 
8192 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
8193     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
8194 }
8195 
8196 /**
8197  * Check if remote supported features query has completed
8198  */
8199 bool hci_remote_features_available(hci_con_handle_t handle){
8200     hci_connection_t * connection = hci_connection_for_handle(handle);
8201     if (!connection) return false;
8202     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
8203 }
8204 
8205 /**
8206  * Trigger remote supported features query
8207  */
8208 
8209 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
8210     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
8211         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
8212     }
8213 }
8214 
8215 void hci_remote_features_query(hci_con_handle_t con_handle){
8216     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8217     if (!connection) return;
8218     hci_trigger_remote_features_for_connection(connection);
8219     hci_run();
8220 }
8221 
8222 // GAP API
8223 /**
8224  * @bbrief enable/disable bonding. default is enabled
8225  * @praram enabled
8226  */
8227 void gap_set_bondable_mode(int enable){
8228     hci_stack->bondable = enable ? 1 : 0;
8229 }
8230 /**
8231  * @brief Get bondable mode.
8232  * @return 1 if bondable
8233  */
8234 int gap_get_bondable_mode(void){
8235     return hci_stack->bondable;
8236 }
8237 
8238 /**
8239  * @brief map link keys to security levels
8240  */
8241 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
8242     switch (link_key_type){
8243         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8244             return LEVEL_4;
8245         case COMBINATION_KEY:
8246         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
8247             return LEVEL_3;
8248         default:
8249             return LEVEL_2;
8250     }
8251 }
8252 
8253 /**
8254  * @brief map link keys to secure connection yes/no
8255  */
8256 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
8257     switch (link_key_type){
8258         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8259         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8260             return true;
8261         default:
8262             return false;
8263     }
8264 }
8265 
8266 /**
8267  * @brief map link keys to authenticated
8268  */
8269 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
8270     switch (link_key_type){
8271         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8272         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
8273             return true;
8274         default:
8275             return false;
8276     }
8277 }
8278 
8279 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
8280     log_info("gap_mitm_protection_required_for_security_level %u", level);
8281     return level > LEVEL_2;
8282 }
8283 
8284 /**
8285  * @brief get current security level
8286  */
8287 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
8288     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8289     if (!connection) return LEVEL_0;
8290     return gap_security_level_for_connection(connection);
8291 }
8292 
8293 /**
8294  * @brief request connection to device to
8295  * @result GAP_AUTHENTICATION_RESULT
8296  */
8297 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
8298     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8299     if (!connection){
8300         hci_emit_security_level(con_handle, LEVEL_0);
8301         return;
8302     }
8303 
8304     btstack_assert(hci_is_le_connection(connection) == false);
8305 
8306     // 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)
8307     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
8308     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
8309         requested_level = LEVEL_4;
8310     }
8311 
8312     gap_security_level_t current_level = gap_security_level(con_handle);
8313     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
8314         requested_level, connection->requested_security_level, current_level);
8315 
8316     // authentication active if authentication request was sent or planned level > 0
8317     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
8318     if (authentication_active){
8319         // authentication already active
8320         if (connection->requested_security_level < requested_level){
8321             // increase requested level as new level is higher
8322             // TODO: handle re-authentication when done
8323             connection->requested_security_level = requested_level;
8324         }
8325     } else {
8326         // no request active, notify if security sufficient
8327         if (requested_level <= current_level){
8328             hci_emit_security_level(con_handle, current_level);
8329             return;
8330         }
8331 
8332         // store request
8333         connection->requested_security_level = requested_level;
8334 
8335         // start to authenticate connection
8336         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
8337 
8338         // request remote features if not already active, also trigger hci_run
8339         hci_remote_features_query(con_handle);
8340     }
8341 }
8342 
8343 /**
8344  * @brief start dedicated bonding with device. disconnect after bonding
8345  * @param device
8346  * @param request MITM protection
8347  * @result GAP_DEDICATED_BONDING_COMPLETE
8348  */
8349 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
8350 
8351     // create connection state machine
8352     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
8353 
8354     if (!connection){
8355         return BTSTACK_MEMORY_ALLOC_FAILED;
8356     }
8357 
8358     // delete link key
8359     gap_drop_link_key_for_bd_addr(device);
8360 
8361     // configure LEVEL_2/3, dedicated bonding
8362     connection->state = SEND_CREATE_CONNECTION;
8363     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
8364     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
8365     connection->bonding_flags = BONDING_DEDICATED;
8366 
8367     hci_run();
8368 
8369     return 0;
8370 }
8371 
8372 uint8_t hci_dedicated_bonding_defer_disconnect(hci_con_handle_t con_handle, bool defer){
8373     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8374     if (connection == NULL){
8375         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8376     }
8377     if (defer){
8378         connection->bonding_flags |= BONDING_DEDICATED_DEFER_DISCONNECT;
8379     } else {
8380         connection->bonding_flags &= ~BONDING_DEDICATED_DEFER_DISCONNECT;
8381         // trigger disconnect
8382         hci_run();
8383     }
8384     return ERROR_CODE_SUCCESS;
8385 }
8386 
8387 void gap_set_local_name(const char * local_name){
8388     hci_stack->local_name = local_name;
8389     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
8390     // also update EIR if not set by user
8391     if (hci_stack->eir_data == NULL){
8392         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
8393     }
8394     hci_run();
8395 }
8396 #endif
8397 
8398 
8399 #ifdef ENABLE_BLE
8400 
8401 #ifdef ENABLE_LE_CENTRAL
8402 void gap_start_scan(void){
8403     hci_stack->le_scanning_enabled = true;
8404     hci_run();
8405 }
8406 
8407 void gap_stop_scan(void){
8408     hci_stack->le_scanning_enabled = false;
8409     hci_run();
8410 }
8411 
8412 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
8413     hci_stack->le_scan_type          = scan_type;
8414     hci_stack->le_scan_filter_policy = scanning_filter_policy;
8415     hci_stack->le_scan_interval      = scan_interval;
8416     hci_stack->le_scan_window        = scan_window;
8417     hci_stack->le_scanning_param_update = true;
8418     hci_run();
8419 }
8420 
8421 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
8422     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
8423 }
8424 
8425 void gap_set_scan_duplicate_filter(bool enabled){
8426     hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0;
8427 }
8428 
8429 void gap_set_scan_phys(uint8_t phys){
8430     // LE Coded and LE 1M PHY
8431     hci_stack->le_scan_phys = phys & 0x05;
8432 }
8433 
8434 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type) {
8435     // disallow le connection if outgoing already active
8436     if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8437         log_error("le connect already active");
8438         return ERROR_CODE_COMMAND_DISALLOWED;
8439     }
8440 
8441     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
8442     if (conn == NULL) {
8443         conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_MASTER);
8444         if (conn == false){
8445             // alloc failed
8446             log_info("gap_connect: failed to alloc hci_connection_t");
8447             return BTSTACK_MEMORY_ALLOC_FAILED;
8448         }
8449     } else {
8450         switch (conn->state) {
8451             case RECEIVED_DISCONNECTION_COMPLETE:
8452                 // connection was just disconnected, reset state and allow re-connect
8453                 conn->role = HCI_ROLE_MASTER;
8454                 break;
8455             default:
8456                 return ERROR_CODE_COMMAND_DISALLOWED;
8457         }
8458     }
8459 
8460     // set le connecting state
8461     if (hci_is_le_connection_type(addr_type)){
8462         hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
8463     }
8464 
8465     // trigger connect
8466     log_info("gap_connect: send create connection next");
8467     conn->state = SEND_CREATE_CONNECTION;
8468     hci_run();
8469     return ERROR_CODE_SUCCESS;
8470 }
8471 
8472 // @assumption: only a single outgoing LE Connection exists
8473 static hci_connection_t * gap_get_outgoing_le_connection(void){
8474     btstack_linked_item_t *it;
8475     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
8476         hci_connection_t * conn = (hci_connection_t *) it;
8477         if (hci_is_le_connection(conn)){
8478             switch (conn->state){
8479                 case SEND_CREATE_CONNECTION:
8480                 case SENT_CREATE_CONNECTION:
8481                     return conn;
8482                 default:
8483                     break;
8484             };
8485         }
8486     }
8487     return NULL;
8488 }
8489 
8490 uint8_t gap_connect_cancel(void){
8491     hci_connection_t * conn;
8492     switch (hci_stack->le_connecting_request){
8493         case LE_CONNECTING_IDLE:
8494             break;
8495         case LE_CONNECTING_WHITELIST:
8496             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8497             hci_run();
8498             break;
8499         case LE_CONNECTING_DIRECT:
8500             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8501             conn = gap_get_outgoing_le_connection();
8502             if (conn == NULL){
8503                 hci_run();
8504             } else {
8505                 switch (conn->state){
8506                     case SEND_CREATE_CONNECTION:
8507                         // skip sending create connection and emit event instead
8508                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
8509                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
8510                         btstack_memory_hci_connection_free( conn );
8511                         break;
8512                     case SENT_CREATE_CONNECTION:
8513                         // let hci_run_general_gap_le cancel outgoing connection
8514                         hci_run();
8515                         break;
8516                     default:
8517                         break;
8518                 }
8519             }
8520             break;
8521         default:
8522             btstack_unreachable();
8523             break;
8524     }
8525     return ERROR_CODE_SUCCESS;
8526 }
8527 
8528 /**
8529  * @brief Set connection parameters for outgoing connections
8530  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
8531  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
8532  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
8533  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
8534  * @param conn_latency, default: 4
8535  * @param supervision_timeout (unit: 10ms), default: 720 ms
8536  * @param min_ce_length (unit: 0.625ms), default: 10 ms
8537  * @param max_ce_length (unit: 0.625ms), default: 30 ms
8538  */
8539 
8540 void gap_set_connection_phys(uint8_t phys){
8541     // LE Coded, LE 1M, LE 2M PHY
8542     hci_stack->le_connection_phys = phys & 7;
8543 }
8544 
8545 #endif
8546 
8547 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
8548                                    uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
8549                                    uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
8550     hci_stack->le_connection_scan_interval = conn_scan_interval;
8551     hci_stack->le_connection_scan_window = conn_scan_window;
8552     hci_stack->le_connection_interval_min = conn_interval_min;
8553     hci_stack->le_connection_interval_max = conn_interval_max;
8554     hci_stack->le_connection_latency = conn_latency;
8555     hci_stack->le_supervision_timeout = supervision_timeout;
8556     hci_stack->le_minimum_ce_length = min_ce_length;
8557     hci_stack->le_maximum_ce_length = max_ce_length;
8558 }
8559 
8560 /**
8561  * @brief Updates the connection parameters for a given LE connection
8562  * @param handle
8563  * @param conn_interval_min (unit: 1.25ms)
8564  * @param conn_interval_max (unit: 1.25ms)
8565  * @param conn_latency
8566  * @param supervision_timeout (unit: 10ms)
8567  * @return 0 if ok
8568  */
8569 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8570     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8571     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8572     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8573     connection->le_conn_interval_min = conn_interval_min;
8574     connection->le_conn_interval_max = conn_interval_max;
8575     connection->le_conn_latency = conn_latency;
8576     connection->le_supervision_timeout = supervision_timeout;
8577     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
8578     hci_run();
8579     return 0;
8580 }
8581 
8582 /**
8583  * @brief Request an update of the connection parameter for a given LE connection
8584  * @param handle
8585  * @param conn_interval_min (unit: 1.25ms)
8586  * @param conn_interval_max (unit: 1.25ms)
8587  * @param conn_latency
8588  * @param supervision_timeout (unit: 10ms)
8589  * @return 0 if ok
8590  */
8591 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8592     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8593     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8594     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8595     connection->le_conn_interval_min = conn_interval_min;
8596     connection->le_conn_interval_max = conn_interval_max;
8597     connection->le_conn_latency = conn_latency;
8598     connection->le_supervision_timeout = supervision_timeout;
8599     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
8600     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
8601     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
8602     return 0;
8603 }
8604 
8605 #ifdef ENABLE_LE_PERIPHERAL
8606 
8607 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8608 static void hci_assert_advertisement_set_0_ready(void){
8609     // force advertising set creation for legacy LE Advertising
8610     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) == 0){
8611         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8612     }
8613 }
8614 #endif
8615 
8616 /**
8617  * @brief Set Advertisement Data
8618  * @param advertising_data_length
8619  * @param advertising_data (max 31 octets)
8620  * @note data is not copied, pointer has to stay valid
8621  */
8622 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
8623     hci_stack->le_advertisements_data_len = advertising_data_length;
8624     hci_stack->le_advertisements_data = advertising_data;
8625     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8626 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8627     hci_assert_advertisement_set_0_ready();
8628 #endif
8629     hci_run();
8630 }
8631 
8632 /**
8633  * @brief Set Scan Response Data
8634  * @param advertising_data_length
8635  * @param advertising_data (max 31 octets)
8636  * @note data is not copied, pointer has to stay valid
8637  */
8638 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
8639     hci_stack->le_scan_response_data_len = scan_response_data_length;
8640     hci_stack->le_scan_response_data = scan_response_data;
8641     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8642 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8643     hci_assert_advertisement_set_0_ready();
8644 #endif
8645     hci_run();
8646 }
8647 
8648 /**
8649  * @brief Set Advertisement Parameters
8650  * @param adv_int_min
8651  * @param adv_int_max
8652  * @param adv_type
8653  * @param direct_address_type
8654  * @param direct_address
8655  * @param channel_map
8656  * @param filter_policy
8657  *
8658  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
8659  */
8660  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
8661     uint8_t direct_address_typ, bd_addr_t direct_address,
8662     uint8_t channel_map, uint8_t filter_policy) {
8663 
8664     hci_stack->le_advertisements_interval_min = adv_int_min;
8665     hci_stack->le_advertisements_interval_max = adv_int_max;
8666     hci_stack->le_advertisements_type = adv_type;
8667     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
8668     hci_stack->le_advertisements_channel_map = channel_map;
8669     hci_stack->le_advertisements_filter_policy = filter_policy;
8670     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
8671                  6);
8672 
8673     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8674     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
8675     hci_run();
8676  }
8677 
8678 /**
8679  * @brief Enable/Disable Advertisements
8680  * @param enabled
8681  */
8682 void gap_advertisements_enable(int enabled){
8683     if (enabled == 0){
8684         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8685     } else {
8686         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
8687     }
8688     hci_update_advertisements_enabled_for_current_roles();
8689     hci_run();
8690 }
8691 
8692 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8693 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
8694     btstack_linked_list_iterator_t it;
8695     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
8696     while (btstack_linked_list_iterator_has_next(&it)){
8697         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
8698         if ( item->advertising_handle == advertising_handle ) {
8699             return item;
8700         }
8701     }
8702     return NULL;
8703 }
8704 
8705 uint8_t gap_extended_advertising_set_resolvable_private_address_update(uint16_t update_s){
8706     hci_stack->le_resolvable_private_address_update_s = update_s;
8707     hci_run();
8708     return ERROR_CODE_SUCCESS;
8709 }
8710 
8711 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
8712     // find free advertisement handle
8713     uint8_t advertisement_handle;
8714     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
8715         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
8716     }
8717     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8718     // clear
8719     memset(storage, 0, sizeof(le_advertising_set_t));
8720     // copy params
8721     storage->advertising_handle = advertisement_handle;
8722     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8723     // add to list
8724     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
8725     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
8726     *out_advertising_handle = advertisement_handle;
8727     // set tasks and start
8728     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8729     hci_run();
8730     return ERROR_CODE_SUCCESS;
8731 }
8732 
8733 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
8734     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8735     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8736     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8737     // set tasks and start
8738     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8739     hci_run();
8740     return ERROR_CODE_SUCCESS;
8741 }
8742 
8743 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
8744     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8745     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8746     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
8747     return ERROR_CODE_SUCCESS;
8748 }
8749 
8750 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
8751     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8752     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8753     memcpy(advertising_set->random_address, random_address, 6);
8754     // set tasks and start
8755     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8756     hci_run();
8757     return ERROR_CODE_SUCCESS;
8758 }
8759 
8760 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
8761     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8762     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8763     advertising_set->adv_data = advertising_data;
8764     advertising_set->adv_data_len = advertising_data_length;
8765     // set tasks and start
8766     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8767     hci_run();
8768     return ERROR_CODE_SUCCESS;
8769 }
8770 
8771 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){
8772     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8773     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8774     advertising_set->scan_data = scan_response_data;
8775     advertising_set->scan_data_len = scan_response_data_length;
8776     // set tasks and start
8777     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8778     hci_run();
8779     return ERROR_CODE_SUCCESS;
8780 }
8781 
8782 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
8783     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8784     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8785     advertising_set->enable_timeout = timeout;
8786     advertising_set->enable_max_scan_events = num_extended_advertising_events;
8787     // set tasks and start
8788     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
8789     hci_run();
8790     return ERROR_CODE_SUCCESS;
8791 }
8792 
8793 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
8794     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8795     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8796     // set tasks and start
8797     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8798     hci_run();
8799     return ERROR_CODE_SUCCESS;
8800 }
8801 
8802 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8803     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8804     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8805     // set tasks and start
8806     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8807     hci_run();
8808     return ERROR_CODE_SUCCESS;
8809 }
8810 
8811 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8812 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8813     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8814     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8815     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8816     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8817     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8818     // set tasks and start
8819     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8820     hci_run();
8821     return ERROR_CODE_SUCCESS;
8822 }
8823 
8824 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8825     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8826     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8827     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8828     return ERROR_CODE_SUCCESS;
8829 }
8830 
8831 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8832     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8833     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8834     advertising_set->periodic_data = periodic_data;
8835     advertising_set->periodic_data_len = periodic_data_length;
8836     // set tasks and start
8837     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8838     hci_run();
8839     return ERROR_CODE_SUCCESS;
8840 }
8841 
8842 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
8843     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8844     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8845     // set tasks and start
8846     advertising_set->periodic_include_adi = include_adi;
8847     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8848     hci_run();
8849     return ERROR_CODE_SUCCESS;
8850 }
8851 
8852 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
8853     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8854     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8855     // set tasks and start
8856     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8857     hci_run();
8858     return ERROR_CODE_SUCCESS;
8859 }
8860 
8861 uint8_t gap_periodic_advertising_sync_transfer_set_default_parameters(uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type){
8862     hci_stack->le_past_mode = mode;
8863     hci_stack->le_past_skip = skip;
8864     hci_stack->le_past_sync_timeout = sync_timeout;
8865     hci_stack->le_past_cte_type = cte_type;
8866     hci_stack->le_past_set_default_params = true;
8867     hci_run();
8868     return ERROR_CODE_SUCCESS;
8869 }
8870 
8871 uint8_t gap_periodic_advertising_sync_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, hci_con_handle_t sync_handle){
8872     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8873     if (hci_connection == NULL){
8874         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8875     }
8876     hci_connection->le_past_sync_handle = sync_handle;
8877     hci_connection->le_past_service_data = service_data;
8878     hci_run();
8879     return ERROR_CODE_SUCCESS;
8880 }
8881 
8882 uint8_t gap_periodic_advertising_set_info_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, uint8_t advertising_handle){
8883     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8884     if (hci_connection == NULL){
8885         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8886     }
8887     hci_connection->le_past_advertising_handle = advertising_handle;
8888     hci_connection->le_past_service_data = service_data;
8889     hci_run();
8890     return ERROR_CODE_SUCCESS;
8891 }
8892 
8893 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
8894 
8895 #endif
8896 
8897 #endif
8898 
8899 void hci_le_set_own_address_type(uint8_t own_address_type){
8900     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
8901     if (own_address_type == hci_stack->le_own_addr_type) return;
8902     hci_stack->le_own_addr_type = own_address_type;
8903 
8904 #ifdef ENABLE_LE_PERIPHERAL
8905     // update advertisement parameters, too
8906     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8907     hci_run();
8908 #endif
8909 #ifdef ENABLE_LE_CENTRAL
8910     // note: we don't update scan parameters or modify ongoing connection attempts
8911 #endif
8912 }
8913 
8914 void hci_le_random_address_set(const bd_addr_t random_address){
8915     log_info("gap_privacy: hci_le_random_address_set %s", bd_addr_to_str(random_address));
8916     memcpy(hci_stack->le_random_address, random_address, 6);
8917     hci_stack->le_random_address_set = true;
8918     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
8919 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8920     if (hci_le_extended_advertising_supported()){
8921         hci_assert_advertisement_set_0_ready();
8922         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
8923     }
8924 #endif
8925     hci_run();
8926 }
8927 
8928 #endif
8929 
8930 uint8_t gap_disconnect(hci_con_handle_t handle){
8931     hci_connection_t * conn = hci_connection_for_handle(handle);
8932     if (!conn){
8933         hci_emit_disconnection_complete(handle, 0);
8934         return 0;
8935     }
8936     // ignore if already disconnected
8937     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
8938         return 0;
8939     }
8940     conn->state = SEND_DISCONNECT;
8941     hci_run();
8942     return 0;
8943 }
8944 
8945 int gap_read_rssi(hci_con_handle_t con_handle){
8946     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8947     if (hci_connection == NULL) return 0;
8948     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
8949     hci_run();
8950     return 1;
8951 }
8952 
8953 /**
8954  * @brief Get connection type
8955  * @param con_handle
8956  * @result connection_type
8957  */
8958 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
8959     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8960     if (!conn) return GAP_CONNECTION_INVALID;
8961     switch (conn->address_type){
8962         case BD_ADDR_TYPE_LE_PUBLIC:
8963         case BD_ADDR_TYPE_LE_RANDOM:
8964         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
8965         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
8966             return GAP_CONNECTION_LE;
8967         case BD_ADDR_TYPE_SCO:
8968             return GAP_CONNECTION_SCO;
8969         case BD_ADDR_TYPE_ACL:
8970             return GAP_CONNECTION_ACL;
8971         default:
8972             return GAP_CONNECTION_INVALID;
8973     }
8974 }
8975 
8976 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
8977     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8978     if (!conn) return HCI_ROLE_INVALID;
8979     return (hci_role_t) conn->role;
8980 }
8981 
8982 
8983 #ifdef ENABLE_CLASSIC
8984 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
8985     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8986     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8987     conn->request_role = role;
8988     hci_run();
8989     return ERROR_CODE_SUCCESS;
8990 }
8991 #endif
8992 
8993 #ifdef ENABLE_BLE
8994 
8995 uint8_t gap_le_set_phy(hci_con_handle_t con_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint16_t phy_options){
8996     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8997     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8998 
8999     conn->le_phy_update_all_phys    = all_phys;
9000     conn->le_phy_update_tx_phys     = tx_phys;
9001     conn->le_phy_update_rx_phys     = rx_phys;
9002     conn->le_phy_update_phy_options = (uint8_t) phy_options;
9003 
9004     hci_run();
9005 
9006     return 0;
9007 }
9008 
9009 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9010 
9011 #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_WHITELIST_ENTRIES) || (MAX_NR_WHITELIST_ENTRIES == 0))
9012     // incorrect configuration:
9013     // - as MAX_NR_WHITELIST_ENTRIES is not defined or zero this function always fails
9014     // - please set MAX_NR_WHITELIST_ENTRIES in btstack_config.h
9015     btstack_assert(false);
9016 #endif
9017 
9018     // check if already in list
9019     btstack_linked_list_iterator_t it;
9020     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9021     while (btstack_linked_list_iterator_has_next(&it)) {
9022         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
9023         if (entry->address_type != address_type) {
9024             continue;
9025         }
9026         if (memcmp(entry->address, address, 6) != 0) {
9027             continue;
9028         }
9029 
9030         // if already on controller:
9031         if ((entry->state & LE_WHITELIST_ON_CONTROLLER) != 0){
9032             if ((entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER) != 0){
9033                 // drop remove request
9034                 entry->state = LE_WHITELIST_ON_CONTROLLER;
9035                 return ERROR_CODE_SUCCESS;
9036             } else {
9037                 // disallow as already on controller
9038                 return ERROR_CODE_COMMAND_DISALLOWED;
9039             }
9040         }
9041 
9042         // assume scheduled to add
9043 		return ERROR_CODE_COMMAND_DISALLOWED;
9044     }
9045 
9046     // alloc and add to list
9047     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
9048     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9049     entry->address_type = address_type;
9050     (void)memcpy(entry->address, address, 6);
9051     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
9052     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
9053     return ERROR_CODE_SUCCESS;
9054 }
9055 
9056 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9057     btstack_linked_list_iterator_t it;
9058     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9059     while (btstack_linked_list_iterator_has_next(&it)){
9060         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
9061         if (entry->address_type != address_type) {
9062             continue;
9063         }
9064         if (memcmp(entry->address, address, 6) != 0) {
9065             continue;
9066         }
9067         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9068             // remove from controller if already present
9069             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9070         }  else {
9071             // directly remove entry from whitelist
9072             btstack_linked_list_iterator_remove(&it);
9073             btstack_memory_whitelist_entry_free(entry);
9074         }
9075         return ERROR_CODE_SUCCESS;
9076     }
9077     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9078 }
9079 
9080 static void hci_whitelist_clear(void){
9081     btstack_linked_list_iterator_t it;
9082     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9083     while (btstack_linked_list_iterator_has_next(&it)){
9084         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
9085         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9086             // remove from controller if already present
9087             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9088             continue;
9089         }
9090         // directly remove entry from whitelist
9091         btstack_linked_list_iterator_remove(&it);
9092         btstack_memory_whitelist_entry_free(entry);
9093     }
9094 }
9095 
9096 /**
9097  * @brief Clear Whitelist
9098  * @return 0 if ok
9099  */
9100 uint8_t gap_whitelist_clear(void){
9101     hci_whitelist_clear();
9102     hci_run();
9103     return ERROR_CODE_SUCCESS;
9104 }
9105 
9106 /**
9107  * @brief Add Device to Whitelist
9108  * @param address_typ
9109  * @param address
9110  * @return 0 if ok
9111  */
9112 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9113     uint8_t status = hci_whitelist_add(address_type, address);
9114     if (status){
9115         return status;
9116     }
9117     hci_run();
9118     return ERROR_CODE_SUCCESS;
9119 }
9120 
9121 /**
9122  * @brief Remove Device from Whitelist
9123  * @param address_typ
9124  * @param address
9125  * @return 0 if ok
9126  */
9127 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9128     uint8_t status = hci_whitelist_remove(address_type, address);
9129     if (status){
9130         return status;
9131     }
9132     hci_run();
9133     return ERROR_CODE_SUCCESS;
9134 }
9135 
9136 #ifdef ENABLE_LE_CENTRAL
9137 /**
9138  * @brief Connect with Whitelist
9139  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
9140  * @return - if ok
9141  */
9142 uint8_t gap_connect_with_whitelist(void){
9143     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
9144         return ERROR_CODE_COMMAND_DISALLOWED;
9145     }
9146     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
9147     hci_run();
9148     return ERROR_CODE_SUCCESS;
9149 }
9150 
9151 /**
9152  * @brief Auto Connection Establishment - Start Connecting to device
9153  * @param address_typ
9154  * @param address
9155  * @return 0 if ok
9156  */
9157 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
9158     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
9159         return ERROR_CODE_COMMAND_DISALLOWED;
9160     }
9161 
9162     uint8_t status = hci_whitelist_add(address_type, address);
9163     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
9164         return status;
9165     }
9166 
9167     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
9168 
9169     hci_run();
9170     return ERROR_CODE_SUCCESS;
9171 }
9172 
9173 /**
9174  * @brief Auto Connection Establishment - Stop Connecting to device
9175  * @param address_typ
9176  * @param address
9177  * @return 0 if ok
9178  */
9179 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
9180     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
9181         return ERROR_CODE_COMMAND_DISALLOWED;
9182     }
9183 
9184     hci_whitelist_remove(address_type, address);
9185     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
9186         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
9187     }
9188     hci_run();
9189     return 0;
9190 }
9191 
9192 /**
9193  * @brief Auto Connection Establishment - Stop everything
9194  * @note  Convenience function to stop all active auto connection attempts
9195  */
9196 uint8_t gap_auto_connection_stop_all(void){
9197     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
9198         return ERROR_CODE_COMMAND_DISALLOWED;
9199     }
9200     hci_whitelist_clear();
9201     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
9202     hci_run();
9203     return ERROR_CODE_SUCCESS;
9204 }
9205 
9206 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
9207     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9208     if (!conn) return 0;
9209     return conn->le_connection_interval;
9210 }
9211 #endif
9212 #endif
9213 
9214 #ifdef ENABLE_CLASSIC
9215 /**
9216  * @brief Set Extended Inquiry Response data
9217  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
9218  * @note has to be done before stack starts up
9219  */
9220 void gap_set_extended_inquiry_response(const uint8_t * data){
9221     hci_stack->eir_data = data;
9222     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
9223     hci_run();
9224 }
9225 
9226 /**
9227  * @brief Start GAP Classic Inquiry
9228  * @param duration in 1.28s units
9229  * @return 0 if ok
9230  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
9231  */
9232 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
9233     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
9234     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9235     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
9236         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9237     }
9238     hci_stack->inquiry_state = duration_in_1280ms_units;
9239     hci_stack->inquiry_max_period_length = 0;
9240     hci_stack->inquiry_min_period_length = 0;
9241     hci_run();
9242     return 0;
9243 }
9244 
9245 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
9246     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
9247     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
9248     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9249     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9250     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
9251     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
9252 
9253     hci_stack->inquiry_state = duration;
9254     hci_stack->inquiry_max_period_length = max_period_length;
9255     hci_stack->inquiry_min_period_length = min_period_length;
9256     hci_run();
9257     return 0;
9258 }
9259 
9260 /**
9261  * @brief Stop GAP Classic Inquiry
9262  * @return 0 if ok
9263  */
9264 int gap_inquiry_stop(void){
9265     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
9266         // emit inquiry complete event, before it even started
9267         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
9268         hci_emit_event(event, sizeof(event), 1);
9269         return 0;
9270     }
9271     switch (hci_stack->inquiry_state){
9272         case GAP_INQUIRY_STATE_ACTIVE:
9273             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
9274             hci_run();
9275             return ERROR_CODE_SUCCESS;
9276         case GAP_INQUIRY_STATE_PERIODIC:
9277             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
9278             hci_run();
9279             return ERROR_CODE_SUCCESS;
9280         default:
9281             return ERROR_CODE_COMMAND_DISALLOWED;
9282     }
9283 }
9284 
9285 void gap_inquiry_set_lap(uint32_t lap){
9286     hci_stack->inquiry_lap = lap;
9287 }
9288 
9289 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
9290     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
9291     hci_stack->inquiry_scan_window   = inquiry_scan_window;
9292     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
9293     hci_run();
9294 }
9295 
9296 void gap_inquiry_set_transmit_power_level(int8_t tx_power)
9297 {
9298     hci_stack->inquiry_tx_power_level = tx_power;
9299     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
9300     hci_run();
9301 }
9302 
9303 
9304 /**
9305  * @brief Remote Name Request
9306  * @param addr
9307  * @param page_scan_repetition_mode
9308  * @param clock_offset only used when bit 15 is set
9309  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
9310  */
9311 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
9312     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9313     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
9314     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
9315     hci_stack->remote_name_clock_offset = clock_offset;
9316     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
9317     hci_run();
9318     return 0;
9319 }
9320 
9321 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
9322     hci_stack->gap_pairing_state = state;
9323     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
9324     hci_run();
9325     return 0;
9326 }
9327 
9328 /**
9329  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
9330  * @param addr
9331  * @param pin_data
9332  * @param pin_len
9333  * @return 0 if ok
9334  */
9335 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
9336     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9337     if (pin_len > PIN_CODE_LEN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9338     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
9339     hci_stack->gap_pairing_pin_len = pin_len;
9340     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
9341 }
9342 
9343 /**
9344  * @brief Legacy Pairing Pin Code Response
9345  * @param addr
9346  * @param pin
9347  * @return 0 if ok
9348  */
9349 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
9350     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
9351 }
9352 
9353 /**
9354  * @brief Abort Legacy Pairing
9355  * @param addr
9356  * @param pin
9357  * @return 0 if ok
9358  */
9359 int gap_pin_code_negative(bd_addr_t addr){
9360     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9361     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
9362 }
9363 
9364 /**
9365  * @brief SSP Passkey Response
9366  * @param addr
9367  * @param passkey
9368  * @return 0 if ok
9369  */
9370 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
9371     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9372     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
9373     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
9374 }
9375 
9376 /**
9377  * @brief Abort SSP Passkey Entry/Pairing
9378  * @param addr
9379  * @param pin
9380  * @return 0 if ok
9381  */
9382 int gap_ssp_passkey_negative(const bd_addr_t addr){
9383     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9384     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
9385 }
9386 
9387 /**
9388  * @brief Accept SSP Numeric Comparison
9389  * @param addr
9390  * @param passkey
9391  * @return 0 if ok
9392  */
9393 int gap_ssp_confirmation_response(const bd_addr_t addr){
9394     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9395     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
9396 }
9397 
9398 /**
9399  * @brief Abort SSP Numeric Comparison/Pairing
9400  * @param addr
9401  * @param pin
9402  * @return 0 if ok
9403  */
9404 int gap_ssp_confirmation_negative(const bd_addr_t addr){
9405     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9406     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
9407 }
9408 
9409 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
9410 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
9411     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9412     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9413     connectionSetAuthenticationFlags(conn, flag);
9414     hci_run();
9415     return ERROR_CODE_SUCCESS;
9416 }
9417 #endif
9418 
9419 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
9420 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
9421     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
9422 }
9423 
9424 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
9425     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
9426 }
9427 #endif
9428 
9429 #ifdef ENABLE_CLASSIC_PAIRING_OOB
9430 /**
9431  * @brief Report Remote OOB Data
9432  * @param bd_addr
9433  * @param c_192 Simple Pairing Hash C derived from P-192 public key
9434  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
9435  * @param c_256 Simple Pairing Hash C derived from P-256 public key
9436  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
9437  */
9438 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){
9439     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9440     if (connection == NULL) {
9441         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9442     }
9443     connection->classic_oob_c_192 = c_192;
9444     connection->classic_oob_r_192 = r_192;
9445 
9446     // ignore P-256 if not supported by us
9447     if (hci_stack->secure_connections_active){
9448         connection->classic_oob_c_256 = c_256;
9449         connection->classic_oob_r_256 = r_256;
9450     }
9451 
9452     return ERROR_CODE_SUCCESS;
9453 }
9454 /**
9455  * @brief Generate new OOB data
9456  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
9457  */
9458 void gap_ssp_generate_oob_data(void){
9459     hci_stack->classic_read_local_oob_data = true;
9460     hci_run();
9461 }
9462 
9463 #endif
9464 
9465 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
9466 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
9467     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9468     if (connection == NULL) {
9469         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9470     }
9471 
9472     memcpy(connection->link_key, link_key, sizeof(link_key_t));
9473     connection->link_key_type = type;
9474 
9475     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
9476 }
9477 
9478 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
9479 /**
9480  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
9481  * @param inquiry_mode see bluetooth_defines.h
9482  */
9483 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
9484     hci_stack->inquiry_mode = inquiry_mode;
9485 }
9486 
9487 /**
9488  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
9489  */
9490 void hci_set_sco_voice_setting(uint16_t voice_setting){
9491     hci_stack->sco_voice_setting = voice_setting;
9492 }
9493 
9494 /**
9495  * @brief Get SCO Voice Setting
9496  * @return current voice setting
9497  */
9498 uint16_t hci_get_sco_voice_setting(void){
9499     return hci_stack->sco_voice_setting;
9500 }
9501 
9502 static int hci_have_usb_transport(void){
9503     if (!hci_stack->hci_transport) return 0;
9504     const char * transport_name = hci_stack->hci_transport->name;
9505     if (!transport_name) return 0;
9506     return (transport_name[0] == 'H') && (transport_name[1] == '2');
9507 }
9508 
9509 static uint16_t hci_sco_packet_length_for_payload_length(uint16_t payload_size){
9510     uint16_t sco_packet_length = 0;
9511 
9512 #if defined(ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
9513     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
9514     int multiplier;
9515     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) &&
9516         ((hci_stack->sco_voice_setting_active & 0x20) == 0x20)) {
9517         multiplier = 2;
9518     } else {
9519         multiplier = 1;
9520     }
9521 #endif
9522 
9523 #ifdef ENABLE_SCO_OVER_HCI
9524     if (hci_have_usb_transport()){
9525         // see Core Spec for H2 USB Transfer.
9526         // 3 byte SCO header + 24 bytes per connection
9527         // @note multiple sco connections not supported currently
9528         sco_packet_length = 3 + 24 * multiplier;
9529     } else {
9530         // 3 byte SCO header + SCO packet length over the air
9531         sco_packet_length = 3 + payload_size * multiplier;
9532         // assert that it still fits inside an SCO buffer
9533         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
9534             sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9535         }
9536     }
9537 #endif
9538 #ifdef HAVE_SCO_TRANSPORT
9539     // 3 byte SCO header + SCO packet length over the air
9540     sco_packet_length = 3 + payload_size * multiplier;
9541     // assert that it still fits inside an SCO buffer
9542     if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
9543         sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9544     }
9545 #endif
9546     return sco_packet_length;
9547 }
9548 
9549 uint16_t hci_get_sco_packet_length_for_connection(hci_con_handle_t sco_con_handle){
9550     hci_connection_t * connection = hci_connection_for_handle(sco_con_handle);
9551     if (connection != NULL){
9552         return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);
9553     }
9554     return 0;
9555 }
9556 
9557 uint16_t hci_get_sco_packet_length(void){
9558     btstack_linked_list_iterator_t it;
9559     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9560     while (btstack_linked_list_iterator_has_next(&it)){
9561         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
9562         if ( connection->address_type == BD_ADDR_TYPE_SCO ) {
9563             return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);;
9564         }
9565     }
9566     return 0;
9567 }
9568 
9569 /**
9570 * @brief Sets the master/slave policy
9571 * @param policy (0: attempt to become master, 1: let connecting device decide)
9572 */
9573 void hci_set_master_slave_policy(uint8_t policy){
9574     hci_stack->master_slave_policy = policy;
9575 }
9576 
9577 #endif
9578 
9579 HCI_STATE hci_get_state(void){
9580     return hci_stack->state;
9581 }
9582 
9583 #ifdef ENABLE_CLASSIC
9584 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
9585     hci_stack->gap_classic_accept_callback = accept_callback;
9586 }
9587 #endif
9588 
9589 /**
9590  * @brief Set callback for Bluetooth Hardware Error
9591  */
9592 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
9593     hci_stack->hardware_error_callback = fn;
9594 }
9595 
9596 void hci_disconnect_all(void){
9597     btstack_linked_list_iterator_t it;
9598     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9599     while (btstack_linked_list_iterator_has_next(&it)){
9600         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9601         if (con->state == SENT_DISCONNECT) continue;
9602         con->state = SEND_DISCONNECT;
9603     }
9604     hci_run();
9605 }
9606 
9607 uint16_t hci_get_manufacturer(void){
9608     return hci_stack->manufacturer;
9609 }
9610 
9611 #ifdef ENABLE_BLE
9612 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
9613     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
9614     if (!hci_con) return NULL;
9615     return &hci_con->sm_connection;
9616 }
9617 
9618 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
9619 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
9620 #endif
9621 
9622 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
9623     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9624     if (hci_connection == NULL) return 0;
9625     if (hci_is_le_connection(hci_connection)){
9626 #ifdef ENABLE_BLE
9627         sm_connection_t * sm_conn = &hci_connection->sm_connection;
9628         if (sm_conn->sm_connection_encrypted != 0u) {
9629             return sm_conn->sm_actual_encryption_key_size;
9630         }
9631 #endif
9632     } else {
9633 #ifdef ENABLE_CLASSIC
9634         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
9635             return hci_connection->encryption_key_size;
9636         }
9637 #endif
9638     }
9639     return 0;
9640 }
9641 
9642 bool gap_authenticated(hci_con_handle_t con_handle){
9643     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9644     if (hci_connection == NULL) return false;
9645 
9646     switch (hci_connection->address_type){
9647 #ifdef ENABLE_BLE
9648         case BD_ADDR_TYPE_LE_PUBLIC:
9649         case BD_ADDR_TYPE_LE_RANDOM:
9650         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9651         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9652             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
9653             return hci_connection->sm_connection.sm_connection_authenticated != 0;
9654 #endif
9655 #ifdef ENABLE_CLASSIC
9656         case BD_ADDR_TYPE_SCO:
9657         case BD_ADDR_TYPE_ACL:
9658             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
9659 #endif
9660         default:
9661             return false;
9662     }
9663 }
9664 
9665 bool gap_secure_connection(hci_con_handle_t con_handle){
9666     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9667     if (hci_connection == NULL) return 0;
9668 
9669     switch (hci_connection->address_type){
9670 #ifdef ENABLE_BLE
9671         case BD_ADDR_TYPE_LE_PUBLIC:
9672         case BD_ADDR_TYPE_LE_RANDOM:
9673         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9674         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9675             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
9676             return hci_connection->sm_connection.sm_connection_sc;
9677 #endif
9678 #ifdef ENABLE_CLASSIC
9679         case BD_ADDR_TYPE_SCO:
9680         case BD_ADDR_TYPE_ACL:
9681             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
9682 #endif
9683         default:
9684             return false;
9685     }
9686 }
9687 
9688 bool gap_bonded(hci_con_handle_t con_handle){
9689 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9690 	if (hci_connection == NULL) return 0;
9691 
9692 #ifdef ENABLE_CLASSIC
9693 	link_key_t link_key;
9694 	link_key_type_t link_key_type;
9695 #endif
9696 	switch (hci_connection->address_type){
9697 #ifdef ENABLE_BLE
9698 		case BD_ADDR_TYPE_LE_PUBLIC:
9699 		case BD_ADDR_TYPE_LE_RANDOM:
9700 	    case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9701         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9702             return hci_connection->sm_connection.sm_le_db_index >= 0;
9703 #endif
9704 #ifdef ENABLE_CLASSIC
9705 		case BD_ADDR_TYPE_SCO:
9706 		case BD_ADDR_TYPE_ACL:
9707 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
9708 #endif
9709 		default:
9710 			return false;
9711 	}
9712 }
9713 
9714 #ifdef ENABLE_BLE
9715 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
9716     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
9717     if (sm_conn == NULL)                             return AUTHORIZATION_UNKNOWN; // wrong connection
9718     if (sm_conn->sm_connection_encrypted == 0u)      return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
9719     if (sm_conn->sm_connection_authenticated == 0u)  return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
9720     return sm_conn->sm_connection_authorization_state;
9721 }
9722 #endif
9723 
9724 #ifdef ENABLE_CLASSIC
9725 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){
9726     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9727     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9728     conn->sniff_min_interval = sniff_min_interval;
9729     conn->sniff_max_interval = sniff_max_interval;
9730     conn->sniff_attempt = sniff_attempt;
9731     conn->sniff_timeout = sniff_timeout;
9732     hci_run();
9733     return 0;
9734 }
9735 
9736 /**
9737  * @brief Exit Sniff mode
9738  * @param con_handle
9739  @ @return 0 if ok
9740  */
9741 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
9742     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9743     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9744     conn->sniff_min_interval = 0xffff;
9745     hci_run();
9746     return 0;
9747 }
9748 
9749 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){
9750     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9751     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9752     conn->sniff_subrating_max_latency = max_latency;
9753     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
9754     conn->sniff_subrating_min_local_timeout = min_local_timeout;
9755     hci_run();
9756     return ERROR_CODE_SUCCESS;
9757 }
9758 
9759 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){
9760     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9761     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9762     conn->qos_service_type = service_type;
9763     conn->qos_token_rate = token_rate;
9764     conn->qos_peak_bandwidth = peak_bandwidth;
9765     conn->qos_latency = latency;
9766     conn->qos_delay_variation = delay_variation;
9767     hci_run();
9768     return ERROR_CODE_SUCCESS;
9769 }
9770 
9771 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
9772     hci_stack->new_page_scan_interval = page_scan_interval;
9773     hci_stack->new_page_scan_window = page_scan_window;
9774     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
9775     hci_run();
9776 }
9777 
9778 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
9779     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
9780     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
9781     hci_run();
9782 }
9783 
9784 void gap_set_page_timeout(uint16_t page_timeout){
9785     hci_stack->page_timeout = page_timeout;
9786     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
9787     hci_run();
9788 }
9789 
9790 #endif
9791 
9792 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
9793 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
9794     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9795     if (le_device_db_index >= le_device_db_max_count()) return;
9796     uint8_t offset = le_device_db_index >> 3;
9797     uint8_t mask = 1 << (le_device_db_index & 7);
9798     hci_stack->le_resolving_list_add_entries[offset] |= mask;
9799     hci_stack->le_resolving_list_set_privacy_mode[offset] |= mask;
9800     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9801     	// note: go back to remove entries, otherwise, a remove + add will skip the add
9802         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9803     }
9804 }
9805 
9806 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
9807 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9808 	if (le_device_db_index >= le_device_db_max_count()) return;
9809 	uint8_t offset = le_device_db_index >> 3;
9810 	uint8_t mask = 1 << (le_device_db_index & 7);
9811 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
9812 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9813 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9814 	}
9815 }
9816 
9817 uint8_t gap_load_resolving_list_from_le_device_db(void){
9818     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
9819 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
9820 	}
9821 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
9822 		// restart le resolving list update
9823 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
9824 	}
9825 	return ERROR_CODE_SUCCESS;
9826 }
9827 
9828 void gap_set_peer_privacy_mode(le_privacy_mode_t privacy_mode ){
9829     hci_stack->le_privacy_mode = privacy_mode;
9830 }
9831 #endif
9832 
9833 #ifdef ENABLE_BLE
9834 #ifdef ENABLE_LE_CENTRAL
9835 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
9836 
9837 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9838 
9839 #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES) || (MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES == 0))
9840     // incorrect configuration:
9841     // - as MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES is not defined or zero this function always fails
9842     // - please set MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES in btstack_config.h
9843     btstack_assert(false);
9844 #endif
9845 
9846     // check if already in list
9847     btstack_linked_list_iterator_t it;
9848     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9849     while (btstack_linked_list_iterator_has_next(&it)) {
9850         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
9851         if (entry->sid != advertising_sid) {
9852             continue;
9853         }
9854         if (entry->address_type != address_type) {
9855             continue;
9856         }
9857         if (memcmp(entry->address, address, 6) != 0) {
9858             continue;
9859         }
9860         // disallow if already scheduled to add
9861         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
9862             return ERROR_CODE_COMMAND_DISALLOWED;
9863         }
9864         // still on controller, but scheduled to remove -> re-add
9865         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9866         return ERROR_CODE_SUCCESS;
9867     }
9868     // alloc and add to list
9869     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
9870     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9871     entry->sid = advertising_sid;
9872     entry->address_type = address_type;
9873     (void)memcpy(entry->address, address, 6);
9874     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9875     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
9876     return ERROR_CODE_SUCCESS;
9877 }
9878 
9879 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9880     btstack_linked_list_iterator_t it;
9881     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9882     while (btstack_linked_list_iterator_has_next(&it)){
9883         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9884         if (entry->sid != advertising_sid) {
9885             continue;
9886         }
9887         if (entry->address_type != address_type) {
9888             continue;
9889         }
9890         if (memcmp(entry->address, address, 6) != 0) {
9891             continue;
9892         }
9893         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9894             // remove from controller if already present
9895             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9896         }  else {
9897             // directly remove entry from whitelist
9898             btstack_linked_list_iterator_remove(&it);
9899             btstack_memory_periodic_advertiser_list_entry_free(entry);
9900         }
9901         return ERROR_CODE_SUCCESS;
9902     }
9903     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9904 }
9905 
9906 static void hci_periodic_advertiser_list_clear(void){
9907     btstack_linked_list_iterator_t it;
9908     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9909     while (btstack_linked_list_iterator_has_next(&it)){
9910         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9911         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9912             // remove from controller if already present
9913             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9914             continue;
9915         }
9916         // directly remove entry from whitelist
9917         btstack_linked_list_iterator_remove(&it);
9918         btstack_memory_periodic_advertiser_list_entry_free(entry);
9919     }
9920 }
9921 
9922 uint8_t gap_periodic_advertiser_list_clear(void){
9923     hci_periodic_advertiser_list_clear();
9924     hci_run();
9925     return ERROR_CODE_SUCCESS;
9926 }
9927 
9928 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9929     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
9930     if (status){
9931         return status;
9932     }
9933     hci_run();
9934     return ERROR_CODE_SUCCESS;
9935 }
9936 
9937 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9938     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
9939     if (status){
9940         return status;
9941     }
9942     hci_run();
9943     return ERROR_CODE_SUCCESS;
9944 }
9945 
9946 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
9947                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
9948     // abort if already active
9949     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
9950         return ERROR_CODE_COMMAND_DISALLOWED;
9951     }
9952     // store request
9953     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
9954     hci_stack->le_periodic_sync_options = options;
9955     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
9956     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
9957     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
9958     hci_stack->le_periodic_sync_skip = skip;
9959     hci_stack->le_periodic_sync_timeout = sync_timeout;
9960     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
9961 
9962     hci_run();
9963     return ERROR_CODE_SUCCESS;
9964 }
9965 
9966 uint8_t gap_periodic_advertising_create_sync_cancel(void){
9967     // abort if not requested
9968     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
9969         return ERROR_CODE_COMMAND_DISALLOWED;
9970     }
9971     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
9972     hci_run();
9973     return ERROR_CODE_SUCCESS;
9974 }
9975 
9976 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
9977     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
9978         return ERROR_CODE_COMMAND_DISALLOWED;
9979     }
9980     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
9981     hci_run();
9982     return ERROR_CODE_SUCCESS;
9983 }
9984 
9985 #endif
9986 #endif
9987 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
9988 static hci_iso_stream_t *
9989 hci_iso_stream_create(hci_iso_type_t iso_type, hci_iso_stream_state_t state, uint8_t group_id, uint8_t stream_id) {
9990     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
9991     if (iso_stream != NULL){
9992         iso_stream->iso_type = iso_type;
9993         iso_stream->state = state;
9994         iso_stream->group_id = group_id;
9995         iso_stream->stream_id = stream_id;
9996         iso_stream->cis_handle = HCI_CON_HANDLE_INVALID;
9997         iso_stream->acl_handle = HCI_CON_HANDLE_INVALID;
9998         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
9999     }
10000     return iso_stream;
10001 }
10002 
10003 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
10004     btstack_linked_list_iterator_t it;
10005     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10006     while (btstack_linked_list_iterator_has_next(&it)){
10007         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10008         if (iso_stream->cis_handle == con_handle ) {
10009             return iso_stream;
10010         }
10011     }
10012     return NULL;
10013 }
10014 
10015 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
10016     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->cis_handle, iso_stream->group_id);
10017     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
10018     btstack_memory_hci_iso_stream_free(iso_stream);
10019 }
10020 
10021 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
10022     btstack_linked_list_iterator_t it;
10023     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10024     while (btstack_linked_list_iterator_has_next(&it)){
10025         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10026         if ((iso_stream->group_id == group_id) &&
10027             (iso_stream->iso_type == iso_type)){
10028             btstack_linked_list_iterator_remove(&it);
10029             btstack_memory_hci_iso_stream_free(iso_stream);
10030         }
10031     }
10032 }
10033 
10034 static void hci_iso_stream_requested_finalize(uint8_t group_id) {
10035     btstack_linked_list_iterator_t it;
10036     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10037     while (btstack_linked_list_iterator_has_next(&it)){
10038         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10039         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
10040             (iso_stream->group_id == group_id)){
10041             btstack_linked_list_iterator_remove(&it);
10042             btstack_memory_hci_iso_stream_free(iso_stream);
10043         }
10044     }
10045 }
10046 static void hci_iso_stream_requested_confirm(uint8_t big_handle){
10047     btstack_linked_list_iterator_t it;
10048     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10049     while (btstack_linked_list_iterator_has_next(&it)){
10050         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10051         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
10052             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
10053         }
10054     }
10055 }
10056 
10057 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
10058     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
10059     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
10060     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
10061     return (sdu_len_offset + 2 + sdu_len) == size;
10062 }
10063 
10064 static void hci_iso_packet_handler(hci_iso_stream_t *iso_stream, uint8_t *packet, uint16_t size) {
10065     if (iso_stream == NULL){
10066         log_error("acl_handler called with non-registered handle %u!" , READ_ISO_CONNECTION_HANDLE(packet));
10067         return;
10068     }
10069 
10070     if (hci_stack->iso_packet_handler == NULL) {
10071         return;
10072     }
10073 
10074     // parse header
10075     uint16_t con_handle_and_flags = little_endian_read_16(packet, 0);
10076     uint16_t data_total_length = little_endian_read_16(packet, 2);
10077     uint8_t  pb_flag = (con_handle_and_flags >> 12) & 3;
10078 
10079     // assert packet is complete
10080     if ((data_total_length + 4u) != size){
10081         return;
10082     }
10083 
10084     if ((pb_flag & 0x01) == 0){
10085         if (pb_flag == 0x02){
10086             // The ISO_SDU_Fragment field contains a header and a complete SDU.
10087             if (hci_iso_sdu_complete(packet, size)) {
10088                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
10089             }
10090         } else {
10091             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
10092             if (size > sizeof(iso_stream->reassembly_buffer)){
10093                 return;
10094             }
10095             memcpy(iso_stream->reassembly_buffer, packet, size);
10096             // fix pb_flag
10097             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
10098             iso_stream->reassembly_pos = size;
10099         }
10100     } else {
10101         // ISO_SDU_Fragment contains continuation or last fragment of an SDU
10102         uint8_t ts_flag = (con_handle_and_flags >> 14) & 1;
10103         if (ts_flag != 0){
10104            return;
10105         }
10106         // append fragment
10107         if (iso_stream->reassembly_pos == 0){
10108             return;
10109         }
10110 
10111         if ((iso_stream->reassembly_pos + data_total_length) > sizeof(iso_stream->reassembly_buffer)){
10112             // reset reassembly buffer
10113             iso_stream->reassembly_pos = 0;
10114             return;
10115         }
10116         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], data_total_length);
10117         iso_stream->reassembly_pos += data_total_length;
10118 
10119         // deliver if last fragment and SDU complete
10120         if (pb_flag == 0x03){
10121             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
10122                 // fix data_total_length
10123                 little_endian_store_16(iso_stream->reassembly_buffer, 2, iso_stream->reassembly_pos - HCI_ISO_HEADER_SIZE);
10124                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
10125             }
10126             // reset reassembly buffer
10127             iso_stream->reassembly_pos = 0;
10128         }
10129     }
10130 }
10131 
10132 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
10133     uint8_t event [6 + (MAX_NR_BIS * 2)];
10134     uint16_t pos = 0;
10135     event[pos++] = HCI_EVENT_META_GAP;
10136     event[pos++] = 4 + (2 * big->num_bis);
10137     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
10138     event[pos++] = status;
10139     event[pos++] = big->big_handle;
10140     event[pos++] = big->num_bis;
10141     uint8_t i;
10142     for (i=0;i<big->num_bis;i++){
10143         little_endian_store_16(event, pos, big->bis_con_handles[i]);
10144         pos += 2;
10145     }
10146     hci_emit_event(event, pos, 0);
10147 }
10148 
10149 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
10150     uint8_t event [6 + (MAX_NR_CIS * 2)];
10151     uint16_t pos = 0;
10152     event[pos++] = HCI_EVENT_META_GAP;
10153     event[pos++] = 4 + (2 * cig->num_cis);
10154     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
10155     event[pos++] = status;
10156     event[pos++] = cig->cig_id;
10157     event[pos++] = cig->num_cis;
10158     uint8_t i;
10159     for (i=0;i<cig->num_cis;i++){
10160         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
10161         pos += 2;
10162     }
10163     hci_emit_event(event, pos, 0);
10164 }
10165 
10166 static uint16_t hci_setup_cis_created(uint8_t * event, hci_iso_stream_t * iso_stream, uint8_t status) {
10167     uint16_t pos = 0;
10168     event[pos++] = HCI_EVENT_META_GAP;
10169     event[pos++] = 8;
10170     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
10171     event[pos++] = status;
10172     event[pos++] = iso_stream->group_id;
10173     event[pos++] = iso_stream->stream_id;
10174     little_endian_store_16(event, pos, iso_stream->cis_handle);
10175     pos += 2;
10176     little_endian_store_16(event, pos, iso_stream->acl_handle);
10177     pos += 2;
10178     little_endian_store_16(event, pos, iso_stream->iso_interval_1250us);
10179     pos += 2;
10180     event[pos++] = iso_stream->number_of_subevents;
10181     event[pos++] = iso_stream->burst_number_c_to_p;
10182     event[pos++] = iso_stream->burst_number_p_to_c;
10183     event[pos++] = iso_stream->flush_timeout_c_to_p;
10184     event[pos++] = iso_stream->flush_timeout_p_to_c;
10185     return pos;
10186 }
10187 
10188 // emits GAP_SUBEVENT_CIS_CREATED after calling hci_iso_finalize
10189 static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status){
10190     // cache data before finalizing struct
10191     uint8_t event [17];
10192     uint16_t pos = hci_setup_cis_created(event, iso_stream, status);
10193     btstack_assert(pos <= sizeof(event));
10194     if (status != ERROR_CODE_SUCCESS){
10195         hci_iso_stream_finalize(iso_stream);
10196     }
10197     hci_emit_event(event, pos, 0);
10198 }
10199 
10200 static void hci_emit_big_terminated(const le_audio_big_t * big){
10201     uint8_t event [4];
10202     uint16_t pos = 0;
10203     event[pos++] = HCI_EVENT_META_GAP;
10204     event[pos++] = 2;
10205     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
10206     event[pos++] = big->big_handle;
10207     hci_emit_event(event, pos, 0);
10208 }
10209 
10210 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
10211     uint8_t event [6 + (MAX_NR_BIS * 2)];
10212     uint16_t pos = 0;
10213     event[pos++] = HCI_EVENT_META_GAP;
10214     event[pos++] = 4;
10215     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
10216     event[pos++] = status;
10217     event[pos++] = big_sync->big_handle;
10218     event[pos++] = big_sync->num_bis;
10219     uint8_t i;
10220     for (i=0;i<big_sync->num_bis;i++){
10221         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
10222         pos += 2;
10223     }
10224     hci_emit_event(event, pos, 0);
10225 }
10226 
10227 static void hci_emit_big_sync_stopped(uint8_t big_handle){
10228     uint8_t event [4];
10229     uint16_t pos = 0;
10230     event[pos++] = HCI_EVENT_META_GAP;
10231     event[pos++] = 2;
10232     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
10233     event[pos++] = big_handle;
10234     hci_emit_event(event, pos, 0);
10235 }
10236 
10237 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
10238     uint8_t event[6];
10239     uint16_t pos = 0;
10240     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
10241     event[pos++] = sizeof(event) - 2;
10242     event[pos++] = big->big_handle;
10243     event[pos++] = bis_index;
10244     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
10245     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
10246 }
10247 
10248 static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) {
10249     uint8_t event[4];
10250     uint16_t pos = 0;
10251     event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW;
10252     event[pos++] = sizeof(event) - 2;
10253     little_endian_store_16(event, pos, cis_con_handle);
10254     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
10255 }
10256 
10257 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
10258     btstack_linked_list_iterator_t it;
10259     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10260     while (btstack_linked_list_iterator_has_next(&it)){
10261         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10262         if ( big->big_handle == big_handle ) {
10263             return big;
10264         }
10265     }
10266     return NULL;
10267 }
10268 
10269 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
10270     btstack_linked_list_iterator_t it;
10271     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
10272     while (btstack_linked_list_iterator_has_next(&it)){
10273         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
10274         if ( big_sync->big_handle == big_handle ) {
10275             return big_sync;
10276         }
10277     }
10278     return NULL;
10279 }
10280 
10281 void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
10282     hci_stack->iso_packets_to_queue = num_packets;
10283 }
10284 
10285 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
10286     btstack_linked_list_iterator_t it;
10287     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
10288     while (btstack_linked_list_iterator_has_next(&it)){
10289         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
10290         if ( cig->cig_id == cig_id ) {
10291             return cig;
10292         }
10293     }
10294     return NULL;
10295 }
10296 
10297 static void hci_iso_notify_can_send_now(void){
10298 
10299     // BIG
10300 
10301     btstack_linked_list_iterator_t it;
10302     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10303     while (btstack_linked_list_iterator_has_next(&it)){
10304         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10305         // track number completed packet timestamps
10306         if (big->num_completed_timestamp_current_valid){
10307             big->num_completed_timestamp_current_valid = false;
10308             if (big->num_completed_timestamp_previous_valid){
10309                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
10310                 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
10311                 int32_t  num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
10312                                                                                big->num_completed_timestamp_previous_ms);
10313                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
10314                     // to catch up, skip packet on all BIS
10315                     uint8_t i;
10316                     for (i=0;i<big->num_bis;i++){
10317                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10318                         if (iso_stream){
10319                             iso_stream->num_packets_to_skip++;
10320                         }
10321                     }
10322                 }
10323             }
10324             big->num_completed_timestamp_previous_valid = true;
10325             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
10326         }
10327 
10328         if (big->can_send_now_requested){
10329             // check if no outgoing iso packets pending and no can send now have to be emitted
10330             uint8_t i;
10331             bool can_send = true;
10332             uint8_t num_iso_queued_minimum = 0;
10333             for (i=0;i<big->num_bis;i++){
10334                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10335                 if (iso_stream == NULL) continue;
10336                 // handle case where individual ISO packet was sent too late:
10337                 // for each additionally queued packet, a new one needs to get skipped
10338                 if (i==0){
10339                     num_iso_queued_minimum = iso_stream->num_packets_sent;
10340                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
10341                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
10342                     iso_stream->num_packets_to_skip += num_packets_to_skip;
10343                     iso_stream->num_packets_sent    -= num_packets_to_skip;
10344                 }
10345                 // check if we can send now
10346                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
10347                     can_send = false;
10348                     break;
10349                 }
10350             }
10351             if (can_send){
10352                 // propagate can send now to individual streams
10353                 big->can_send_now_requested = false;
10354                 for (i=0;i<big->num_bis;i++){
10355                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10356                     iso_stream->emit_ready_to_send = true;
10357                 }
10358             }
10359         }
10360     }
10361 
10362     if (hci_stack->hci_packet_buffer_reserved) return;
10363 
10364     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10365     while (btstack_linked_list_iterator_has_next(&it)){
10366         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10367         // report bis ready
10368         uint8_t i;
10369         for (i=0;i<big->num_bis;i++){
10370             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10371             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
10372                 iso_stream->emit_ready_to_send = false;
10373                 hci_emit_bis_can_send_now(big, i);
10374                 break;
10375             }
10376         }
10377     }
10378 
10379     // CIS
10380     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10381     while (btstack_linked_list_iterator_has_next(&it)) {
10382         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10383         if ((iso_stream->can_send_now_requested) &&
10384             (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){
10385             iso_stream->can_send_now_requested = false;
10386             hci_emit_cis_can_send_now(iso_stream->cis_handle);
10387         }
10388     }
10389 }
10390 
10391 static uint8_t gap_big_setup_iso_streams(uint8_t num_bis, uint8_t big_handle){
10392     // make big handle unique and usuable for big and big sync
10393     if (hci_big_for_handle(big_handle) != NULL){
10394         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10395     }
10396     if (hci_big_sync_for_handle(big_handle) != NULL){
10397         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10398     }
10399     if (num_bis == 0){
10400         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10401     }
10402     if (num_bis > MAX_NR_BIS){
10403         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10404     }
10405 
10406     // reserve ISO Streams
10407     uint8_t i;
10408     uint8_t status = ERROR_CODE_SUCCESS;
10409     for (i=0;i<num_bis;i++){
10410         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_ISO_STREAM_STATE_REQUESTED, big_handle, i);
10411         if (iso_stream == NULL) {
10412             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10413             break;
10414         }
10415     }
10416 
10417     // free structs on error
10418     if (status != ERROR_CODE_SUCCESS){
10419         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_handle);
10420     }
10421 
10422     return status;
10423 }
10424 
10425 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
10426     uint8_t status = gap_big_setup_iso_streams(big_params->num_bis, big_params->big_handle);
10427     if (status != ERROR_CODE_SUCCESS){
10428         return status;
10429     }
10430 
10431     le_audio_big_t * big = storage;
10432     big->big_handle = big_params->big_handle;
10433     big->params = big_params;
10434     big->state = LE_AUDIO_BIG_STATE_CREATE;
10435     big->num_bis = big_params->num_bis;
10436     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
10437 
10438     hci_run();
10439 
10440     return ERROR_CODE_SUCCESS;
10441 }
10442 
10443 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
10444     uint8_t status = gap_big_setup_iso_streams(big_sync_params->num_bis, big_sync_params->big_handle);
10445     if (status != ERROR_CODE_SUCCESS){
10446         return status;
10447     }
10448 
10449     le_audio_big_sync_t * big_sync = storage;
10450     big_sync->big_handle = big_sync_params->big_handle;
10451     big_sync->params = big_sync_params;
10452     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
10453     big_sync->num_bis = big_sync_params->num_bis;
10454     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10455 
10456     hci_run();
10457 
10458     return ERROR_CODE_SUCCESS;
10459 }
10460 
10461 uint8_t gap_big_terminate(uint8_t big_handle){
10462     le_audio_big_t * big = hci_big_for_handle(big_handle);
10463     if (big == NULL){
10464         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10465     }
10466     switch (big->state){
10467         case LE_AUDIO_BIG_STATE_CREATE:
10468             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
10469             hci_emit_big_terminated(big);
10470             break;
10471         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
10472             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
10473             break;
10474         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
10475         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
10476         case LE_AUDIO_BIG_STATE_ACTIVE:
10477             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
10478             hci_run();
10479             break;
10480         default:
10481             return ERROR_CODE_COMMAND_DISALLOWED;
10482     }
10483     return ERROR_CODE_SUCCESS;
10484 }
10485 
10486 uint8_t gap_big_sync_terminate(uint8_t big_handle){
10487     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
10488     if (big_sync == NULL){
10489         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10490     }
10491     switch (big_sync->state){
10492         case LE_AUDIO_BIG_STATE_CREATE:
10493             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10494             hci_emit_big_sync_stopped(big_handle);
10495             break;
10496         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
10497             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
10498             break;
10499         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
10500         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
10501         case LE_AUDIO_BIG_STATE_ACTIVE:
10502             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
10503             hci_run();
10504             break;
10505         default:
10506             return ERROR_CODE_COMMAND_DISALLOWED;
10507     }
10508     return ERROR_CODE_SUCCESS;
10509 }
10510 
10511 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
10512     le_audio_big_t * big = hci_big_for_handle(big_handle);
10513     if (big == NULL){
10514         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10515     }
10516     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
10517         return ERROR_CODE_COMMAND_DISALLOWED;
10518     }
10519     big->can_send_now_requested = true;
10520     hci_iso_notify_can_send_now();
10521     return ERROR_CODE_SUCCESS;
10522 }
10523 
10524 uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){
10525     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
10526     if (iso_stream == NULL){
10527         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10528     }
10529     if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) {
10530         return ERROR_CODE_COMMAND_DISALLOWED;
10531     }
10532     iso_stream->can_send_now_requested = true;
10533     hci_iso_notify_can_send_now();
10534     return ERROR_CODE_SUCCESS;
10535 }
10536 
10537 uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
10538     if (hci_cig_for_id(cig_params->cig_id) != NULL){
10539         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10540     }
10541     if (cig_params->num_cis == 0){
10542         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10543     }
10544     if (cig_params->num_cis > MAX_NR_CIS){
10545         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10546     }
10547 
10548     // reserve ISO Streams
10549     uint8_t i;
10550     uint8_t status = ERROR_CODE_SUCCESS;
10551     for (i=0;i<cig_params->num_cis;i++){
10552         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS,HCI_ISO_STREAM_STATE_REQUESTED, cig_params->cig_id, i);
10553         if (iso_stream == NULL) {
10554             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10555             break;
10556         }
10557     }
10558 
10559     // free structs on error
10560     if (status != ERROR_CODE_SUCCESS){
10561         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
10562         return status;
10563     }
10564 
10565     le_audio_cig_t * cig = storage;
10566     cig->cig_id = cig_params->cig_id;
10567     cig->num_cis = cig_params->num_cis;
10568     cig->params = cig_params;
10569     cig->state = LE_AUDIO_CIG_STATE_CREATE;
10570     for (i=0;i<cig->num_cis;i++){
10571         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
10572         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
10573         cig->cis_setup_active[i] = false;
10574         cig->cis_established[i] = false;
10575     }
10576     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
10577 
10578     hci_run();
10579 
10580     return ERROR_CODE_SUCCESS;
10581 }
10582 
10583 uint8_t gap_cig_remove(uint8_t cig_id){
10584     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10585     if (cig == NULL){
10586         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10587     }
10588 
10589     // close active CIS
10590     uint8_t i;
10591     for (i=0;i<cig->num_cis;i++){
10592         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
10593         if (stream != NULL){
10594             stream->state = HCI_ISO_STREAM_STATE_W2_CLOSE;
10595         }
10596     }
10597     cig->state = LE_AUDIO_CIG_STATE_REMOVE;
10598 
10599     hci_run();
10600 
10601     return ERROR_CODE_SUCCESS;
10602 }
10603 
10604 uint8_t gap_cis_create(uint8_t cig_id, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
10605     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10606     if (cig == NULL){
10607         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10608     }
10609 
10610     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
10611         return ERROR_CODE_COMMAND_DISALLOWED;
10612     }
10613 
10614     // store ACL Connection Handles
10615     uint8_t i;
10616     for (i=0;i<cig->num_cis;i++){
10617         // check that all con handles exist and store
10618         hci_con_handle_t cis_handle = cis_con_handles[i];
10619         if (cis_handle == HCI_CON_HANDLE_INVALID){
10620             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10621         }
10622         uint8_t j;
10623         bool found = false;
10624         for (j=0;j<cig->num_cis;j++){
10625             if (cig->cis_con_handles[j] == cis_handle){
10626                 cig->acl_con_handles[j] = acl_con_handles[j];
10627                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
10628                 btstack_assert(iso_stream != NULL);
10629                 iso_stream->acl_handle = acl_con_handles[j];
10630                 found = true;
10631                 break;
10632             }
10633         }
10634         if (!found){
10635             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10636         }
10637     }
10638 
10639     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
10640     hci_run();
10641 
10642     return ERROR_CODE_SUCCESS;
10643 }
10644 
10645 static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_handle, hci_iso_stream_state_t state){
10646     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
10647     if (iso_stream == NULL){
10648         // if we got a CIS Request but fail to allocate a hci_iso_stream_t object, we won't find it here
10649         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10650     }
10651 
10652     // set next state and continue
10653     iso_stream->state = state;
10654     hci_run();
10655     return ERROR_CODE_SUCCESS;
10656 }
10657 
10658 uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){
10659     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT);
10660 }
10661 
10662 uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){
10663     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT);
10664 }
10665 
10666 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
10667 
10668 // GAP Privacy - notify clients before random address update
10669 
10670 static bool gap_privacy_client_all_ready(void){
10671     // check if all ready
10672     btstack_linked_list_iterator_t it;
10673     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10674     while (btstack_linked_list_iterator_has_next(&it)) {
10675         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10676         if (client->state != GAP_PRIVACY_CLIENT_STATE_READY){
10677             return false;
10678         }
10679     }
10680     return true;
10681 }
10682 
10683 static void gap_privacy_clients_handle_ready(void){
10684     // clear 'ready'
10685     btstack_linked_list_iterator_t it;
10686     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10687     while (btstack_linked_list_iterator_has_next(&it)) {
10688         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10689         client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10690     }
10691     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
10692     hci_run();
10693 }
10694 
10695 static void gap_privacy_clients_notify(bd_addr_t new_random_address){
10696     btstack_linked_list_iterator_t it;
10697     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10698     while (btstack_linked_list_iterator_has_next(&it)) {
10699         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10700         if (client->state == GAP_PRIVACY_CLIENT_STATE_IDLE){
10701             client->state = GAP_PRIVACY_CLIENT_STATE_PENDING;
10702             (*client->callback)(client, new_random_address);
10703         }
10704     }
10705     if (gap_privacy_client_all_ready()){
10706         gap_privacy_clients_handle_ready();
10707     }
10708 }
10709 
10710 void gap_privacy_client_register(gap_privacy_client_t * client){
10711     client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10712     btstack_linked_list_add(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10713 }
10714 
10715 void gap_privacy_client_ready(gap_privacy_client_t * client){
10716     client->state = GAP_PRIVACY_CLIENT_STATE_READY;
10717     if (gap_privacy_client_all_ready()){
10718         gap_privacy_clients_handle_ready();
10719     }
10720 }
10721 
10722 void gap_privacy_client_unregister(gap_privacy_client_t * client){
10723     btstack_linked_list_remove(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10724 }
10725 
10726 #endif /* ENABLE_BLE */
10727 
10728 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
10729 void hci_setup_test_connections_fuzz(void){
10730     hci_connection_t * conn;
10731 
10732     // default address: 66:55:44:33:00:01
10733     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
10734 
10735     // setup Controller info
10736     hci_stack->num_cmd_packets = 255;
10737     hci_stack->acl_packets_total_num = 255;
10738 
10739     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
10740     addr[5] = 0x01;
10741     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
10742     conn->con_handle = addr[5];
10743     conn->state = RECEIVED_CONNECTION_REQUEST;
10744     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10745 
10746     // setup incoming Classic SCO connection with con handle 0x0002
10747     addr[5] = 0x02;
10748     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
10749     conn->con_handle = addr[5];
10750     conn->state = RECEIVED_CONNECTION_REQUEST;
10751     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10752 
10753     // setup ready Classic ACL connection with con handle 0x0003
10754     addr[5] = 0x03;
10755     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
10756     conn->con_handle = addr[5];
10757     conn->state = OPEN;
10758     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10759 
10760     // setup ready Classic SCO connection with con handle 0x0004
10761     addr[5] = 0x04;
10762     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
10763     conn->con_handle = addr[5];
10764     conn->state = OPEN;
10765     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10766 
10767     // setup ready LE ACL connection with con handle 0x005 and public address
10768     addr[5] = 0x05;
10769     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC, HCI_ROLE_SLAVE);
10770     conn->con_handle = addr[5];
10771     conn->state = OPEN;
10772     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10773     conn->sm_connection.sm_connection_encrypted = 1;
10774 }
10775 
10776 void hci_free_connections_fuzz(void){
10777     btstack_linked_list_iterator_t it;
10778     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
10779     while (btstack_linked_list_iterator_has_next(&it)){
10780         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
10781         btstack_linked_list_iterator_remove(&it);
10782         btstack_memory_hci_connection_free(con);
10783     }
10784 }
10785 void hci_simulate_working_fuzz(void){
10786     hci_stack->le_scanning_param_update = false;
10787     hci_init_done();
10788     hci_stack->num_cmd_packets = 255;
10789 }
10790 #endif
10791