xref: /btstack/src/hci.c (revision 5b0f090baa70e403643bff22d333b468d42029e0)
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                         hci_emit_transport_packet_sent();
4196                     }
4197                 }
4198             }
4199 
4200 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4201             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
4202             if (hci_stack->iso_fragmentation_total_size > 0u) {
4203                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4204                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
4205                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
4206                     hci_stack->iso_fragmentation_total_size = 0;
4207                     hci_stack->iso_fragmentation_pos = 0;
4208                     if (release_buffer){
4209                         hci_release_packet_buffer();
4210                     }
4211                 }
4212             }
4213 
4214             // finalize iso stream for CIS handle
4215             iso_stream = hci_iso_stream_for_con_handle(handle);
4216             if (iso_stream != NULL){
4217                 hci_iso_stream_finalize(iso_stream);
4218                 break;
4219             }
4220 
4221             // finalize iso stream(s) for ACL handle
4222             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4223             while (btstack_linked_list_iterator_has_next(&it)){
4224                 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4225                 if (iso_stream->acl_handle == handle ) {
4226                     hci_iso_stream_finalize(iso_stream);
4227                 }
4228             }
4229 #endif
4230 
4231 #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
4232             if ((handle != HCI_CON_HANDLE_INVALID) && (handle == hci_stack->hci_command_con_handle)){
4233                 // we did not receive a HCI Command Complete or HCI Command Status event for the disconnected connection
4234                 // if needed, we could also track the hci command opcode and simulate a hci command complete with status
4235                 // but the connection has failed anyway, so for now, we only set the num hci commands back to 1
4236                 log_info("Disconnect for conn handle 0x%04x in pending HCI command, assume command failed", handle);
4237                 hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4238                 hci_stack->num_cmd_packets = 1;
4239             }
4240 #endif
4241 
4242             conn = hci_connection_for_handle(handle);
4243             if (!conn) break;
4244 #ifdef ENABLE_CLASSIC
4245             // pairing failed if it was ongoing
4246             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4247 #endif
4248 
4249             // emit dedicatd bonding event
4250             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
4251                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
4252             }
4253 
4254             // mark connection for shutdown, stop timers, reset state
4255             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
4256             hci_connection_stop_timer(conn);
4257             hci_connection_init(conn);
4258 
4259 #ifdef ENABLE_BLE
4260 #ifdef ENABLE_LE_PERIPHERAL
4261             // re-enable advertisements for le connections if active
4262             if (hci_is_le_connection(conn)){
4263                 hci_update_advertisements_enabled_for_current_roles();
4264             }
4265 #endif
4266 #endif
4267             break;
4268 
4269         case HCI_EVENT_HARDWARE_ERROR:
4270             log_error("Hardware Error: 0x%02x", packet[2]);
4271             if (hci_stack->hardware_error_callback){
4272                 (*hci_stack->hardware_error_callback)(packet[2]);
4273             } else {
4274                 // if no special requests, just reboot stack
4275                 hci_power_control_off();
4276                 hci_power_control_on();
4277             }
4278             break;
4279 
4280 #ifdef ENABLE_CLASSIC
4281         case HCI_EVENT_ROLE_CHANGE:
4282             if (packet[2]) break;   // status != 0
4283             reverse_bd_addr(&packet[3], addr);
4284             addr_type = BD_ADDR_TYPE_ACL;
4285             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4286             if (!conn) break;
4287             conn->role = (hci_role_t) packet[9];
4288             break;
4289 #endif
4290 
4291         case HCI_EVENT_TRANSPORT_PACKET_SENT:
4292             // release packet buffer only for asynchronous transport and if there are not further fragments
4293             if (hci_transport_synchronous()) {
4294                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
4295                 return; // instead of break: to avoid re-entering hci_run()
4296             }
4297             hci_stack->acl_fragmentation_tx_active = 0;
4298 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4299             hci_stack->iso_fragmentation_tx_active = 0;
4300             if (hci_stack->iso_fragmentation_total_size) break;
4301 #endif
4302             if (hci_stack->acl_fragmentation_total_size) break;
4303             hci_release_packet_buffer();
4304 
4305 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4306             hci_iso_notify_can_send_now();
4307 #endif
4308             // L2CAP receives this event via the hci_emit_event below
4309 
4310 #ifdef ENABLE_CLASSIC
4311             // For SCO, we do the can_send_now_check here
4312             hci_notify_if_sco_can_send_now();
4313 #endif
4314             break;
4315 
4316 #ifdef ENABLE_CLASSIC
4317         case HCI_EVENT_SCO_CAN_SEND_NOW:
4318             // For SCO, we do the can_send_now_check here
4319             hci_stack->sco_can_send_now = true;
4320             hci_notify_if_sco_can_send_now();
4321             return;
4322 
4323         // explode inquriy results for easier consumption
4324         case HCI_EVENT_INQUIRY_RESULT:
4325         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4326         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4327             gap_inquiry_explode(packet, size);
4328             break;
4329 #endif
4330 
4331 #ifdef ENABLE_BLE
4332         case HCI_EVENT_LE_META:
4333             switch (packet[2]){
4334 #ifdef ENABLE_LE_CENTRAL
4335                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
4336                     if (!hci_stack->le_scanning_enabled) break;
4337                     le_handle_advertisement_report(packet, size);
4338                     break;
4339 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4340                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
4341                     if (!hci_stack->le_scanning_enabled) break;
4342                     le_handle_extended_advertisement_report(packet, size);
4343                     break;
4344                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
4345                     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
4346                     hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE;
4347                     break;
4348                 case HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED:
4349                     advertising_handle = hci_subevent_le_advertising_set_terminated_get_advertising_handle(packet);
4350                     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4351                     while (btstack_linked_list_iterator_has_next(&it)) {
4352                         le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
4353                         if (advertising_set->advertising_handle == advertising_handle){
4354                             advertising_set->state &= ~(LE_ADVERTISEMENT_STATE_ACTIVE | LE_ADVERTISEMENT_STATE_ENABLED);
4355                         }
4356                     }
4357                     break;
4358 #endif
4359 #endif
4360                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
4361                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
4362                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
4363                     hci_handle_le_connection_complete_event(packet);
4364                     break;
4365 
4366                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
4367                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
4368                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
4369                     conn = hci_connection_for_handle(handle);
4370                     if (!conn) break;
4371                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
4372                     break;
4373 
4374                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
4375                     // connection
4376                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
4377                     conn = hci_connection_for_handle(handle);
4378                     if (conn) {
4379                         // read arguments
4380                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
4381                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
4382                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
4383                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
4384 
4385                         // validate against current connection parameter range
4386                         le_connection_parameter_range_t existing_range;
4387                         gap_get_connection_parameter_range(&existing_range);
4388                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4389                         if (update_parameter){
4390                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
4391                             conn->le_conn_interval_min = le_conn_interval_min;
4392                             conn->le_conn_interval_max = le_conn_interval_max;
4393                             conn->le_conn_latency = le_conn_latency;
4394                             conn->le_supervision_timeout = le_supervision_timeout;
4395                         } else {
4396                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
4397                         }
4398                     }
4399                     break;
4400 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
4401                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
4402                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
4403                     conn = hci_connection_for_handle(handle);
4404                     if (conn) {
4405                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
4406                     }
4407                     break;
4408 #endif
4409 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4410                 case HCI_SUBEVENT_LE_CIS_REQUEST:
4411                     // incoming CIS request, allocate iso stream object and cache metadata
4412                     iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_ISO_STREAM_W4_USER,
4413                                                        hci_subevent_le_cis_request_get_cig_id(packet),
4414                                                        hci_subevent_le_cis_request_get_cis_id(packet));
4415                     // if there's no memory, gap_cis_accept/gap_cis_reject will fail
4416                     if (iso_stream != NULL){
4417                         iso_stream->cis_handle = hci_subevent_le_cis_request_get_cis_connection_handle(packet);
4418                         iso_stream->acl_handle = hci_subevent_le_cis_request_get_acl_connection_handle(packet);
4419                     }
4420                     break;
4421                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
4422                     if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
4423                         handle = hci_subevent_le_cis_established_get_connection_handle(packet);
4424                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
4425                         iso_stream = hci_iso_stream_for_con_handle(handle);
4426                         btstack_assert(iso_stream != NULL);
4427                         // track connection info
4428                         iso_stream->number_of_subevents  = hci_subevent_le_cis_established_get_nse(packet);
4429                         iso_stream->burst_number_c_to_p  = hci_subevent_le_cis_established_get_bn_c_to_p(packet);
4430                         iso_stream->burst_number_p_to_c  = hci_subevent_le_cis_established_get_bn_p_to_c(packet);
4431                         iso_stream->flush_timeout_c_to_p = hci_subevent_le_cis_established_get_ft_c_to_p(packet);
4432                         iso_stream->flush_timeout_p_to_c = hci_subevent_le_cis_established_get_ft_p_to_c(packet);
4433                         iso_stream->max_sdu_c_to_p       = hci_subevent_le_cis_established_get_max_pdu_c_to_p(packet);
4434                         iso_stream->max_sdu_p_to_c       = hci_subevent_le_cis_established_get_max_pdu_p_to_c(packet);
4435                         iso_stream->iso_interval_1250us  = hci_subevent_le_cis_established_get_iso_interval(packet);
4436                         if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
4437                             // CIS Accept by Peripheral
4438                             if (status == ERROR_CODE_SUCCESS){
4439                                 if (iso_stream->max_sdu_p_to_c > 0){
4440                                     // we're peripheral and we will send data
4441                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT;
4442                                 } else {
4443                                     // we're peripheral and we will only receive data
4444                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
4445                                 }
4446                             } else {
4447                                 hci_cis_handle_created(iso_stream, status);
4448                             }
4449                             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4450                         } else {
4451                             // CIG Setup by Central
4452                             le_audio_cig_t * cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
4453                             btstack_assert(cig != NULL);
4454                             // update iso stream state
4455                             if (status == ERROR_CODE_SUCCESS){
4456                                 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4457                             } else {
4458                                 iso_stream->state = HCI_ISO_STREAM_STATE_IDLE;
4459                             }
4460                             // update cig state
4461                             uint8_t i;
4462                             for (i=0;i<cig->num_cis;i++){
4463                                 if (cig->cis_con_handles[i] == handle){
4464                                     cig->cis_setup_active[i] = false;
4465                                     if (status == ERROR_CODE_SUCCESS){
4466                                         cig->cis_established[i] = true;
4467                                     } else {
4468                                         hci_cis_handle_created(iso_stream, status);
4469                                     }
4470                                 }
4471                             }
4472 
4473                             // trigger iso path setup if complete
4474                             bool cis_setup_active = false;
4475                             for (i=0;i<cig->num_cis;i++){
4476                                 cis_setup_active |= cig->cis_setup_active[i];
4477                             }
4478                             if (cis_setup_active == false){
4479                                 cig->state_vars.next_cis = 0;
4480                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
4481                                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4482                             }
4483                         }
4484                     }
4485                     break;
4486                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
4487                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4488                     big = hci_big_for_handle(packet[4]);
4489                     if (big != NULL){
4490                         uint8_t status = packet[3];
4491                         if (status == ERROR_CODE_SUCCESS){
4492                             // store bis_con_handles and trigger iso path setup
4493                             uint8_t num_bis = btstack_min(big->num_bis, packet[20]);
4494                             uint8_t i;
4495                             for (i=0;i<num_bis;i++){
4496                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4497                                 big->bis_con_handles[i] = bis_handle;
4498                                 // assign bis handle
4499                                 btstack_linked_list_iterator_t it;
4500                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4501                                 while (btstack_linked_list_iterator_has_next(&it)){
4502                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4503                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4504                                         (iso_stream->group_id == big->big_handle)){
4505                                         iso_stream->cis_handle = bis_handle;
4506                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4507                                         break;
4508                                     }
4509                                 }
4510                             }
4511                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4512                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4513                                 big->state_vars.next_bis = 0;
4514                             }
4515                         } else {
4516                             // create BIG failed or has been stopped by us
4517                             hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
4518                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4519                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
4520                                 hci_emit_big_created(big, status);
4521                             } else {
4522                                 hci_emit_big_terminated(big);
4523                             }
4524                         }
4525                     }
4526                     break;
4527                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4528                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4529                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
4530                     if (big != NULL){
4531                         // finalize associated ISO streams
4532                         btstack_linked_list_iterator_t it;
4533                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4534                         while (btstack_linked_list_iterator_has_next(&it)){
4535                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4536                             if (iso_stream->group_id == big->big_handle){
4537                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->cis_handle);
4538                                 btstack_linked_list_iterator_remove(&it);
4539                                 btstack_memory_hci_iso_stream_free(iso_stream);
4540                             }
4541                         }
4542                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4543                         switch (big->state){
4544                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
4545                                 hci_emit_big_created(big, big->state_vars.status);
4546                                 break;
4547                             default:
4548                                 hci_emit_big_terminated(big);
4549                                 break;
4550                         }
4551                     }
4552                     break;
4553                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4554                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4555                     big_sync = hci_big_sync_for_handle(packet[4]);
4556                     if (big_sync != NULL){
4557                         uint8_t status = packet[3];
4558                         uint8_t big_handle = packet[4];
4559                         if (status == ERROR_CODE_SUCCESS){
4560                             // store bis_con_handles and trigger iso path setup
4561                             uint8_t num_bis = btstack_min(big_sync->num_bis, packet[16]);
4562                             uint8_t i;
4563                             for (i=0;i<num_bis;i++){
4564                                 hci_con_handle_t bis_handle = little_endian_read_16(packet, 17 + (2 * i));
4565                                 big_sync->bis_con_handles[i] = bis_handle;
4566                                 // setup iso_stream_t
4567                                 btstack_linked_list_iterator_t it;
4568                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4569                                 while (btstack_linked_list_iterator_has_next(&it)){
4570                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4571                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4572                                         (iso_stream->group_id == big_sync->big_handle)){
4573                                         iso_stream->cis_handle = bis_handle;
4574                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4575                                         break;
4576                                     }
4577                                 }
4578                             }
4579                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4580                                 // trigger iso path setup
4581                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4582                                 big_sync->state_vars.next_bis = 0;
4583                             }
4584                         } else {
4585                             // create BIG Sync failed or has been stopped by us
4586                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4587                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4588                                 hci_emit_big_sync_created(big_sync, status);
4589                             } else {
4590                                 hci_emit_big_sync_stopped(big_handle);
4591                             }
4592                         }
4593                     }
4594                     break;
4595                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4596                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4597                     big_sync = hci_big_sync_for_handle(packet[4]);
4598                     if (big_sync != NULL){
4599                         uint8_t big_handle = packet[4];
4600                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4601                         hci_emit_big_sync_stopped(big_handle);
4602                     }
4603                     break;
4604 #endif
4605                 default:
4606                     break;
4607             }
4608             break;
4609 #endif
4610         case HCI_EVENT_VENDOR_SPECIFIC:
4611             // Vendor specific commands often create vendor specific event instead of num completed packets
4612             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
4613             switch (hci_stack->manufacturer){
4614                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
4615                     hci_stack->num_cmd_packets = 1;
4616                     break;
4617                 default:
4618                     break;
4619             }
4620             break;
4621         default:
4622             break;
4623     }
4624 
4625     handle_event_for_current_stack_state(packet, size);
4626 
4627     // notify upper stack
4628 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
4629 
4630     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4631     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4632 		handle = little_endian_read_16(packet, 3);
4633 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4634 		// discard connection if app did not trigger a reconnect in the event handler
4635 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
4636 			hci_shutdown_connection(aConn);
4637 		}
4638 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
4639         hci_controller_dump_packets();
4640 #endif
4641     }
4642 
4643 	// execute main loop
4644 	hci_run();
4645 }
4646 
4647 #ifdef ENABLE_CLASSIC
4648 
4649 static void sco_handler(uint8_t * packet, uint16_t size){
4650     // lookup connection struct
4651     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
4652     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
4653     if (!conn) return;
4654 
4655 #ifdef ENABLE_SCO_OVER_HCI
4656     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4657     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4658         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4659             packet[2] = 0x3c;
4660             memmove(&packet[3], &packet[23], 63);
4661             size = 63;
4662         }
4663     }
4664 
4665     if (hci_have_usb_transport()){
4666         // Nothing to do
4667     } else {
4668         // 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);
4669         if (hci_stack->synchronous_flow_control_enabled == 0){
4670             // ignore received SCO packets for the first 10 ms, then allow for max two HCI_SCO_2EV3_SIZE packets
4671             uint16_t max_sco_packets = btstack_min(2 * HCI_SCO_2EV3_SIZE / conn->sco_payload_length, hci_stack->sco_packets_total_num);
4672             if (conn->sco_tx_active == 0){
4673                 if (btstack_time_delta(btstack_run_loop_get_time_ms(), conn->sco_established_ms) > 10){
4674                     conn->sco_tx_active = 1;
4675                     conn->sco_tx_ready = max_sco_packets;
4676                     log_info("Start SCO sending, %u packets", conn->sco_tx_ready);
4677                     hci_notify_if_sco_can_send_now();
4678                 }
4679             } else {
4680                 if (conn->sco_tx_ready < max_sco_packets){
4681                     conn->sco_tx_ready++;
4682                 }
4683                 hci_notify_if_sco_can_send_now();
4684             }
4685         }
4686     }
4687 #endif
4688 
4689     // deliver to app
4690     if (hci_stack->sco_packet_handler) {
4691         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
4692     }
4693 
4694 #ifdef HAVE_SCO_TRANSPORT
4695     // We can send one packet for each received packet
4696     conn->sco_tx_ready++;
4697     hci_notify_if_sco_can_send_now();
4698 #endif
4699 
4700 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4701     conn->num_packets_completed++;
4702     hci_stack->host_completed_packets = 1;
4703     hci_run();
4704 #endif
4705 }
4706 #endif
4707 
4708 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
4709 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4710     // propagate ISO packets received as ACL
4711     hci_iso_stream_t * iso_stream = NULL;
4712     if ((packet_type == HCI_ACL_DATA_PACKET) && (size >= HCI_ACL_HEADER_SIZE)){
4713         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
4714         iso_stream = hci_iso_stream_for_con_handle(con_handle);
4715         if (iso_stream != NULL){
4716             packet_type = HCI_ISO_DATA_PACKET;
4717         }
4718     }
4719 #endif
4720 
4721     hci_dump_packet(packet_type, 1, packet, size);
4722     switch (packet_type) {
4723         case HCI_EVENT_PACKET:
4724             event_handler(packet, size);
4725             break;
4726         case HCI_ACL_DATA_PACKET:
4727             acl_handler(packet, size);
4728             break;
4729 #ifdef ENABLE_CLASSIC
4730         case HCI_SCO_DATA_PACKET:
4731             sco_handler(packet, size);
4732             break;
4733 #endif
4734 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4735         case HCI_ISO_DATA_PACKET:
4736             if ((iso_stream == NULL) && (size >= HCI_ISO_HEADER_SIZE)){
4737                 hci_con_handle_t con_handle = READ_ISO_CONNECTION_HANDLE(packet);
4738                 iso_stream = hci_iso_stream_for_con_handle(con_handle);
4739             }
4740             hci_iso_packet_handler(iso_stream, packet, size);
4741             break;
4742 #endif
4743         default:
4744             break;
4745     }
4746 }
4747 
4748 /**
4749  * @brief Add event packet handler.
4750  */
4751 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4752     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4753 }
4754 
4755 /**
4756  * @brief Remove event packet handler.
4757  */
4758 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
4759     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4760 }
4761 
4762 /** Register HCI packet handlers */
4763 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4764     hci_stack->acl_packet_handler = handler;
4765 }
4766 
4767 #ifdef ENABLE_CLASSIC
4768 /**
4769  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
4770  */
4771 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
4772     hci_stack->sco_packet_handler = handler;
4773 }
4774 #endif
4775 
4776 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4777 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
4778     hci_stack->iso_packet_handler = handler;
4779 }
4780 #endif
4781 
4782 static void hci_state_reset(void){
4783     // no connections yet
4784     hci_stack->connections = NULL;
4785 
4786     // keep discoverable/connectable as this has been requested by the client(s)
4787     // hci_stack->discoverable = 0;
4788     // hci_stack->connectable = 0;
4789     // hci_stack->bondable = 1;
4790     // hci_stack->own_addr_type = 0;
4791 
4792     // buffer is free
4793     hci_stack->hci_packet_buffer_reserved = false;
4794 
4795     // no pending cmds
4796     hci_stack->decline_reason = 0;
4797 
4798     hci_stack->secure_connections_active = false;
4799 
4800 #ifdef ENABLE_CLASSIC
4801     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
4802     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
4803 
4804     hci_stack->gap_tasks_classic =
4805             GAP_TASK_SET_DEFAULT_LINK_POLICY |
4806             GAP_TASK_SET_CLASS_OF_DEVICE |
4807             GAP_TASK_SET_LOCAL_NAME |
4808             GAP_TASK_SET_EIR_DATA |
4809             GAP_TASK_WRITE_SCAN_ENABLE |
4810             GAP_TASK_WRITE_PAGE_TIMEOUT;
4811 #endif
4812 
4813 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4814     hci_stack->classic_read_local_oob_data = false;
4815     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4816 #endif
4817 
4818     // LE
4819 #ifdef ENABLE_BLE
4820     memset(hci_stack->le_random_address, 0, 6);
4821     hci_stack->le_random_address_set = 0;
4822 #endif
4823 #ifdef ENABLE_LE_CENTRAL
4824     hci_stack->le_scanning_active  = false;
4825     hci_stack->le_scanning_param_update = true;
4826     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4827     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4828     hci_stack->le_whitelist_capacity = 0;
4829 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4830     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
4831 #endif
4832 #endif
4833 #ifdef ENABLE_LE_PERIPHERAL
4834     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4835     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4836         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4837     }
4838     if (hci_stack->le_advertisements_data != NULL){
4839         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4840     }
4841 #endif
4842 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4843     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION;
4844 #endif
4845 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4846     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4847     hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID;
4848 #endif
4849 #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
4850     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4851 #endif
4852 }
4853 
4854 #ifdef ENABLE_CLASSIC
4855 /**
4856  * @brief Configure Bluetooth hardware control. Has to be called before power on.
4857  */
4858 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
4859     // store and open remote device db
4860     hci_stack->link_key_db = link_key_db;
4861     if (hci_stack->link_key_db) {
4862         hci_stack->link_key_db->open();
4863     }
4864 }
4865 #endif
4866 
4867 void hci_init(const hci_transport_t *transport, const void *config){
4868 
4869 #ifdef HAVE_MALLOC
4870     if (!hci_stack) {
4871         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
4872     }
4873 #else
4874     hci_stack = &hci_stack_static;
4875 #endif
4876     memset(hci_stack, 0, sizeof(hci_stack_t));
4877 
4878     // reference to use transport layer implementation
4879     hci_stack->hci_transport = transport;
4880 
4881     // reference to used config
4882     hci_stack->config = config;
4883 
4884     // setup pointer for outgoing packet buffer
4885     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
4886 
4887     // max acl payload size defined in config.h
4888     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4889 
4890     // register packet handlers with transport
4891     transport->register_packet_handler(&packet_handler);
4892 
4893     hci_stack->state = HCI_STATE_OFF;
4894 
4895     // class of device
4896     hci_stack->class_of_device = 0x007a020c; // Smartphone
4897 
4898     // bondable by default
4899     hci_stack->bondable = 1;
4900 
4901 #ifdef ENABLE_CLASSIC
4902     // classic name
4903     hci_stack->local_name = default_classic_name;
4904 
4905     // Master slave policy
4906     hci_stack->master_slave_policy = 1;
4907 
4908     // Allow Role Switch
4909     hci_stack->allow_role_switch = 1;
4910 
4911     // Default / minimum security level = 2
4912     hci_stack->gap_security_level = LEVEL_2;
4913 
4914     // Default Security Mode 4
4915     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
4916 
4917     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4918     hci_stack->gap_required_encyrption_key_size = 7;
4919 
4920     // Link Supervision Timeout
4921     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4922 
4923     // All ACL packet types are enabledh
4924     hci_stack->enabled_packet_types_acl = ACL_PACKET_TYPES_ALL;
4925 #endif
4926 
4927     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
4928     hci_stack->ssp_enable = 1;
4929     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
4930     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4931     hci_stack->ssp_auto_accept = 1;
4932 
4933     // Secure Connections: enable (requires support from Controller)
4934     hci_stack->secure_connections_enable = true;
4935 
4936     // voice setting - signed 16 bit pcm data with CVSD over the air
4937     hci_stack->sco_voice_setting = 0x60;
4938 
4939 #ifdef ENABLE_BLE
4940     hci_stack->le_connection_scan_interval = 0x0060;   //    60 ms
4941     hci_stack->le_connection_scan_window   = 0x0030;    //   30 ms
4942     hci_stack->le_connection_interval_min  = 0x0008;    //   10 ms
4943     hci_stack->le_connection_interval_max  = 0x0018;    //   30 ms
4944     hci_stack->le_connection_latency       =      4;    //    4
4945     hci_stack->le_supervision_timeout      = 0x0048;    //  720 ms
4946     hci_stack->le_minimum_ce_length        =      0;    //    0 ms
4947     hci_stack->le_maximum_ce_length        =      0;    //    0 ms
4948 #endif
4949 
4950 #ifdef ENABLE_LE_CENTRAL
4951     hci_stack->le_connection_phys          =   0x01;    // LE 1M PHY
4952 
4953     // default LE Scanning
4954     hci_stack->le_scan_type     =  0x01; // active
4955     hci_stack->le_scan_interval = 0x1e0; // 300 ms
4956     hci_stack->le_scan_window   =  0x30; //  30 ms
4957     hci_stack->le_scan_phys     =  0x01; // LE 1M PHY
4958 #endif
4959 
4960 #ifdef ENABLE_LE_PERIPHERAL
4961     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4962 
4963     // default advertising parameters from Core v5.4 -- needed to use random address without prior adv setup
4964     hci_stack->le_advertisements_interval_min =                         0x0800;
4965     hci_stack->le_advertisements_interval_max =                         0x0800;
4966     hci_stack->le_advertisements_type =                                      0;
4967     hci_stack->le_own_addr_type =                       BD_ADDR_TYPE_LE_PUBLIC;
4968     hci_stack->le_advertisements_direct_address_type =  BD_ADDR_TYPE_LE_PUBLIC;
4969     hci_stack->le_advertisements_channel_map =                            0x07;
4970     hci_stack->le_advertisements_filter_policy =                             0;
4971 #endif
4972 
4973     // connection parameter range used to answer connection parameter update requests in l2cap
4974     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4975     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4976     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4977     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4978     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4979     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4980 
4981 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4982     hci_stack->iso_packets_to_queue = 1;
4983 #endif
4984 
4985 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4986     hci_stack->le_privacy_mode = LE_PRIVACY_MODE_DEVICE;
4987 #endif
4988 
4989     hci_state_reset();
4990 }
4991 
4992 void hci_deinit(void){
4993     btstack_run_loop_remove_timer(&hci_stack->timeout);
4994 #ifdef HAVE_MALLOC
4995     if (hci_stack) {
4996         free(hci_stack);
4997     }
4998 #endif
4999     hci_stack = NULL;
5000 
5001 #ifdef ENABLE_CLASSIC
5002     disable_l2cap_timeouts = 0;
5003 #endif
5004 }
5005 
5006 /**
5007  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
5008  */
5009 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
5010     hci_stack->chipset = chipset_driver;
5011 
5012     // reset chipset driver - init is also called on power_up
5013     if (hci_stack->chipset && hci_stack->chipset->init){
5014         hci_stack->chipset->init(hci_stack->config);
5015     }
5016 }
5017 
5018 void hci_enable_custom_pre_init(void){
5019     hci_stack->chipset_pre_init = true;
5020 }
5021 
5022 /**
5023  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
5024  */
5025 void hci_set_control(const btstack_control_t *hardware_control){
5026     // references to used control implementation
5027     hci_stack->control = hardware_control;
5028     // init with transport config
5029     hardware_control->init(hci_stack->config);
5030 }
5031 
5032 static void hci_discard_connections(void){
5033     btstack_linked_list_iterator_t it;
5034     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5035     while (btstack_linked_list_iterator_has_next(&it)){
5036         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
5037         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
5038         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
5039         hci_shutdown_connection(connection);
5040     }
5041 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5042     while (hci_stack->iso_streams != NULL){
5043         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
5044     }
5045 #endif
5046 }
5047 
5048 void hci_close(void){
5049 
5050 #ifdef ENABLE_CLASSIC
5051     // close remote device db
5052     if (hci_stack->link_key_db) {
5053         hci_stack->link_key_db->close();
5054     }
5055 #endif
5056 
5057     hci_discard_connections();
5058 
5059     hci_power_control(HCI_POWER_OFF);
5060 
5061 #ifdef HAVE_MALLOC
5062     free(hci_stack);
5063 #endif
5064     hci_stack = NULL;
5065 }
5066 
5067 #ifdef HAVE_SCO_TRANSPORT
5068 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
5069     hci_stack->sco_transport = sco_transport;
5070     sco_transport->register_packet_handler(&packet_handler);
5071 }
5072 #endif
5073 
5074 #ifdef ENABLE_CLASSIC
5075 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
5076     // validate ranage and set
5077     if (encryption_key_size < 7)  return;
5078     if (encryption_key_size > 16) return;
5079     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
5080 }
5081 
5082 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
5083     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
5084         hci_stack->gap_security_mode = security_mode;
5085         return ERROR_CODE_SUCCESS;
5086     } else {
5087         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
5088     }
5089 }
5090 
5091 gap_security_mode_t gap_get_security_mode(void){
5092     return hci_stack->gap_security_mode;
5093 }
5094 
5095 void gap_set_security_level(gap_security_level_t security_level){
5096     hci_stack->gap_security_level = security_level;
5097 }
5098 
5099 gap_security_level_t gap_get_security_level(void){
5100     if (hci_stack->gap_secure_connections_only_mode){
5101         return LEVEL_4;
5102     }
5103     return hci_stack->gap_security_level;
5104 }
5105 
5106 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
5107     hci_stack->gap_minimal_service_security_level = security_level;
5108 }
5109 
5110 void gap_set_secure_connections_only_mode(bool enable){
5111     hci_stack->gap_secure_connections_only_mode = enable;
5112 }
5113 
5114 bool gap_get_secure_connections_only_mode(void){
5115     return hci_stack->gap_secure_connections_only_mode;
5116 }
5117 #endif
5118 
5119 #ifdef ENABLE_CLASSIC
5120 void gap_set_class_of_device(uint32_t class_of_device){
5121     hci_stack->class_of_device = class_of_device;
5122     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
5123     hci_run();
5124 }
5125 
5126 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
5127     hci_stack->default_link_policy_settings = default_link_policy_settings;
5128     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
5129     hci_run();
5130 }
5131 
5132 void gap_set_allow_role_switch(bool allow_role_switch){
5133     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
5134 }
5135 
5136 uint8_t hci_get_allow_role_switch(void){
5137     return  hci_stack->allow_role_switch;
5138 }
5139 
5140 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
5141     hci_stack->link_supervision_timeout = link_supervision_timeout;
5142 }
5143 
5144 void gap_enable_link_watchdog(uint16_t timeout_ms){
5145     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
5146 }
5147 
5148 uint16_t hci_automatic_flush_timeout(void){
5149     return hci_stack->automatic_flush_timeout;
5150 }
5151 
5152 void hci_disable_l2cap_timeout_check(void){
5153     disable_l2cap_timeouts = 1;
5154 }
5155 #endif
5156 
5157 #ifndef HAVE_HOST_CONTROLLER_API
5158 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
5159 void hci_set_bd_addr(bd_addr_t addr){
5160     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
5161     hci_stack->custom_bd_addr_set = 1;
5162 }
5163 #endif
5164 
5165 // State-Module-Driver overview
5166 // state                    module  low-level
5167 // HCI_STATE_OFF             off      close
5168 // HCI_STATE_INITIALIZING,   on       open
5169 // HCI_STATE_WORKING,        on       open
5170 // HCI_STATE_HALTING,        on       open
5171 // HCI_STATE_SLEEPING,    off/sleep   close
5172 // HCI_STATE_FALLING_ASLEEP  on       open
5173 
5174 static int hci_power_control_on(void){
5175 
5176     // power on
5177     int err = 0;
5178     if (hci_stack->control && hci_stack->control->on){
5179         err = (*hci_stack->control->on)();
5180     }
5181     if (err){
5182         log_error( "POWER_ON failed");
5183         hci_emit_hci_open_failed();
5184         return err;
5185     }
5186 
5187     // int chipset driver
5188     if (hci_stack->chipset && hci_stack->chipset->init){
5189         hci_stack->chipset->init(hci_stack->config);
5190     }
5191 
5192     // init transport
5193     if (hci_stack->hci_transport->init){
5194         hci_stack->hci_transport->init(hci_stack->config);
5195     }
5196 
5197     // open transport
5198     err = hci_stack->hci_transport->open();
5199     if (err){
5200         log_error( "HCI_INIT failed, turning Bluetooth off again");
5201         if (hci_stack->control && hci_stack->control->off){
5202             (*hci_stack->control->off)();
5203         }
5204         hci_emit_hci_open_failed();
5205         return err;
5206     }
5207     return 0;
5208 }
5209 
5210 static void hci_power_control_off(void){
5211 
5212     log_info("hci_power_control_off");
5213 
5214     // close low-level device
5215     hci_stack->hci_transport->close();
5216 
5217     log_info("hci_power_control_off - hci_transport closed");
5218 
5219     // power off
5220     if (hci_stack->control && hci_stack->control->off){
5221         (*hci_stack->control->off)();
5222     }
5223 
5224     log_info("hci_power_control_off - control closed");
5225 
5226     hci_stack->state = HCI_STATE_OFF;
5227 }
5228 
5229 static void hci_power_control_sleep(void){
5230 
5231     log_info("hci_power_control_sleep");
5232 
5233 #if 0
5234     // don't close serial port during sleep
5235 
5236     // close low-level device
5237     hci_stack->hci_transport->close(hci_stack->config);
5238 #endif
5239 
5240     // sleep mode
5241     if (hci_stack->control && hci_stack->control->sleep){
5242         (*hci_stack->control->sleep)();
5243     }
5244 
5245     hci_stack->state = HCI_STATE_SLEEPING;
5246 }
5247 
5248 static int hci_power_control_wake(void){
5249 
5250     log_info("hci_power_control_wake");
5251 
5252     // wake on
5253     if (hci_stack->control && hci_stack->control->wake){
5254         (*hci_stack->control->wake)();
5255     }
5256 
5257 #if 0
5258     // open low-level device
5259     int err = hci_stack->hci_transport->open(hci_stack->config);
5260     if (err){
5261         log_error( "HCI_INIT failed, turning Bluetooth off again");
5262         if (hci_stack->control && hci_stack->control->off){
5263             (*hci_stack->control->off)();
5264         }
5265         hci_emit_hci_open_failed();
5266         return err;
5267     }
5268 #endif
5269 
5270     return 0;
5271 }
5272 
5273 static void hci_power_enter_initializing_state(void){
5274     // set up state machine
5275     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
5276     hci_stack->hci_packet_buffer_reserved = false;
5277     hci_stack->state = HCI_STATE_INITIALIZING;
5278 
5279 #ifndef HAVE_HOST_CONTROLLER_API
5280     if (hci_stack->chipset_pre_init) {
5281         hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
5282     } else
5283 #endif
5284     {
5285         hci_stack->substate = HCI_INIT_SEND_RESET;
5286     }
5287 }
5288 
5289 static void hci_power_enter_halting_state(void){
5290 #ifdef ENABLE_BLE
5291     // drop entries scheduled for removal, mark others for re-adding
5292     btstack_linked_list_iterator_t it;
5293     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5294     while (btstack_linked_list_iterator_has_next(&it)){
5295         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5296         if ((entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)) == LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5297             btstack_linked_list_iterator_remove(&it);
5298             btstack_memory_whitelist_entry_free(entry);
5299         } else {
5300             entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5301         }
5302     }
5303 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5304     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
5305     const uint8_t mask = LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5306     while (btstack_linked_list_iterator_has_next(&it)){
5307         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
5308         if ((entry->state & mask) == LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER) {
5309             btstack_linked_list_iterator_remove(&it);
5310             btstack_memory_periodic_advertiser_list_entry_free(entry);
5311         } else {
5312             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5313             continue;
5314         }
5315     }
5316 #endif
5317 #endif
5318     // see hci_run
5319     hci_stack->state = HCI_STATE_HALTING;
5320     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
5321     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
5322     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
5323     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5324     btstack_run_loop_add_timer(&hci_stack->timeout);
5325 }
5326 
5327 // returns error
5328 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
5329     int err;
5330     switch (power_mode){
5331         case HCI_POWER_ON:
5332             err = hci_power_control_on();
5333             if (err != 0) {
5334                 log_error("hci_power_control_on() error %d", err);
5335                 return err;
5336             }
5337             hci_power_enter_initializing_state();
5338             break;
5339         case HCI_POWER_OFF:
5340             // do nothing
5341             break;
5342         case HCI_POWER_SLEEP:
5343             // do nothing (with SLEEP == OFF)
5344             break;
5345         default:
5346             btstack_assert(false);
5347             break;
5348     }
5349     return ERROR_CODE_SUCCESS;
5350 }
5351 
5352 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
5353     switch (power_mode){
5354         case HCI_POWER_ON:
5355             // do nothing
5356             break;
5357         case HCI_POWER_OFF:
5358             // no connections yet, just turn it off
5359             hci_power_control_off();
5360             break;
5361         case HCI_POWER_SLEEP:
5362             // no connections yet, just turn it off
5363             hci_power_control_sleep();
5364             break;
5365         default:
5366             btstack_assert(false);
5367             break;
5368     }
5369     return ERROR_CODE_SUCCESS;
5370 }
5371 
5372 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
5373     switch (power_mode){
5374         case HCI_POWER_ON:
5375             // do nothing
5376             break;
5377         case HCI_POWER_OFF:
5378             hci_power_enter_halting_state();
5379             break;
5380         case HCI_POWER_SLEEP:
5381             // see hci_run
5382             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5383             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5384             break;
5385         default:
5386             btstack_assert(false);
5387             break;
5388     }
5389     return ERROR_CODE_SUCCESS;
5390 }
5391 
5392 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
5393     switch (power_mode){
5394         case HCI_POWER_ON:
5395             hci_power_enter_initializing_state();
5396             break;
5397         case HCI_POWER_OFF:
5398             // do nothing
5399             break;
5400         case HCI_POWER_SLEEP:
5401             // see hci_run
5402             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5403             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5404             break;
5405         default:
5406             btstack_assert(false);
5407             break;
5408     }
5409     return ERROR_CODE_SUCCESS;
5410 }
5411 
5412 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
5413     switch (power_mode){
5414         case HCI_POWER_ON:
5415             hci_power_enter_initializing_state();
5416             break;
5417         case HCI_POWER_OFF:
5418             hci_power_enter_halting_state();
5419             break;
5420         case HCI_POWER_SLEEP:
5421             // do nothing
5422             break;
5423         default:
5424             btstack_assert(false);
5425             break;
5426     }
5427     return ERROR_CODE_SUCCESS;
5428 }
5429 
5430 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
5431     int err;
5432     switch (power_mode){
5433         case HCI_POWER_ON:
5434             err = hci_power_control_wake();
5435             if (err) return err;
5436             hci_power_enter_initializing_state();
5437             break;
5438         case HCI_POWER_OFF:
5439             hci_power_enter_halting_state();
5440             break;
5441         case HCI_POWER_SLEEP:
5442             // do nothing
5443             break;
5444         default:
5445             btstack_assert(false);
5446             break;
5447     }
5448     return ERROR_CODE_SUCCESS;
5449 }
5450 
5451 int hci_power_control(HCI_POWER_MODE power_mode){
5452     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
5453     btstack_run_loop_remove_timer(&hci_stack->timeout);
5454     int err = 0;
5455     switch (hci_stack->state){
5456         case HCI_STATE_OFF:
5457             err = hci_power_control_state_off(power_mode);
5458             break;
5459         case HCI_STATE_INITIALIZING:
5460             err = hci_power_control_state_initializing(power_mode);
5461             break;
5462         case HCI_STATE_WORKING:
5463             err = hci_power_control_state_working(power_mode);
5464             break;
5465         case HCI_STATE_HALTING:
5466             err = hci_power_control_state_halting(power_mode);
5467             break;
5468         case HCI_STATE_FALLING_ASLEEP:
5469             err = hci_power_control_state_falling_asleep(power_mode);
5470             break;
5471         case HCI_STATE_SLEEPING:
5472             err = hci_power_control_state_sleeping(power_mode);
5473             break;
5474         default:
5475             btstack_assert(false);
5476             break;
5477     }
5478     if (err != 0){
5479         return err;
5480     }
5481 
5482     // create internal event
5483 	hci_emit_state();
5484 
5485 	// trigger next/first action
5486 	hci_run();
5487 
5488     return 0;
5489 }
5490 
5491 
5492 static void hci_halting_run(void) {
5493 
5494     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5495 
5496     hci_connection_t *connection;
5497 #ifdef ENABLE_BLE
5498 #ifdef ENABLE_LE_PERIPHERAL
5499     bool stop_advertismenets;
5500 #endif
5501 #endif
5502 
5503     switch (hci_stack->substate) {
5504         case HCI_HALTING_CLASSIC_STOP:
5505 #ifdef ENABLE_CLASSIC
5506             if (!hci_can_send_command_packet_now()) return;
5507 
5508             if (hci_stack->connectable || hci_stack->discoverable){
5509                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5510                 hci_send_cmd(&hci_write_scan_enable, 0);
5511                 return;
5512             }
5513 #endif
5514             /* fall through */
5515 
5516         case HCI_HALTING_LE_ADV_STOP:
5517             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5518 
5519 #ifdef ENABLE_BLE
5520 #ifdef ENABLE_LE_PERIPHERAL
5521             if (!hci_can_send_command_packet_now()) return;
5522 
5523             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5524 
5525 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5526             if (hci_le_extended_advertising_supported()){
5527 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5528                 btstack_linked_list_iterator_t it;
5529                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5530                 // stop all periodic advertisements and check if an extended set is active
5531                 while (btstack_linked_list_iterator_has_next(&it)){
5532                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5533                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5534                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5535                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
5536                         return;
5537                     }
5538                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5539                         stop_advertismenets = true;
5540                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5541                     }
5542                 }
5543 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5544                 if (stop_advertismenets){
5545                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5546                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5547                     return;
5548                 }
5549             } else
5550 #else /* ENABLE_LE_PERIPHERAL */
5551             {
5552                 if (stop_advertismenets) {
5553                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5554                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5555                     return;
5556                 }
5557             }
5558 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5559 #endif  /* ENABLE_LE_PERIPHERAL */
5560 #endif  /* ENABLE_BLE */
5561 
5562             /* fall through */
5563 
5564         case HCI_HALTING_LE_SCAN_STOP:
5565             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5566             if (!hci_can_send_command_packet_now()) return;
5567 
5568 #ifdef ENABLE_BLE
5569 #ifdef ENABLE_LE_CENTRAL
5570             if (hci_stack->le_scanning_active){
5571                 hci_le_scan_stop();
5572                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5573                 return;
5574             }
5575 #endif
5576 #endif
5577 
5578             /* fall through */
5579 
5580         case HCI_HALTING_DISCONNECT_ALL:
5581             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5582             if (!hci_can_send_command_packet_now()) return;
5583 
5584             // close all open connections
5585             connection = (hci_connection_t *) hci_stack->connections;
5586             if (connection) {
5587                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5588 
5589                 log_info("HCI_STATE_HALTING, connection %p, handle %u, state %u", connection, con_handle, connection->state);
5590 
5591                 // check state
5592                 switch(connection->state) {
5593                     case SENT_DISCONNECT:
5594                     case RECEIVED_DISCONNECTION_COMPLETE:
5595                         // wait until connection is gone
5596                         return;
5597                     default:
5598                         break;
5599                 }
5600 
5601                 // finally, send the disconnect command
5602                 connection->state = SENT_DISCONNECT;
5603                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5604                 return;
5605             }
5606 
5607 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5608             // stop BIGs and BIG Syncs
5609             if (hci_stack->le_audio_bigs != NULL){
5610                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5611                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5612                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5613                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5614                 return;
5615             }
5616             if (hci_stack->le_audio_big_syncs != NULL){
5617                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5618                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5619                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5620                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5621                 return;
5622             }
5623 #endif
5624 
5625             btstack_run_loop_remove_timer(&hci_stack->timeout);
5626 
5627             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5628             log_info("HCI_STATE_HALTING: wait 50 ms");
5629             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5630             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5631             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5632             btstack_run_loop_add_timer(&hci_stack->timeout);
5633             break;
5634 
5635         case HCI_HALTING_W4_CLOSE_TIMER:
5636             // keep waiting
5637             break;
5638 
5639         case HCI_HALTING_CLOSE:
5640             // close left over connections (that had not been properly closed before)
5641             hci_stack->substate = HCI_HALTING_CLOSE_DISCARDING_CONNECTIONS;
5642             hci_discard_connections();
5643 
5644             log_info("HCI_STATE_HALTING, calling off");
5645 
5646             // switch mode
5647             hci_power_control_off();
5648 
5649             log_info("HCI_STATE_HALTING, emitting state");
5650             hci_emit_state();
5651             log_info("HCI_STATE_HALTING, done");
5652             break;
5653 
5654         default:
5655             break;
5656     }
5657 };
5658 
5659 static void hci_falling_asleep_run(void){
5660     hci_connection_t * connection;
5661     switch(hci_stack->substate) {
5662         case HCI_FALLING_ASLEEP_DISCONNECT:
5663             log_info("HCI_STATE_FALLING_ASLEEP");
5664             // close all open connections
5665             connection =  (hci_connection_t *) hci_stack->connections;
5666             if (connection){
5667 
5668                 // send disconnect
5669                 if (!hci_can_send_command_packet_now()) return;
5670 
5671                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5672                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5673 
5674                 // send disconnected event right away - causes higher layer connections to get closed, too.
5675                 hci_shutdown_connection(connection);
5676                 return;
5677             }
5678 
5679             if (hci_classic_supported()){
5680                 // disable page and inquiry scan
5681                 if (!hci_can_send_command_packet_now()) return;
5682 
5683                 log_info("HCI_STATE_HALTING, disabling inq scans");
5684                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5685 
5686                 // continue in next sub state
5687                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5688                 break;
5689             }
5690 
5691             /* fall through */
5692 
5693             case HCI_FALLING_ASLEEP_COMPLETE:
5694                 log_info("HCI_STATE_HALTING, calling sleep");
5695                 // switch mode
5696                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5697                 hci_emit_state();
5698                 break;
5699 
5700                 default:
5701                     break;
5702     }
5703 }
5704 
5705 #ifdef ENABLE_CLASSIC
5706 
5707 static void hci_update_scan_enable(void){
5708     // 2 = page scan, 1 = inq scan
5709     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5710     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5711     hci_run();
5712 }
5713 
5714 void gap_discoverable_control(uint8_t enable){
5715     if (enable) enable = 1; // normalize argument
5716 
5717     if (hci_stack->discoverable == enable){
5718         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5719         return;
5720     }
5721 
5722     hci_stack->discoverable = enable;
5723     hci_update_scan_enable();
5724 }
5725 
5726 void gap_connectable_control(uint8_t enable){
5727     if (enable) enable = 1; // normalize argument
5728 
5729     // don't emit event
5730     if (hci_stack->connectable == enable) return;
5731 
5732     hci_stack->connectable = enable;
5733     hci_update_scan_enable();
5734 }
5735 #endif
5736 
5737 void gap_local_bd_addr(bd_addr_t address_buffer){
5738     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5739 }
5740 
5741 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5742 static void hci_host_num_completed_packets(void){
5743 
5744     // create packet manually as arrays are not supported and num_commands should not get reduced
5745     hci_reserve_packet_buffer();
5746     uint8_t * packet = hci_get_outgoing_packet_buffer();
5747 
5748     uint16_t size = 0;
5749     uint16_t num_handles = 0;
5750     packet[size++] = 0x35;
5751     packet[size++] = 0x0c;
5752     size++;  // skip param len
5753     size++;  // skip num handles
5754 
5755     // add { handle, packets } entries
5756     btstack_linked_item_t * it;
5757     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5758         hci_connection_t * connection = (hci_connection_t *) it;
5759         if (connection->num_packets_completed){
5760             little_endian_store_16(packet, size, connection->con_handle);
5761             size += 2;
5762             little_endian_store_16(packet, size, connection->num_packets_completed);
5763             size += 2;
5764             //
5765             num_handles++;
5766             connection->num_packets_completed = 0;
5767         }
5768     }
5769 
5770     packet[2] = size - 3;
5771     packet[3] = num_handles;
5772 
5773     hci_stack->host_completed_packets = 0;
5774 
5775     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5776     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5777 
5778     // release packet buffer for synchronous transport implementations
5779     if (hci_transport_synchronous()){
5780         hci_release_packet_buffer();
5781         hci_emit_transport_packet_sent();
5782     }
5783 }
5784 #endif
5785 
5786 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5787     UNUSED(ds);
5788     hci_stack->substate = HCI_HALTING_CLOSE;
5789     hci_halting_run();
5790 }
5791 
5792 static bool hci_run_acl_fragments(void){
5793     if (hci_stack->acl_fragmentation_total_size > 0u) {
5794         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5795         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5796         if (connection) {
5797             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5798                 hci_send_acl_packet_fragments(connection);
5799                 return true;
5800             }
5801         } else {
5802             // connection gone -> discard further fragments
5803             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5804             hci_stack->acl_fragmentation_total_size = 0;
5805             hci_stack->acl_fragmentation_pos = 0;
5806         }
5807     }
5808     return false;
5809 }
5810 
5811 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5812 static bool hci_run_iso_fragments(void){
5813     if (hci_stack->iso_fragmentation_total_size > 0u) {
5814         // TODO: flow control
5815         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5816             hci_send_iso_packet_fragments();
5817             return true;
5818         }
5819     }
5820     return false;
5821 }
5822 #endif
5823 
5824 #ifdef ENABLE_CLASSIC
5825 
5826 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5827 static bool hci_classic_operation_active(void) {
5828     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5829         return true;
5830     }
5831     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5832         return true;
5833     }
5834     btstack_linked_item_t * it;
5835     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5836         hci_connection_t *connection = (hci_connection_t *) it;
5837         switch (connection->state) {
5838             case SENT_CREATE_CONNECTION:
5839             case SENT_CANCEL_CONNECTION:
5840             case SENT_DISCONNECT:
5841                 return true;
5842             default:
5843                 break;
5844         }
5845     }
5846     return false;
5847 }
5848 #endif
5849 
5850 static bool hci_run_general_gap_classic(void){
5851 
5852     // assert stack is working and classic is active
5853     if (hci_classic_supported() == false)      return false;
5854     if (hci_stack->state != HCI_STATE_WORKING) return false;
5855 
5856     // decline incoming connections
5857     if (hci_stack->decline_reason){
5858         uint8_t reason = hci_stack->decline_reason;
5859         hci_stack->decline_reason = 0;
5860         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5861         return true;
5862     }
5863 
5864     if (hci_stack->gap_tasks_classic != 0){
5865         hci_run_gap_tasks_classic();
5866         return true;
5867     }
5868 
5869     // start/stop inquiry
5870     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5871 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5872         if (hci_classic_operation_active() == false)
5873 #endif
5874         {
5875             uint8_t duration = hci_stack->inquiry_state;
5876             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5877             if (hci_stack->inquiry_max_period_length != 0){
5878                 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);
5879             } else {
5880                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5881             }
5882             return true;
5883         }
5884     }
5885     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5886         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5887         hci_send_cmd(&hci_inquiry_cancel);
5888         return true;
5889     }
5890 
5891     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5892         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5893         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5894         return true;
5895     }
5896 
5897     // remote name request
5898     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5899 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5900         if (hci_classic_operation_active() == false)
5901 #endif
5902         {
5903             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5904             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5905                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5906             return true;
5907         }
5908     }
5909 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5910     // Local OOB data
5911     if (hci_stack->classic_read_local_oob_data){
5912         hci_stack->classic_read_local_oob_data = false;
5913         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5914             hci_send_cmd(&hci_read_local_extended_oob_data);
5915         } else {
5916             hci_send_cmd(&hci_read_local_oob_data);
5917         }
5918     }
5919 #endif
5920     // pairing
5921     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5922         uint8_t state = hci_stack->gap_pairing_state;
5923         uint8_t pin_code[PIN_CODE_LEN];
5924         switch (state){
5925             case GAP_PAIRING_STATE_SEND_PIN:
5926                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5927                 memset(pin_code, 0, 16);
5928                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5929                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5930                 break;
5931             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5932                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5933                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5934                 break;
5935             case GAP_PAIRING_STATE_SEND_PASSKEY:
5936                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5937                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5938                 break;
5939             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5940                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5941                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5942                 break;
5943             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5944                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5945                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5946                 break;
5947             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5948                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5949                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5950                 break;
5951             default:
5952                 break;
5953         }
5954         return true;
5955     }
5956     return false;
5957 }
5958 #endif
5959 
5960 #ifdef ENABLE_BLE
5961 
5962 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5963 static uint8_t hci_le_num_phys(uint8_t phys){
5964     const uint8_t num_bits_set[] = { 0, 1, 1, 2, 1, 2, 2, 3 };
5965     btstack_assert(phys);
5966     return num_bits_set[phys];
5967 }
5968 #endif
5969 
5970 #ifdef ENABLE_LE_CENTRAL
5971 static void hci_le_scan_stop(void){
5972 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5973     if (hci_le_extended_advertising_supported()) {
5974             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5975     } else
5976 #endif
5977     {
5978         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5979     }
5980 }
5981 
5982 static void
5983 hci_send_le_create_connection(uint8_t initiator_filter_policy, bd_addr_type_t address_type, uint8_t *address) {
5984 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5985     if (hci_le_extended_advertising_supported()) {
5986         // prepare arrays for all phys (LE Coded, LE 1M, LE 2M PHY)
5987         uint16_t le_connection_scan_interval[3];
5988         uint16_t le_connection_scan_window[3];
5989         uint16_t le_connection_interval_min[3];
5990         uint16_t le_connection_interval_max[3];
5991         uint16_t le_connection_latency[3];
5992         uint16_t le_supervision_timeout[3];
5993         uint16_t le_minimum_ce_length[3];
5994         uint16_t le_maximum_ce_length[3];
5995 
5996         uint8_t i;
5997         uint8_t num_phys = hci_le_num_phys(hci_stack->le_connection_phys);
5998         for (i=0;i<num_phys;i++){
5999             le_connection_scan_interval[i] = hci_stack->le_connection_scan_interval;
6000             le_connection_scan_window[i]   = hci_stack->le_connection_scan_window;
6001             le_connection_interval_min[i]  = hci_stack->le_connection_interval_min;
6002             le_connection_interval_max[i]  = hci_stack->le_connection_interval_max;
6003             le_connection_latency[i]       = hci_stack->le_connection_latency;
6004             le_supervision_timeout[i]      = hci_stack->le_supervision_timeout;
6005             le_minimum_ce_length[i]        = hci_stack->le_minimum_ce_length;
6006             le_maximum_ce_length[i]        = hci_stack->le_maximum_ce_length;
6007         }
6008         hci_send_cmd(&hci_le_extended_create_connection,
6009                      initiator_filter_policy,
6010                      hci_stack->le_connection_own_addr_type,   // our addr type:
6011                      address_type,                  // peer address type
6012                      address,                       // peer bd addr
6013                      hci_stack->le_connection_phys, // initiating PHY
6014                      le_connection_scan_interval,   // conn scan interval
6015                      le_connection_scan_window,     // conn scan windows
6016                      le_connection_interval_min,    // conn interval min
6017                      le_connection_interval_max,    // conn interval max
6018                      le_connection_latency,         // conn latency
6019                      le_supervision_timeout,        // conn latency
6020                      le_minimum_ce_length,          // min ce length
6021                      le_maximum_ce_length           // max ce length
6022         );
6023     } else
6024 #endif
6025     {
6026         hci_send_cmd(&hci_le_create_connection,
6027                      hci_stack->le_connection_scan_interval,  // conn scan interval
6028                      hci_stack->le_connection_scan_window,    // conn scan windows
6029                      initiator_filter_policy,                 // don't use whitelist
6030                      address_type,                            // peer address type
6031                      address,                                 // peer bd addr
6032                      hci_stack->le_connection_own_addr_type,  // our addr type:
6033                      hci_stack->le_connection_interval_min,   // conn interval min
6034                      hci_stack->le_connection_interval_max,   // conn interval max
6035                      hci_stack->le_connection_latency,        // conn latency
6036                      hci_stack->le_supervision_timeout,       // conn latency
6037                      hci_stack->le_minimum_ce_length,         // min ce length
6038                      hci_stack->le_maximum_ce_length          // max ce length
6039         );
6040     }
6041 }
6042 #endif
6043 
6044 #ifdef ENABLE_LE_PERIPHERAL
6045 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6046 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
6047     uint8_t  operation = 0;
6048     if (pos == 0){
6049         // first fragment or complete data
6050         operation |= 1;
6051     }
6052     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
6053         // last fragment or complete data
6054         operation |= 2;
6055     }
6056     return operation;
6057 }
6058 #endif
6059 #endif
6060 
6061 static bool hci_run_general_gap_le(void){
6062 
6063     btstack_linked_list_iterator_t lit;
6064 
6065 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6066     if (hci_stack->le_resolvable_private_address_update_s > 0){
6067         uint16_t update_s = hci_stack->le_resolvable_private_address_update_s;
6068         hci_stack->le_resolvable_private_address_update_s = 0;
6069         hci_send_cmd(&hci_le_set_resolvable_private_address_timeout, update_s);
6070         return true;
6071     }
6072 #endif
6073 
6074     // Phase 1: collect what to stop
6075 
6076 #ifdef ENABLE_LE_CENTRAL
6077     bool scanning_stop = false;
6078     bool connecting_stop = false;
6079 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6080 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6081     bool periodic_sync_stop = false;
6082 #endif
6083 #endif
6084 #endif
6085 
6086 #ifdef ENABLE_LE_PERIPHERAL
6087     bool advertising_stop = false;
6088 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6089     le_advertising_set_t * advertising_stop_set = NULL;
6090 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6091     bool periodic_advertising_stop = false;
6092 #endif
6093 #endif
6094 #endif
6095 
6096     // check if own address changes
6097     uint8_t address_change_mask = LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
6098     bool random_address_change = (hci_stack->le_advertisements_todo & address_change_mask) != 0;
6099 
6100     // check if whitelist needs modification
6101     bool whitelist_modification_pending = false;
6102     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6103     while (btstack_linked_list_iterator_has_next(&lit)){
6104         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6105         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
6106             whitelist_modification_pending = true;
6107             break;
6108         }
6109     }
6110 
6111     // check if resolving list needs modification
6112     bool resolving_list_modification_pending = false;
6113 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6114     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
6115 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
6116         resolving_list_modification_pending = true;
6117     }
6118 #endif
6119 
6120 #ifdef ENABLE_LE_CENTRAL
6121 
6122 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6123     // check if periodic advertiser list needs modification
6124     bool periodic_list_modification_pending = false;
6125     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6126     while (btstack_linked_list_iterator_has_next(&lit)){
6127         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6128         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
6129             periodic_list_modification_pending = true;
6130             break;
6131         }
6132     }
6133 #endif
6134 
6135     // scanning control
6136     if (hci_stack->le_scanning_active) {
6137         // stop if:
6138         // - parameter change required
6139         // - it's disabled
6140         // - whitelist change required but used for scanning
6141         // - resolving list modified
6142         // - own address changes
6143         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
6144         if ((hci_stack->le_scanning_param_update) ||
6145             !hci_stack->le_scanning_enabled ||
6146             (scanning_uses_whitelist && whitelist_modification_pending) ||
6147             resolving_list_modification_pending ||
6148             random_address_change){
6149 
6150             scanning_stop = true;
6151         }
6152     }
6153 
6154     // connecting control
6155     bool connecting_with_whitelist;
6156     switch (hci_stack->le_connecting_state){
6157         case LE_CONNECTING_DIRECT:
6158         case LE_CONNECTING_WHITELIST:
6159             // stop connecting if:
6160             // - connecting uses white and whitelist modification pending
6161             // - if it got disabled
6162             // - resolving list modified
6163             // - own address changes
6164             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
6165             if ((connecting_with_whitelist && whitelist_modification_pending) ||
6166                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
6167                 resolving_list_modification_pending ||
6168                 random_address_change) {
6169 
6170                 connecting_stop = true;
6171             }
6172             break;
6173         default:
6174             break;
6175     }
6176 
6177 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6178 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6179     // periodic sync control
6180     bool sync_with_advertiser_list;
6181     switch(hci_stack->le_periodic_sync_state){
6182         case LE_CONNECTING_DIRECT:
6183         case LE_CONNECTING_WHITELIST:
6184             // stop sync if:
6185             // - sync with advertiser list and advertiser list modification pending
6186             // - if it got disabled
6187             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
6188             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
6189                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
6190                 periodic_sync_stop = true;
6191             }
6192             break;
6193         default:
6194             break;
6195     }
6196 #endif
6197 #endif
6198 
6199 #endif /* ENABLE_LE_CENTRAL */
6200 
6201 #ifdef ENABLE_LE_PERIPHERAL
6202     // le advertisement control
6203     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
6204         // stop if:
6205         // - parameter change required
6206         // - random address used in advertising and changes
6207         // - it's disabled
6208         // - whitelist change required but used for advertisement filter policy
6209         // - resolving list modified
6210         // - own address changes
6211         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
6212         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
6213         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
6214         if (advertising_change ||
6215             (advertising_uses_random_address && random_address_change) ||
6216             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
6217             (advertising_uses_whitelist && whitelist_modification_pending) ||
6218             resolving_list_modification_pending ||
6219             random_address_change) {
6220 
6221             advertising_stop = true;
6222         }
6223     }
6224 
6225 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6226     if (hci_le_extended_advertising_supported() && (advertising_stop == false)){
6227         btstack_linked_list_iterator_t it;
6228         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6229         while (btstack_linked_list_iterator_has_next(&it)){
6230             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6231             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
6232                 // stop if:
6233                 // - parameter change required
6234                 // - random address used in connectable advertising and changes
6235                 // - it's disabled
6236                 // - whitelist change required but used for advertisement filter policy
6237                 // - resolving list modified
6238                 // - own address changes
6239                 // - advertisement set will be removed
6240                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
6241                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
6242                 bool advertising_uses_random_address =
6243                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
6244                         advertising_connectable;
6245                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
6246                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
6247                 bool advertising_set_random_address_change =
6248                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
6249                 bool advertising_set_will_be_removed =
6250                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
6251                 if (advertising_parameter_change ||
6252                     (advertising_uses_random_address && advertising_set_random_address_change) ||
6253                     (advertising_enabled == false) ||
6254                     (advertising_uses_whitelist && whitelist_modification_pending) ||
6255                     resolving_list_modification_pending ||
6256                     advertising_set_will_be_removed) {
6257 
6258                     advertising_stop = true;
6259                     advertising_stop_set = advertising_set;
6260                     break;
6261                 }
6262             }
6263 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6264             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
6265                 // stop if:
6266                 // - it's disabled
6267                 // - parameter change required
6268                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
6269                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
6270                 if ((periodic_enabled == false) || periodic_parameter_change){
6271                     periodic_advertising_stop = true;
6272                     advertising_stop_set = advertising_set;
6273                 }
6274             }
6275 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6276         }
6277     }
6278 #endif
6279 
6280 #endif
6281 
6282 
6283     // Phase 2: stop everything that should be off during modifications
6284 
6285 
6286     // 2.1 Outgoing connection
6287 #ifdef ENABLE_LE_CENTRAL
6288     if (connecting_stop){
6289         hci_send_cmd(&hci_le_create_connection_cancel);
6290         return true;
6291     }
6292 #endif
6293 
6294     // 2.2 Scanning
6295 #ifdef ENABLE_LE_CENTRAL
6296     if (scanning_stop){
6297         hci_stack->le_scanning_active = false;
6298         hci_le_scan_stop();
6299         return true;
6300     }
6301 
6302     // 2.3 Periodic Sync
6303 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6304     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
6305         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
6306         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
6307         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
6308         return true;
6309     }
6310 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6311     if (periodic_sync_stop){
6312         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
6313         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
6314         return true;
6315     }
6316 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6317 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6318 #endif /* ENABLE_LE_CENTRAL */
6319 
6320     // 2.4 Advertising: legacy, extended, periodic
6321 #ifdef ENABLE_LE_PERIPHERAL
6322     if (advertising_stop){
6323 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6324         if (hci_le_extended_advertising_supported()) {
6325             uint8_t advertising_stop_handle;
6326             if (advertising_stop_set != NULL){
6327                 advertising_stop_handle = advertising_stop_set->advertising_handle;
6328                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6329             } else {
6330                 advertising_stop_handle = 0;
6331                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6332             }
6333             const uint8_t advertising_handles[] = { advertising_stop_handle };
6334             const uint16_t durations[] = { 0 };
6335             const uint16_t max_events[] = { 0 };
6336             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
6337         } else
6338 #endif
6339         {
6340             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6341             hci_send_cmd(&hci_le_set_advertise_enable, 0);
6342         }
6343         return true;
6344     }
6345 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6346 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6347     if (periodic_advertising_stop){
6348         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6349         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
6350         return true;
6351     }
6352 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6353 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6354 #endif /* ENABLE_LE_PERIPHERAL */
6355 
6356 
6357     // Phase 3: modify
6358 
6359     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY) {
6360         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
6361         // GAP Privacy, notify clients upon upcoming random address change
6362         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
6363         gap_privacy_clients_notify(hci_stack->le_random_address);
6364     }
6365 
6366     // - wait until privacy update completed
6367     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PRIVACY_PENDING) != 0){
6368         return false;
6369     }
6370 
6371     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS){
6372         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6373         hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
6374 #ifdef ENABLE_LE_SET_ADV_PARAMS_ON_RANDOM_ADDRESS_CHANGE
6375         // workaround: on some Controllers, address in advertisements is updated only after next dv params set
6376         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6377 #endif
6378         return true;
6379     }
6380 
6381 #ifdef ENABLE_LE_CENTRAL
6382     if (hci_stack->le_scanning_param_update){
6383         hci_stack->le_scanning_param_update = false;
6384 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6385         if (hci_le_extended_advertising_supported()){
6386             // prepare arrays for all phys (LE Coded and LE 1M PHY)
6387             uint8_t  scan_types[2];
6388             uint16_t scan_intervals[2];
6389             uint16_t scan_windows[2];
6390 
6391             uint8_t i;
6392             uint8_t num_phys = hci_le_num_phys(hci_stack->le_scan_phys);
6393             for (i=0;i<num_phys;i++){
6394                 scan_types[i]     = hci_stack->le_scan_type;
6395                 scan_intervals[i] = hci_stack->le_scan_interval;
6396                 scan_windows[i]   = hci_stack->le_scan_window;
6397             }
6398             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
6399                          hci_stack->le_scan_filter_policy, hci_stack->le_scan_phys, scan_types, scan_intervals, scan_windows);
6400         } else
6401 #endif
6402         {
6403             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
6404                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
6405         }
6406         return true;
6407     }
6408 #endif
6409 
6410 #ifdef ENABLE_LE_PERIPHERAL
6411     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
6412         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6413         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
6414 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6415         if (hci_le_extended_advertising_supported()){
6416             // map advertisment type to advertising event properties
6417             uint16_t adv_event_properties = 0;
6418             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
6419             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
6420                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
6421             }
6422             hci_stack->le_advertising_set_in_current_command = 0;
6423             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6424                          0,
6425                          adv_event_properties,
6426                          hci_stack->le_advertisements_interval_min,
6427                          hci_stack->le_advertisements_interval_max,
6428                          hci_stack->le_advertisements_channel_map,
6429                          hci_stack->le_advertisements_own_addr_type,
6430                          hci_stack->le_advertisements_direct_address_type,
6431                          hci_stack->le_advertisements_direct_address,
6432                          hci_stack->le_advertisements_filter_policy,
6433                          0x7f,  // tx power: no preference
6434                          0x01,  // primary adv phy: LE 1M
6435                          0,     // secondary adv max skip
6436                          0x01,  // secondary adv phy
6437                          0,     // adv sid
6438                          0      // scan request notification
6439                          );
6440         } else
6441 #endif
6442         {
6443             hci_send_cmd(&hci_le_set_advertising_parameters,
6444                          hci_stack->le_advertisements_interval_min,
6445                          hci_stack->le_advertisements_interval_max,
6446                          hci_stack->le_advertisements_type,
6447                          hci_stack->le_advertisements_own_addr_type,
6448                          hci_stack->le_advertisements_direct_address_type,
6449                          hci_stack->le_advertisements_direct_address,
6450                          hci_stack->le_advertisements_channel_map,
6451                          hci_stack->le_advertisements_filter_policy);
6452         }
6453         return true;
6454     }
6455 
6456 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6457     // assumption: only set if extended advertising is supported
6458     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0) != 0){
6459         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
6460         hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
6461         return true;
6462     }
6463 #endif
6464 
6465     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
6466         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6467         uint8_t adv_data_clean[31];
6468         memset(adv_data_clean, 0, sizeof(adv_data_clean));
6469         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
6470                      hci_stack->le_advertisements_data_len);
6471         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
6472 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6473         if (hci_le_extended_advertising_supported()){
6474             hci_stack->le_advertising_set_in_current_command = 0;
6475             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
6476         } else
6477 #endif
6478         {
6479             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
6480         }
6481         return true;
6482     }
6483 
6484     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
6485         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6486         uint8_t scan_data_clean[31];
6487         memset(scan_data_clean, 0, sizeof(scan_data_clean));
6488         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
6489                      hci_stack->le_scan_response_data_len);
6490         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6491 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6492         if (hci_le_extended_advertising_supported()){
6493             hci_stack->le_advertising_set_in_current_command = 0;
6494             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6495         } else
6496 #endif
6497         {
6498             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6499         }
6500         return true;
6501     }
6502 
6503 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6504     if (hci_le_extended_advertising_supported()) {
6505         btstack_linked_list_iterator_t it;
6506         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6507         while (btstack_linked_list_iterator_has_next(&it)){
6508             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6509             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6510                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6511                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6512                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6513                 return true;
6514             }
6515             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6516                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6517                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6518                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6519                              advertising_set->advertising_handle,
6520                              advertising_set->extended_params.advertising_event_properties,
6521                              advertising_set->extended_params.primary_advertising_interval_min,
6522                              advertising_set->extended_params.primary_advertising_interval_max,
6523                              advertising_set->extended_params.primary_advertising_channel_map,
6524                              advertising_set->extended_params.own_address_type,
6525                              advertising_set->extended_params.peer_address_type,
6526                              advertising_set->extended_params.peer_address,
6527                              advertising_set->extended_params.advertising_filter_policy,
6528                              advertising_set->extended_params.advertising_tx_power,
6529                              advertising_set->extended_params.primary_advertising_phy,
6530                              advertising_set->extended_params.secondary_advertising_max_skip,
6531                              advertising_set->extended_params.secondary_advertising_phy,
6532                              advertising_set->extended_params.advertising_sid,
6533                              advertising_set->extended_params.scan_request_notification_enable
6534                 );
6535                 return true;
6536             }
6537             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
6538                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6539                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
6540                 return true;
6541             }
6542             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6543                 uint16_t pos = advertising_set->adv_data_pos;
6544                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6545                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6546                 if ((operation & 0x02) != 0){
6547                     // last fragment or complete data
6548                     operation |= 2;
6549                     advertising_set->adv_data_pos = 0;
6550                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6551                 } else {
6552                     advertising_set->adv_data_pos += data_to_upload;
6553                 }
6554                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6555                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6556                 return true;
6557             }
6558             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6559                 uint16_t pos = advertising_set->scan_data_pos;
6560                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6561                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6562                 if ((operation & 0x02) != 0){
6563                     advertising_set->scan_data_pos = 0;
6564                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6565                 } else {
6566                     advertising_set->scan_data_pos += data_to_upload;
6567                 }
6568                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6569                 hci_send_cmd(&hci_le_set_extended_scan_response_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
6570                 return true;
6571             }
6572 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6573             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
6574                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
6575                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6576                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
6577                              advertising_set->advertising_handle,
6578                              advertising_set->periodic_params.periodic_advertising_interval_min,
6579                              advertising_set->periodic_params.periodic_advertising_interval_max,
6580                              advertising_set->periodic_params.periodic_advertising_properties);
6581                 return true;
6582             }
6583             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
6584                 uint16_t pos = advertising_set->periodic_data_pos;
6585                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
6586                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6587                 if ((operation & 0x02) != 0){
6588                     // last fragment or complete data
6589                     operation |= 2;
6590                     advertising_set->periodic_data_pos = 0;
6591                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
6592                 } else {
6593                     advertising_set->periodic_data_pos += data_to_upload;
6594                 }
6595                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6596                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
6597                 return true;
6598             }
6599 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6600         }
6601     }
6602 #endif
6603 
6604 #endif
6605 
6606 #ifdef ENABLE_LE_CENTRAL
6607     // if connect with whitelist was active and is not cancelled yet, wait until next time
6608     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
6609 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6610     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
6611     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
6612 #endif
6613 #endif
6614 
6615     // LE Whitelist Management
6616     if (whitelist_modification_pending){
6617         // add/remove entries
6618         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6619         while (btstack_linked_list_iterator_has_next(&lit)){
6620             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6621 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
6622 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6623                 entry->state &= ~LE_WHITELIST_ON_CONTROLLER;
6624                 bd_addr_type_t address_type = entry->address_type;
6625                 bd_addr_t address;
6626                 memcpy(address, entry->address, 6);
6627                 if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) == 0){
6628                     // remove from whitelist if not scheduled for re-addition
6629                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6630                     btstack_memory_whitelist_entry_free(entry);
6631                 }
6632 				hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
6633 				return true;
6634 			}
6635             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
6636 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
6637                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
6638                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
6639                 return true;
6640             }
6641         }
6642     }
6643 
6644 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6645     // LE Resolving List Management
6646     if (resolving_list_modification_pending) {
6647 		uint16_t i;
6648         uint8_t null_16[16];
6649         uint8_t local_irk_flipped[16];
6650         const uint8_t *local_irk;
6651 		switch (hci_stack->le_resolving_list_state) {
6652 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
6653 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6654 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
6655 				return true;
6656 			case LE_RESOLVING_LIST_READ_SIZE:
6657 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
6658 				hci_send_cmd(&hci_le_read_resolving_list_size);
6659 				return true;
6660 			case LE_RESOLVING_LIST_SEND_CLEAR:
6661 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SET_IRK;
6662 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6663 							  sizeof(hci_stack->le_resolving_list_add_entries));
6664                 (void) memset(hci_stack->le_resolving_list_set_privacy_mode, 0xff,
6665                               sizeof(hci_stack->le_resolving_list_set_privacy_mode));
6666 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6667 							  sizeof(hci_stack->le_resolving_list_remove_entries));
6668 				hci_send_cmd(&hci_le_clear_resolving_list);
6669 				return true;
6670             case LE_RESOLVING_LIST_SET_IRK:
6671                 // set IRK used by RPA for undirected advertising
6672                 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
6673                 local_irk = gap_get_persistent_irk();
6674                 reverse_128(local_irk, local_irk_flipped);
6675                 memset(null_16, 0, sizeof(null_16));
6676                 hci_send_cmd(&hci_le_add_device_to_resolving_list, BD_ADDR_TYPE_LE_PUBLIC, null_16,
6677                              null_16, local_irk_flipped);
6678                 return true;
6679 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
6680                 // first remove old entries
6681 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6682 					uint8_t offset = i >> 3;
6683 					uint8_t mask = 1 << (i & 7);
6684 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
6685 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
6686 					bd_addr_t peer_identity_addreses;
6687 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6688 					sm_key_t peer_irk;
6689 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6690 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6691 
6692 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6693 					// trigger whitelist entry 'update' (work around for controller bug)
6694 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6695 					while (btstack_linked_list_iterator_has_next(&lit)) {
6696 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6697 						if (entry->address_type != peer_identity_addr_type) continue;
6698 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6699 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6700 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6701 					}
6702 #endif
6703 
6704 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6705 								 peer_identity_addreses);
6706 					return true;
6707 				}
6708 
6709                 // then add new entries
6710 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6711 					uint8_t offset = i >> 3;
6712 					uint8_t mask = 1 << (i & 7);
6713 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
6714 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
6715 					bd_addr_t peer_identity_addreses;
6716 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6717 					sm_key_t peer_irk;
6718 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6719 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6720                     if (btstack_is_null(peer_irk, 16)) continue;
6721 					local_irk = gap_get_persistent_irk();
6722 					// command uses format specifier 'P' that stores 16-byte value without flip
6723 					uint8_t peer_irk_flipped[16];
6724 					reverse_128(local_irk, local_irk_flipped);
6725 					reverse_128(peer_irk, peer_irk_flipped);
6726 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6727 								 peer_irk_flipped, local_irk_flipped);
6728 					return true;
6729 				}
6730 
6731                 // finally, set privacy mode
6732                 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6733                     uint8_t offset = i >> 3;
6734                     uint8_t mask = 1 << (i & 7);
6735                     if ((hci_stack->le_resolving_list_set_privacy_mode[offset] & mask) == 0) continue;
6736                     hci_stack->le_resolving_list_set_privacy_mode[offset] &= ~mask;
6737                     if (hci_stack->le_privacy_mode == LE_PRIVACY_MODE_NETWORK) {
6738                         // Network Privacy Mode is default
6739                         continue;
6740                     }
6741                     bd_addr_t peer_identity_address;
6742                     int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6743                     sm_key_t peer_irk;
6744                     le_device_db_info(i, &peer_identity_addr_type, peer_identity_address, peer_irk);
6745                     if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6746                     if (btstack_is_null(peer_irk, 16)) continue;
6747                     // command uses format specifier 'P' that stores 16-byte value without flip
6748                     uint8_t peer_irk_flipped[16];
6749                     reverse_128(peer_irk, peer_irk_flipped);
6750                     hci_send_cmd(&hci_le_set_privacy_mode, peer_identity_addr_type, peer_identity_address, hci_stack->le_privacy_mode);
6751                     return true;
6752                 }
6753 				break;
6754 
6755 			default:
6756 				break;
6757 		}
6758         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6759 	}
6760 #endif
6761 
6762 #ifdef ENABLE_LE_CENTRAL
6763 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6764     // LE Whitelist Management
6765     if (periodic_list_modification_pending){
6766         // add/remove entries
6767         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6768         while (btstack_linked_list_iterator_has_next(&lit)){
6769             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6770             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6771                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6772                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6773                 return true;
6774             }
6775             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6776                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6777                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
6778                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6779                 return true;
6780             }
6781             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6782                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6783                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6784             }
6785         }
6786     }
6787 #endif
6788 #endif
6789 
6790 #ifdef ENABLE_LE_CENTRAL
6791 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6792 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6793     if (hci_stack->le_past_set_default_params){
6794         hci_stack->le_past_set_default_params = false;
6795         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
6796                      hci_stack->le_past_mode,
6797                      hci_stack->le_past_skip,
6798                      hci_stack->le_past_sync_timeout,
6799                      hci_stack->le_past_cte_type);
6800         return true;
6801     }
6802 #endif
6803 #endif
6804 #endif
6805 
6806     // post-pone all actions until stack is fully working
6807     if (hci_stack->state != HCI_STATE_WORKING) return false;
6808 
6809     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6810     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6811 
6812     // Phase 4: restore state
6813 
6814 #ifdef ENABLE_LE_CENTRAL
6815     // re-start scanning
6816     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6817         hci_stack->le_scanning_active = true;
6818 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6819         if (hci_le_extended_advertising_supported()){
6820             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
6821         } else
6822 #endif
6823         {
6824             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
6825         }
6826         return true;
6827     }
6828 #endif
6829 
6830 #ifdef ENABLE_LE_CENTRAL
6831     // re-start connecting
6832     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6833         bd_addr_t null_addr;
6834         memset(null_addr, 0, 6);
6835         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6836         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6837         hci_send_le_create_connection(1, 0, null_addr);
6838         return true;
6839     }
6840 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6841     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6842         switch(hci_stack->le_periodic_sync_request){
6843             case LE_CONNECTING_DIRECT:
6844             case LE_CONNECTING_WHITELIST:
6845                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6846                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6847                              hci_stack->le_periodic_sync_options,
6848                              hci_stack->le_periodic_sync_advertising_sid,
6849                              hci_stack->le_periodic_sync_advertiser_address_type,
6850                              hci_stack->le_periodic_sync_advertiser_address,
6851                              hci_stack->le_periodic_sync_skip,
6852                              hci_stack->le_periodic_sync_timeout,
6853                              hci_stack->le_periodic_sync_cte_type);
6854                 return true;
6855             default:
6856                 break;
6857         }
6858     }
6859 #endif
6860 #endif
6861 
6862 #ifdef ENABLE_LE_PERIPHERAL
6863     // re-start advertising
6864     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6865         // check if advertisements should be enabled given
6866         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6867         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6868 
6869 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6870         if (hci_le_extended_advertising_supported()){
6871             const uint8_t advertising_handles[] = { 0 };
6872             const uint16_t durations[] = { 0 };
6873             const uint16_t max_events[] = { 0 };
6874             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6875         } else
6876 #endif
6877         {
6878             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6879         }
6880         return true;
6881     }
6882 
6883 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6884     if (hci_le_extended_advertising_supported()) {
6885         btstack_linked_list_iterator_t it;
6886         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6887         while (btstack_linked_list_iterator_has_next(&it)) {
6888             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6889             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6890                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6891                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6892                 const uint16_t durations[] = { advertising_set->enable_timeout };
6893                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6894                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6895                 return true;
6896             }
6897 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6898             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6899                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6900                 uint8_t enable = 1;
6901                 if (advertising_set->periodic_include_adi){
6902                     enable |= 2;
6903                 }
6904                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6905                 return true;
6906             }
6907 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6908         }
6909     }
6910 #endif
6911 #endif
6912 
6913     return false;
6914 }
6915 
6916 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6917 static bool hci_run_iso_tasks(void){
6918     btstack_linked_list_iterator_t it;
6919 
6920     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
6921         return false;
6922     }
6923 
6924     // BIG
6925     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6926     while (btstack_linked_list_iterator_has_next(&it)){
6927         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6928         switch (big->state){
6929             case LE_AUDIO_BIG_STATE_CREATE:
6930                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
6931                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6932                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6933                 hci_send_cmd(&hci_le_create_big,
6934                              big->params->big_handle,
6935                              big->params->advertising_handle,
6936                              big->params->num_bis,
6937                              big->params->sdu_interval_us,
6938                              big->params->max_sdu,
6939                              big->params->max_transport_latency_ms,
6940                              big->params->rtn,
6941                              big->params->phy,
6942                              big->params->packing,
6943                              big->params->framing,
6944                              big->params->encryption,
6945                              big->params->broadcast_code);
6946                 return true;
6947             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6948                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6949                 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);
6950                 return true;
6951             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6952                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6953                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6954                 return true;
6955             case LE_AUDIO_BIG_STATE_TERMINATE:
6956                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6957                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6958                 return true;
6959             default:
6960                 break;
6961         }
6962     }
6963 
6964     // BIG Sync
6965     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6966     while (btstack_linked_list_iterator_has_next(&it)){
6967         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6968         switch (big_sync->state){
6969             case LE_AUDIO_BIG_STATE_CREATE:
6970                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
6971                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6972                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6973                 hci_send_cmd(&hci_le_big_create_sync,
6974                              big_sync->params->big_handle,
6975                              big_sync->params->sync_handle,
6976                              big_sync->params->encryption,
6977                              big_sync->params->broadcast_code,
6978                              big_sync->params->mse,
6979                              big_sync->params->big_sync_timeout_10ms,
6980                              big_sync->params->num_bis,
6981                              big_sync->params->bis_indices);
6982                 return true;
6983             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6984                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6985                 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);
6986                 return true;
6987             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6988                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6989                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6990                 return true;
6991             case LE_AUDIO_BIG_STATE_TERMINATE:
6992                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6993                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6994                 return true;
6995             default:
6996                 break;
6997         }
6998     }
6999 
7000     // CIG
7001     bool cig_active;
7002     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
7003     while (btstack_linked_list_iterator_has_next(&it)) {
7004         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
7005         uint8_t i;
7006         // Set CIG Parameters
7007         uint8_t cis_id[MAX_NR_CIS];
7008         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
7009         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
7010         uint8_t phy_c_to_p[MAX_NR_CIS];
7011         uint8_t phy_p_to_c[MAX_NR_CIS];
7012         uint8_t rtn_c_to_p[MAX_NR_CIS];
7013         uint8_t rtn_p_to_c[MAX_NR_CIS];
7014         switch (cig->state) {
7015             case LE_AUDIO_CIG_STATE_CREATE:
7016                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7017                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7018                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
7019                 le_audio_cig_params_t * params = cig->params;
7020                 for (i = 0; i < params->num_cis; i++) {
7021                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
7022                     cis_id[i]         = cis_params->cis_id;
7023                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
7024                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
7025                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
7026                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
7027                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
7028                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
7029                 }
7030                 hci_send_cmd(&hci_le_set_cig_parameters,
7031                              cig->cig_id,
7032                              params->sdu_interval_c_to_p,
7033                              params->sdu_interval_p_to_c,
7034                              params->worst_case_sca,
7035                              params->packing,
7036                              params->framing,
7037                              params->max_transport_latency_c_to_p,
7038                              params->max_transport_latency_p_to_c,
7039                              params->num_cis,
7040                              cis_id,
7041                              max_sdu_c_to_p,
7042                              max_sdu_p_to_c,
7043                              phy_c_to_p,
7044                              phy_p_to_c,
7045                              rtn_c_to_p,
7046                              rtn_p_to_c
7047                 );
7048                 return true;
7049             case LE_AUDIO_CIG_STATE_CREATE_CIS:
7050                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7051                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7052                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
7053                 for (i=0;i<cig->num_cis;i++){
7054                     cig->cis_setup_active[i] = true;
7055                 }
7056                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
7057                 return true;
7058             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
7059                 while (cig->state_vars.next_cis < (cig->num_cis * 2)){
7060                     // find next path to setup
7061                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
7062                     if (cig->cis_established[cis_index] == false) {
7063                         continue;
7064                     }
7065                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
7066                     bool setup = true;
7067                     if (cis_direction == 0){
7068                         // 0 - input - host to controller
7069                         // we are central => central to peripheral
7070                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
7071                     } else {
7072                         // 1 - output - controller to host
7073                         // we are central => peripheral to central
7074                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
7075                     }
7076                     if (setup){
7077                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7078                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7079                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
7080                         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);
7081                         return true;
7082                     }
7083                     cig->state_vars.next_cis++;
7084                 }
7085                 // emit done
7086                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
7087                 break;
7088             case LE_AUDIO_CIG_STATE_REMOVE:
7089                 // check if CIG Active
7090                 cig_active = false;
7091                 for (i = 0; i < cig->num_cis; i++) {
7092                     if (cig->cis_con_handles[i] != HCI_CON_HANDLE_INVALID){
7093                         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
7094                         if (stream != NULL){
7095                             cig_active = true;
7096                             break;
7097                         }
7098                     }
7099                 }
7100                 if (cig_active == false){
7101                     btstack_linked_list_iterator_remove(&it);
7102                     hci_send_cmd(&hci_le_remove_cig, cig->cig_id);
7103                     return true;
7104                 }
7105             default:
7106                 break;
7107         }
7108     }
7109 
7110     // CIS Accept/Reject/Setup ISO Path/Close
7111     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
7112     while (btstack_linked_list_iterator_has_next(&it)) {
7113         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
7114         hci_con_handle_t con_handle;
7115         switch (iso_stream->state){
7116             case HCI_ISO_STREAM_W2_ACCEPT:
7117                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
7118                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7119                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7120                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->cis_handle);
7121                 return true;
7122             case HCI_ISO_STREAM_W2_REJECT:
7123                 con_handle = iso_stream->cis_handle;
7124                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7125                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7126                 hci_iso_stream_finalize(iso_stream);
7127                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
7128                 return true;
7129             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
7130                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7131                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7132                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
7133                 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);
7134                 break;
7135             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
7136                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7137                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7138                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT;
7139                 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);
7140                 break;
7141             case HCI_ISO_STREAM_STATE_W2_CLOSE:
7142                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_DISCONNECTED;
7143                 hci_send_cmd(&hci_disconnect, iso_stream->cis_handle);
7144                 break;
7145             default:
7146                 break;
7147         }
7148     }
7149 
7150     return false;
7151 }
7152 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
7153 #endif
7154 
7155 static bool hci_run_general_pending_commands(void){
7156     btstack_linked_item_t * it;
7157     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7158         hci_connection_t * connection = (hci_connection_t *) it;
7159 
7160         switch(connection->state){
7161             case SEND_CREATE_CONNECTION:
7162                 switch(connection->address_type){
7163 #ifdef ENABLE_CLASSIC
7164                     case BD_ADDR_TYPE_ACL:
7165                         log_info("sending hci_create_connection");
7166                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
7167                         break;
7168 #endif
7169                     default:
7170 #ifdef ENABLE_BLE
7171 #ifdef ENABLE_LE_CENTRAL
7172                         log_info("sending hci_le_create_connection");
7173                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
7174                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
7175                         hci_send_le_create_connection(0, connection->address_type, connection->address);
7176                         connection->state = SENT_CREATE_CONNECTION;
7177 #endif
7178 #endif
7179                         break;
7180                 }
7181                 return true;
7182 
7183 #ifdef ENABLE_CLASSIC
7184             case RECEIVED_CONNECTION_REQUEST:
7185                 if (connection->address_type == BD_ADDR_TYPE_ACL){
7186                     log_info("sending hci_accept_connection_request");
7187                     connection->state = ACCEPTED_CONNECTION_REQUEST;
7188                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
7189                     return true;
7190                 }
7191                 break;
7192 #endif
7193             case SEND_DISCONNECT:
7194                 connection->state = SENT_DISCONNECT;
7195                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7196                 return true;
7197 
7198             default:
7199                 break;
7200         }
7201 
7202         // no further commands if connection is about to get shut down
7203         if (connection->state == SENT_DISCONNECT) continue;
7204 
7205 #ifdef ENABLE_CLASSIC
7206 
7207         // Handling link key request requires remote supported features
7208         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
7209             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
7210             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
7211 
7212             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
7213             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
7214             if (have_link_key && security_level_sufficient){
7215                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
7216             } else {
7217                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
7218             }
7219             return true;
7220         }
7221 
7222         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
7223             log_info("denying to pin request");
7224             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
7225             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
7226             return true;
7227         }
7228 
7229         // security assessment requires remote features
7230         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
7231             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
7232             hci_ssp_assess_security_on_io_cap_request(connection);
7233             // 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
7234         }
7235 
7236         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
7237             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7238             // set authentication requirements:
7239             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
7240             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
7241             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
7242             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
7243                 authreq |= 1;
7244             }
7245             bool bonding = hci_stack->bondable;
7246             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
7247                 // if we have received IO Cap Response, we're in responder role
7248                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7249                 if (bonding && !remote_bonding){
7250                     log_info("Remote not bonding, dropping local flag");
7251                     bonding = false;
7252                 }
7253             }
7254             if (bonding){
7255                 if (connection->bonding_flags & BONDING_DEDICATED){
7256                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7257                 } else {
7258                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
7259                 }
7260             }
7261             uint8_t have_oob_data = 0;
7262 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7263             if (connection->classic_oob_c_192 != NULL){
7264                     have_oob_data |= 1;
7265             }
7266             if (connection->classic_oob_c_256 != NULL){
7267                 have_oob_data |= 2;
7268             }
7269 #endif
7270             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
7271             return true;
7272         }
7273 
7274         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
7275             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
7276             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
7277             return true;
7278         }
7279 
7280 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7281         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
7282             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
7283             const uint8_t zero[16] = { 0 };
7284             const uint8_t * r_192 = zero;
7285             const uint8_t * c_192 = zero;
7286             const uint8_t * r_256 = zero;
7287             const uint8_t * c_256 = zero;
7288             // verify P-256 OOB
7289             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
7290                 c_256 = connection->classic_oob_c_256;
7291                 if (connection->classic_oob_r_256 != NULL) {
7292                     r_256 = connection->classic_oob_r_256;
7293                 }
7294             }
7295             // verify P-192 OOB
7296             if ((connection->classic_oob_c_192 != NULL)) {
7297                 c_192 = connection->classic_oob_c_192;
7298                 if (connection->classic_oob_r_192 != NULL) {
7299                     r_192 = connection->classic_oob_r_192;
7300                 }
7301             }
7302 
7303             // assess security
7304             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
7305             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
7306             if (need_level_4 && !can_reach_level_4){
7307                 log_info("Level 4 required, but not possible -> abort");
7308                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
7309                 // send oob negative reply
7310                 c_256 = NULL;
7311                 c_192 = NULL;
7312             }
7313 
7314             // Reply
7315             if (c_256 != zero) {
7316                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
7317             } else if (c_192 != zero){
7318                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
7319             } else {
7320                 hci_stack->classic_oob_con_handle = connection->con_handle;
7321                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
7322             }
7323             return true;
7324         }
7325 #endif
7326 
7327         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
7328             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
7329             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
7330             return true;
7331         }
7332 
7333         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
7334             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
7335             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
7336             return true;
7337         }
7338 
7339         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
7340             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
7341             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
7342             return true;
7343         }
7344 
7345         if ((connection->bonding_flags & (BONDING_DISCONNECT_DEDICATED_DONE | BONDING_DEDICATED_DEFER_DISCONNECT)) == BONDING_DISCONNECT_DEDICATED_DONE){
7346             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
7347             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
7348             connection->state = SENT_DISCONNECT;
7349             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7350             return true;
7351         }
7352 
7353         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
7354             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
7355             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
7356             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
7357             return true;
7358         }
7359 
7360         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
7361             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
7362             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
7363             return true;
7364         }
7365 
7366         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
7367             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
7368             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
7369             return true;
7370         }
7371 
7372         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
7373             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7374             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
7375             return true;
7376         }
7377 
7378         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
7379             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
7380             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
7381             return true;
7382         }
7383 
7384         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
7385             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
7386             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
7387             return true;
7388         }
7389 #endif
7390 
7391         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
7392             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
7393 #ifdef ENABLE_CLASSIC
7394             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
7395 #endif
7396             if (connection->state != SENT_DISCONNECT){
7397                 connection->state = SENT_DISCONNECT;
7398                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
7399                 return true;
7400             }
7401         }
7402 
7403 #ifdef ENABLE_CLASSIC
7404         uint16_t sniff_min_interval;
7405         switch (connection->sniff_min_interval){
7406             case 0:
7407                 break;
7408             case 0xffff:
7409                 connection->sniff_min_interval = 0;
7410                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
7411                 return true;
7412             default:
7413                 sniff_min_interval = connection->sniff_min_interval;
7414                 connection->sniff_min_interval = 0;
7415                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
7416                 return true;
7417         }
7418 
7419         if (connection->sniff_subrating_max_latency != 0xffff){
7420             uint16_t max_latency = connection->sniff_subrating_max_latency;
7421             connection->sniff_subrating_max_latency = 0;
7422             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
7423             return true;
7424         }
7425 
7426         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
7427             uint8_t service_type = (uint8_t) connection->qos_service_type;
7428             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
7429             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);
7430             return true;
7431         }
7432 
7433         if (connection->request_role != HCI_ROLE_INVALID){
7434             hci_role_t role = connection->request_role;
7435             connection->request_role = HCI_ROLE_INVALID;
7436             hci_send_cmd(&hci_switch_role_command, connection->address, role);
7437             return true;
7438         }
7439 #endif
7440 
7441         if (connection->gap_connection_tasks != 0){
7442 #ifdef ENABLE_CLASSIC
7443             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
7444                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
7445                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
7446                 return true;
7447             }
7448             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
7449                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
7450                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
7451                 return true;
7452             }
7453 #endif
7454             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
7455                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
7456                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
7457                 return true;
7458             }
7459 #ifdef ENABLE_BLE
7460             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
7461                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
7462                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
7463                 return true;
7464             }
7465 #endif
7466         }
7467 
7468 #ifdef ENABLE_BLE
7469         switch (connection->le_con_parameter_update_state){
7470             // response to L2CAP CON PARAMETER UPDATE REQUEST
7471             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
7472                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7473                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
7474                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7475                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7476                 return true;
7477             case CON_PARAMETER_UPDATE_REPLY:
7478                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7479                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
7480                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7481                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7482                 return true;
7483             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
7484                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7485                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
7486                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
7487                 return true;
7488             default:
7489                 break;
7490         }
7491         if (connection->le_phy_update_all_phys != 0xffu){
7492             uint8_t all_phys = connection->le_phy_update_all_phys;
7493             connection->le_phy_update_all_phys = 0xff;
7494             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);
7495             return true;
7496         }
7497 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7498         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
7499             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
7500             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
7501             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
7502             return true;
7503         }
7504         if (connection->le_past_advertising_handle != 0xff){
7505             uint8_t advertising_handle = connection->le_past_advertising_handle;
7506             connection->le_past_advertising_handle = 0xff;
7507             hci_send_cmd(&hci_le_periodic_advertising_set_info_transfer, connection->con_handle, connection->le_past_service_data, advertising_handle);
7508             return true;
7509         }
7510 #endif
7511 #endif
7512     }
7513     return false;
7514 }
7515 
7516 static void hci_run(void){
7517 
7518     // stack state sub statemachines
7519     switch (hci_stack->state) {
7520         case HCI_STATE_INITIALIZING:
7521             hci_initializing_run();
7522             break;
7523         case HCI_STATE_HALTING:
7524             hci_halting_run();
7525             break;
7526         case HCI_STATE_FALLING_ASLEEP:
7527             hci_falling_asleep_run();
7528             break;
7529         default:
7530             break;
7531     }
7532 
7533     // allow to run after initialization to working transition
7534     if (hci_stack->state != HCI_STATE_WORKING){
7535         return;
7536     }
7537 
7538     bool done;
7539 
7540     // send continuation fragments first, as they block the prepared packet buffer
7541     done = hci_run_acl_fragments();
7542     if (done) return;
7543 
7544 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7545     done = hci_run_iso_fragments();
7546     if (done) return;
7547 #endif
7548 
7549 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7550     // send host num completed packets next as they don't require num_cmd_packets > 0
7551     if (!hci_can_send_comand_packet_transport()) return;
7552     if (hci_stack->host_completed_packets){
7553         hci_host_num_completed_packets();
7554         return;
7555     }
7556 #endif
7557 
7558     if (!hci_can_send_command_packet_now()) return;
7559 
7560     // global/non-connection oriented commands
7561 
7562 
7563 #ifdef ENABLE_CLASSIC
7564     // general gap classic
7565     done = hci_run_general_gap_classic();
7566     if (done) return;
7567 #endif
7568 
7569 #ifdef ENABLE_BLE
7570     // general gap le
7571     done = hci_run_general_gap_le();
7572     if (done) return;
7573 
7574 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7575     // ISO related tasks, e.g. BIG create/terminate/sync
7576     done = hci_run_iso_tasks();
7577     if (done) return;
7578 #endif
7579 #endif
7580 
7581     // send pending HCI commands
7582     hci_run_general_pending_commands();
7583 }
7584 
7585 #ifdef ENABLE_CLASSIC
7586 static void hci_set_sco_payload_length_for_flipped_packet_types(hci_connection_t * hci_connection, uint16_t flipped_packet_types){
7587     // bits 6-9 are 'don't use'
7588     uint16_t packet_types = flipped_packet_types ^ 0x03c0;
7589 
7590     // restrict packet types to local and remote supported
7591     packet_types &= hci_connection->remote_supported_sco_packets & hci_stack->usable_packet_types_sco;
7592     hci_connection->sco_payload_length = hci_sco_payload_length_for_packet_types(packet_types);
7593     log_info("Possible SCO packet types 0x%04x => payload length %u", packet_types, hci_connection->sco_payload_length);
7594 }
7595 #endif
7596 
7597 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
7598     // house-keeping
7599 
7600 #ifdef ENABLE_CLASSIC
7601     bd_addr_t addr;
7602     hci_connection_t * conn;
7603 #endif
7604 #ifdef ENABLE_LE_CENTRAL
7605     uint8_t initiator_filter_policy;
7606 #endif
7607 
7608     uint16_t opcode = little_endian_read_16(packet, 0);
7609     switch (opcode) {
7610         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
7611             hci_stack->loopback_mode = packet[3];
7612             break;
7613 
7614 #ifdef ENABLE_CLASSIC
7615         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7616             reverse_bd_addr(&packet[3], addr);
7617             log_info("Create_connection to %s", bd_addr_to_str(addr));
7618 
7619             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
7620             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
7621                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
7622                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
7623             }
7624 
7625             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7626             if (!conn) {
7627                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
7628                 if (!conn) {
7629                     // notify client that alloc failed
7630                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7631                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
7632                 }
7633                 conn->state = SEND_CREATE_CONNECTION;
7634             }
7635 
7636             log_info("conn state %u", conn->state);
7637             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7638             switch (conn->state) {
7639                 // if connection active exists
7640                 case OPEN:
7641                     // and OPEN, emit connection complete command
7642                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
7643                     // packet not sent to controller
7644                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7645                 case RECEIVED_DISCONNECTION_COMPLETE:
7646                     // create connection triggered in disconnect complete event, let's do it now
7647                     break;
7648                 case SEND_CREATE_CONNECTION:
7649 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
7650                     if (hci_classic_operation_active()){
7651                         return ERROR_CODE_SUCCESS;
7652                     }
7653 #endif
7654                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7655                     break;
7656                 default:
7657                     // otherwise, just ignore as it is already in the open process
7658                     // packet not sent to controller
7659                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7660             }
7661             conn->state = SENT_CREATE_CONNECTION;
7662 
7663             // track outgoing connection
7664             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
7665             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7666             break;
7667 
7668         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
7669             conn = hci_connection_for_handle(little_endian_read_16(packet, 3));
7670             if (conn == NULL) {
7671                 // neither SCO nor ACL connection for con handle
7672                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7673             } else {
7674                 uint16_t remote_supported_sco_packets;
7675                 switch (conn->address_type){
7676                     case BD_ADDR_TYPE_ACL:
7677                         // assert SCO connection does not exit
7678                         if (hci_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO) != NULL){
7679                             return ERROR_CODE_COMMAND_DISALLOWED;
7680                         }
7681                         // cache remote sco packet types
7682                         remote_supported_sco_packets = conn->remote_supported_sco_packets;
7683 
7684                         // allocate connection struct
7685                         conn = create_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO,
7686                                                                       HCI_ROLE_MASTER);
7687                         if (!conn) {
7688                             return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7689                         }
7690                         conn->remote_supported_sco_packets = remote_supported_sco_packets;
7691                         break;
7692                     case BD_ADDR_TYPE_SCO:
7693                         // update of existing SCO connection
7694                         break;
7695                     default:
7696                         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7697                 }
7698             }
7699 
7700             // conn refers to hci connection of type sco now
7701 
7702             conn->state = SENT_CREATE_CONNECTION;
7703 
7704             // track outgoing connection to handle command status with error
7705             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7706             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7707 
7708             // setup_synchronous_connection? Voice setting at offset 22
7709             // TODO: compare to current setting if sco connection already active
7710             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7711 
7712             // derive sco payload length from packet types
7713             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 18));
7714             break;
7715 
7716         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
7717             // get SCO connection
7718             reverse_bd_addr(&packet[3], addr);
7719             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
7720             if (conn == NULL){
7721                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7722             }
7723 
7724             conn->state = ACCEPTED_CONNECTION_REQUEST;
7725 
7726             // track outgoing connection to handle command status with error
7727             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7728             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7729 
7730             // accept_synchronous_connection? Voice setting at offset 18
7731             // TODO: compare to current setting if sco connection already active
7732             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7733 
7734             // derive sco payload length from packet types
7735             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 22));
7736             break;
7737 #endif
7738 
7739 #ifdef ENABLE_BLE
7740 #ifdef ENABLE_LE_CENTRAL
7741         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7742             // white list used?
7743             initiator_filter_policy = packet[7];
7744             switch (initiator_filter_policy) {
7745                 case 0:
7746                     // whitelist not used
7747                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7748                     break;
7749                 case 1:
7750                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7751                     break;
7752                 default:
7753                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7754                     break;
7755             }
7756             // track outgoing connection
7757             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer address type
7758             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
7759             break;
7760 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7761         case HCI_OPCODE_HCI_LE_EXTENDED_CREATE_CONNECTION:
7762             // white list used?
7763             initiator_filter_policy = packet[3];
7764             switch (initiator_filter_policy) {
7765                 case 0:
7766                     // whitelist not used
7767                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7768                     break;
7769                 case 1:
7770                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7771                     break;
7772                 default:
7773                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7774                     break;
7775             }
7776             // track outgoing connection
7777             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[5]; // peer address type
7778             reverse_bd_addr( &packet[6], hci_stack->outgoing_addr); // peer address
7779             break;
7780 #endif
7781         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
7782             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
7783             break;
7784 #endif
7785 #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
7786         case HCI_OPCODE_HCI_LE_CONNECTION_UPDATE:
7787         case HCI_OPCODE_HCI_LE_READ_REMOTE_USED_FEATURES:
7788         case HCI_OPCODE_HCI_LE_START_ENCRYPTION:
7789         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_REQUEST_REPLY:
7790         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_NEGATIVE_REPLY:
7791         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY:
7792         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY:
7793         case HCI_OPCODE_HCI_LE_SET_DATA_LENGTH:
7794         case HCI_OPCODE_HCI_LE_READ_PHY:
7795         case HCI_OPCODE_HCI_LE_SET_PHY:
7796             // conection handle is first command parameter
7797             hci_stack->hci_command_con_handle = little_endian_read_16(packet, 3);
7798             break;
7799 #endif
7800 #endif /* ENABLE_BLE */
7801         default:
7802             break;
7803     }
7804 
7805     hci_stack->num_cmd_packets--;
7806 
7807     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
7808     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7809     if (err != 0){
7810         return ERROR_CODE_HARDWARE_FAILURE;
7811     }
7812     return ERROR_CODE_SUCCESS;
7813 }
7814 
7815 // disconnect because of security block
7816 void hci_disconnect_security_block(hci_con_handle_t con_handle){
7817     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7818     if (!connection) return;
7819     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
7820 }
7821 
7822 
7823 // Configure Secure Simple Pairing
7824 
7825 #ifdef ENABLE_CLASSIC
7826 
7827 // enable will enable SSP during init
7828 void gap_ssp_set_enable(int enable){
7829     hci_stack->ssp_enable = enable;
7830 }
7831 
7832 static int hci_local_ssp_activated(void){
7833     return gap_ssp_supported() && hci_stack->ssp_enable;
7834 }
7835 
7836 // if set, BTstack will respond to io capability request using authentication requirement
7837 void gap_ssp_set_io_capability(int io_capability){
7838     hci_stack->ssp_io_capability = io_capability;
7839 }
7840 void gap_ssp_set_authentication_requirement(int authentication_requirement){
7841     hci_stack->ssp_authentication_requirement = authentication_requirement;
7842 }
7843 
7844 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
7845 void gap_ssp_set_auto_accept(int auto_accept){
7846     hci_stack->ssp_auto_accept = auto_accept;
7847 }
7848 
7849 void gap_secure_connections_enable(bool enable){
7850     hci_stack->secure_connections_enable = enable;
7851 }
7852 bool gap_secure_connections_active(void){
7853     return hci_stack->secure_connections_active;
7854 }
7855 
7856 #endif
7857 
7858 // va_list part of hci_send_cmd
7859 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
7860     if (!hci_can_send_command_packet_now()){
7861         log_error("hci_send_cmd called but cannot send packet now");
7862         return ERROR_CODE_COMMAND_DISALLOWED;
7863     }
7864 
7865     // for HCI INITIALIZATION
7866     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
7867     hci_stack->last_cmd_opcode = cmd->opcode;
7868 
7869     hci_reserve_packet_buffer();
7870     uint8_t * packet = hci_stack->hci_packet_buffer;
7871     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
7872     uint8_t status = hci_send_cmd_packet(packet, size);
7873 
7874     // release packet buffer on error or for synchronous transport implementations
7875     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7876         hci_release_packet_buffer();
7877         hci_emit_transport_packet_sent();
7878     }
7879 
7880     return status;
7881 }
7882 
7883 /**
7884  * pre: numcmds >= 0 - it's allowed to send a command to the controller
7885  */
7886 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
7887     va_list argptr;
7888     va_start(argptr, cmd);
7889     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
7890     va_end(argptr);
7891     return status;
7892 }
7893 
7894 // Create various non-HCI events.
7895 // TODO: generalize, use table similar to hci_create_command
7896 
7897 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
7898     // dump packet
7899     if (dump) {
7900         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
7901     }
7902 
7903     // dispatch to all event handlers
7904     btstack_linked_list_iterator_t it;
7905     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
7906     while (btstack_linked_list_iterator_has_next(&it)){
7907         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
7908         entry->callback(HCI_EVENT_PACKET, 0, event, size);
7909     }
7910 }
7911 
7912 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
7913     if (!hci_stack->acl_packet_handler) return;
7914     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
7915 }
7916 
7917 #ifdef ENABLE_CLASSIC
7918 static void hci_notify_if_sco_can_send_now(void){
7919     // notify SCO sender if waiting
7920     if (!hci_stack->sco_waiting_for_can_send_now) return;
7921     if (hci_can_send_sco_packet_now()){
7922         hci_stack->sco_waiting_for_can_send_now = 0;
7923         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
7924         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
7925         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
7926     }
7927 }
7928 
7929 // parsing end emitting has been merged to reduce code size
7930 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
7931     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
7932 
7933     uint8_t * eir_data;
7934     ad_context_t context;
7935     const uint8_t * name;
7936     uint8_t         name_len;
7937 
7938     if (size < 3) return;
7939 
7940     int event_type = hci_event_packet_get_type(packet);
7941     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
7942     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
7943 
7944     switch (event_type){
7945         case HCI_EVENT_INQUIRY_RESULT:
7946         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7947             if (size != (3 + (num_responses * 14))) return;
7948             break;
7949         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7950             if (size != 257) return;
7951             if (num_responses != 1) return;
7952             break;
7953         default:
7954             return;
7955     }
7956 
7957     // event[1] is set at the end
7958     int i;
7959     for (i=0; i<num_responses;i++){
7960         memset(event, 0, sizeof(event));
7961         event[0] = GAP_EVENT_INQUIRY_RESULT;
7962         uint8_t event_size = 27;    // if name is not set by EIR
7963 
7964         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
7965         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
7966         (void)memcpy(&event[9],
7967                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
7968                      3); // class of device
7969         (void)memcpy(&event[12],
7970                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
7971                      2); // clock offset
7972 
7973         switch (event_type){
7974             case HCI_EVENT_INQUIRY_RESULT:
7975                 // 14,15,16,17 = 0, size 18
7976                 break;
7977             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7978                 event[14] = 1;
7979                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7980                 // 16,17 = 0, size 18
7981                 break;
7982             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7983                 event[14] = 1;
7984                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7985                 // EIR packets only contain a single inquiry response
7986                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
7987                 name = NULL;
7988                 // Iterate over EIR data
7989                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
7990                     uint8_t data_type    = ad_iterator_get_data_type(&context);
7991                     uint8_t data_size    = ad_iterator_get_data_len(&context);
7992                     const uint8_t * data = ad_iterator_get_data(&context);
7993                     // Prefer Complete Local Name over Shortened Local Name
7994                     switch (data_type){
7995                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
7996                             if (name) continue;
7997                             /* fall through */
7998                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
7999                             name = data;
8000                             name_len = data_size;
8001                             break;
8002                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
8003                             if (data_size != 8) break;
8004                             event[16] = 1;
8005                             memcpy(&event[17], data, 8);
8006                             break;
8007                         default:
8008                             break;
8009                     }
8010                 }
8011                 if (name){
8012                     event[25] = 1;
8013                     // truncate name if needed
8014                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
8015                     event[26] = len;
8016                     (void)memcpy(&event[27], name, len);
8017                     event_size += len;
8018                 }
8019                 break;
8020             default:
8021                 return;
8022         }
8023         event[1] = event_size - 2;
8024         hci_emit_event(event, event_size, 1);
8025     }
8026 }
8027 #endif
8028 
8029 void hci_emit_state(void){
8030     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
8031     uint8_t event[3];
8032     event[0] = BTSTACK_EVENT_STATE;
8033     event[1] = sizeof(event) - 2u;
8034     event[2] = hci_stack->state;
8035     hci_emit_event(event, sizeof(event), 1);
8036 }
8037 
8038 #ifdef ENABLE_CLASSIC
8039 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
8040     uint8_t event[13];
8041     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
8042     event[1] = sizeof(event) - 2;
8043     event[2] = status;
8044     little_endian_store_16(event, 3, con_handle);
8045     reverse_bd_addr(address, &event[5]);
8046     event[11] = 1; // ACL connection
8047     event[12] = 0; // encryption disabled
8048     hci_emit_event(event, sizeof(event), 1);
8049 }
8050 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
8051     if (disable_l2cap_timeouts) return;
8052     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
8053     uint8_t event[4];
8054     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
8055     event[1] = sizeof(event) - 2;
8056     little_endian_store_16(event, 2, conn->con_handle);
8057     hci_emit_event(event, sizeof(event), 1);
8058 }
8059 #endif
8060 
8061 #ifdef ENABLE_BLE
8062 #ifdef ENABLE_LE_CENTRAL
8063 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){
8064     uint8_t hci_event[21];
8065     hci_event[0] = HCI_EVENT_LE_META;
8066     hci_event[1] = sizeof(hci_event) - 2u;
8067     hci_event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
8068     hci_event[3] = status;
8069     little_endian_store_16(hci_event, 4, con_handle);
8070     hci_event[6] = 0; // TODO: role
8071     hci_event[7] = address_type;
8072     reverse_bd_addr(address, &hci_event[8]);
8073     little_endian_store_16(hci_event, 14, 0); // interval
8074     little_endian_store_16(hci_event, 16, 0); // latency
8075     little_endian_store_16(hci_event, 18, 0); // supervision timeout
8076     hci_event[20] = 0; // master clock accuracy
8077     hci_emit_event(hci_event, sizeof(hci_event), 1);
8078     // emit GAP event, too
8079     uint8_t gap_event[36];
8080     hci_create_gap_connection_complete_event(hci_event, gap_event);
8081     hci_emit_event(gap_event, sizeof(gap_event), 1);
8082 }
8083 #endif
8084 #endif
8085 
8086 static void hci_emit_transport_packet_sent(void){
8087     // notify upper stack that it might be possible to send again
8088     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
8089     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
8090 }
8091 
8092 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
8093     uint8_t event[6];
8094     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
8095     event[1] = sizeof(event) - 2u;
8096     event[2] = 0; // status = OK
8097     little_endian_store_16(event, 3, con_handle);
8098     event[5] = reason;
8099     hci_emit_event(event, sizeof(event), 1);
8100 }
8101 
8102 static void hci_emit_nr_connections_changed(void){
8103     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
8104     uint8_t event[3];
8105     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
8106     event[1] = sizeof(event) - 2u;
8107     event[2] = nr_hci_connections();
8108     hci_emit_event(event, sizeof(event), 1);
8109 }
8110 
8111 static void hci_emit_hci_open_failed(void){
8112     log_info("BTSTACK_EVENT_POWERON_FAILED");
8113     uint8_t event[2];
8114     event[0] = BTSTACK_EVENT_POWERON_FAILED;
8115     event[1] = sizeof(event) - 2u;
8116     hci_emit_event(event, sizeof(event), 1);
8117 }
8118 
8119 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
8120     log_info("hci_emit_dedicated_bonding_result %u ", status);
8121     uint8_t event[9];
8122     int pos = 0;
8123     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
8124     event[pos++] = sizeof(event) - 2u;
8125     event[pos++] = status;
8126     reverse_bd_addr(address, &event[pos]);
8127     hci_emit_event(event, sizeof(event), 1);
8128 }
8129 
8130 
8131 #ifdef ENABLE_CLASSIC
8132 
8133 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
8134     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
8135     uint8_t event[5];
8136     int pos = 0;
8137     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
8138     event[pos++] = sizeof(event) - 2;
8139     little_endian_store_16(event, 2, con_handle);
8140     pos += 2;
8141     event[pos++] = level;
8142     hci_emit_event(event, sizeof(event), 1);
8143 }
8144 
8145 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
8146     if (!connection) return LEVEL_0;
8147     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
8148     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
8149     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
8150     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
8151     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
8152     // LEVEL 4 always requires 128 bit encrytion key size
8153     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
8154         security_level = LEVEL_3;
8155     }
8156     return security_level;
8157 }
8158 
8159 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
8160     uint8_t event[4];
8161     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
8162     event[1] = sizeof(event) - 2;
8163     event[2] = discoverable;
8164     event[3] = connectable;
8165     hci_emit_event(event, sizeof(event), 1);
8166 }
8167 
8168 // query if remote side supports eSCO
8169 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
8170     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8171     if (!connection) return false;
8172     return (connection->remote_supported_features[0] & 1) != 0;
8173 }
8174 
8175 uint16_t hci_remote_sco_packet_types(hci_con_handle_t con_handle){
8176     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8177     if (!connection) return 0;
8178     return connection->remote_supported_sco_packets;
8179 }
8180 
8181 static bool hci_ssp_supported(hci_connection_t * connection){
8182     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
8183     return (connection->bonding_flags & mask) == mask;
8184 }
8185 
8186 // query if remote side supports SSP
8187 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
8188     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8189     if (!connection) return false;
8190     return hci_ssp_supported(connection) ? 1 : 0;
8191 }
8192 
8193 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
8194     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
8195 }
8196 
8197 /**
8198  * Check if remote supported features query has completed
8199  */
8200 bool hci_remote_features_available(hci_con_handle_t handle){
8201     hci_connection_t * connection = hci_connection_for_handle(handle);
8202     if (!connection) return false;
8203     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
8204 }
8205 
8206 /**
8207  * Trigger remote supported features query
8208  */
8209 
8210 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
8211     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
8212         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
8213     }
8214 }
8215 
8216 void hci_remote_features_query(hci_con_handle_t con_handle){
8217     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8218     if (!connection) return;
8219     hci_trigger_remote_features_for_connection(connection);
8220     hci_run();
8221 }
8222 
8223 // GAP API
8224 /**
8225  * @bbrief enable/disable bonding. default is enabled
8226  * @praram enabled
8227  */
8228 void gap_set_bondable_mode(int enable){
8229     hci_stack->bondable = enable ? 1 : 0;
8230 }
8231 /**
8232  * @brief Get bondable mode.
8233  * @return 1 if bondable
8234  */
8235 int gap_get_bondable_mode(void){
8236     return hci_stack->bondable;
8237 }
8238 
8239 /**
8240  * @brief map link keys to security levels
8241  */
8242 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
8243     switch (link_key_type){
8244         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8245             return LEVEL_4;
8246         case COMBINATION_KEY:
8247         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
8248             return LEVEL_3;
8249         default:
8250             return LEVEL_2;
8251     }
8252 }
8253 
8254 /**
8255  * @brief map link keys to secure connection yes/no
8256  */
8257 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
8258     switch (link_key_type){
8259         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8260         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8261             return true;
8262         default:
8263             return false;
8264     }
8265 }
8266 
8267 /**
8268  * @brief map link keys to authenticated
8269  */
8270 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
8271     switch (link_key_type){
8272         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8273         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
8274             return true;
8275         default:
8276             return false;
8277     }
8278 }
8279 
8280 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
8281     log_info("gap_mitm_protection_required_for_security_level %u", level);
8282     return level > LEVEL_2;
8283 }
8284 
8285 /**
8286  * @brief get current security level
8287  */
8288 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
8289     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8290     if (!connection) return LEVEL_0;
8291     return gap_security_level_for_connection(connection);
8292 }
8293 
8294 /**
8295  * @brief request connection to device to
8296  * @result GAP_AUTHENTICATION_RESULT
8297  */
8298 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
8299     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8300     if (!connection){
8301         hci_emit_security_level(con_handle, LEVEL_0);
8302         return;
8303     }
8304 
8305     btstack_assert(hci_is_le_connection(connection) == false);
8306 
8307     // 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)
8308     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
8309     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
8310         requested_level = LEVEL_4;
8311     }
8312 
8313     gap_security_level_t current_level = gap_security_level(con_handle);
8314     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
8315         requested_level, connection->requested_security_level, current_level);
8316 
8317     // authentication active if authentication request was sent or planned level > 0
8318     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
8319     if (authentication_active){
8320         // authentication already active
8321         if (connection->requested_security_level < requested_level){
8322             // increase requested level as new level is higher
8323             // TODO: handle re-authentication when done
8324             connection->requested_security_level = requested_level;
8325         }
8326     } else {
8327         // no request active, notify if security sufficient
8328         if (requested_level <= current_level){
8329             hci_emit_security_level(con_handle, current_level);
8330             return;
8331         }
8332 
8333         // store request
8334         connection->requested_security_level = requested_level;
8335 
8336         // start to authenticate connection
8337         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
8338 
8339         // request remote features if not already active, also trigger hci_run
8340         hci_remote_features_query(con_handle);
8341     }
8342 }
8343 
8344 /**
8345  * @brief start dedicated bonding with device. disconnect after bonding
8346  * @param device
8347  * @param request MITM protection
8348  * @result GAP_DEDICATED_BONDING_COMPLETE
8349  */
8350 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
8351 
8352     // create connection state machine
8353     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
8354 
8355     if (!connection){
8356         return BTSTACK_MEMORY_ALLOC_FAILED;
8357     }
8358 
8359     // delete link key
8360     gap_drop_link_key_for_bd_addr(device);
8361 
8362     // configure LEVEL_2/3, dedicated bonding
8363     connection->state = SEND_CREATE_CONNECTION;
8364     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
8365     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
8366     connection->bonding_flags = BONDING_DEDICATED;
8367 
8368     hci_run();
8369 
8370     return 0;
8371 }
8372 
8373 uint8_t hci_dedicated_bonding_defer_disconnect(hci_con_handle_t con_handle, bool defer){
8374     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8375     if (connection == NULL){
8376         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8377     }
8378     if (defer){
8379         connection->bonding_flags |= BONDING_DEDICATED_DEFER_DISCONNECT;
8380     } else {
8381         connection->bonding_flags &= ~BONDING_DEDICATED_DEFER_DISCONNECT;
8382         // trigger disconnect
8383         hci_run();
8384     }
8385     return ERROR_CODE_SUCCESS;
8386 }
8387 
8388 void gap_set_local_name(const char * local_name){
8389     hci_stack->local_name = local_name;
8390     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
8391     // also update EIR if not set by user
8392     if (hci_stack->eir_data == NULL){
8393         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
8394     }
8395     hci_run();
8396 }
8397 #endif
8398 
8399 
8400 #ifdef ENABLE_BLE
8401 
8402 #ifdef ENABLE_LE_CENTRAL
8403 void gap_start_scan(void){
8404     hci_stack->le_scanning_enabled = true;
8405     hci_run();
8406 }
8407 
8408 void gap_stop_scan(void){
8409     hci_stack->le_scanning_enabled = false;
8410     hci_run();
8411 }
8412 
8413 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
8414     hci_stack->le_scan_type          = scan_type;
8415     hci_stack->le_scan_filter_policy = scanning_filter_policy;
8416     hci_stack->le_scan_interval      = scan_interval;
8417     hci_stack->le_scan_window        = scan_window;
8418     hci_stack->le_scanning_param_update = true;
8419     hci_run();
8420 }
8421 
8422 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
8423     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
8424 }
8425 
8426 void gap_set_scan_duplicate_filter(bool enabled){
8427     hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0;
8428 }
8429 
8430 void gap_set_scan_phys(uint8_t phys){
8431     // LE Coded and LE 1M PHY
8432     hci_stack->le_scan_phys = phys & 0x05;
8433 }
8434 
8435 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type) {
8436     // disallow le connection if outgoing already active
8437     if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8438         log_error("le connect already active");
8439         return ERROR_CODE_COMMAND_DISALLOWED;
8440     }
8441 
8442     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
8443     if (conn == NULL) {
8444         conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_MASTER);
8445         if (conn == false){
8446             // alloc failed
8447             log_info("gap_connect: failed to alloc hci_connection_t");
8448             return BTSTACK_MEMORY_ALLOC_FAILED;
8449         }
8450     } else {
8451         switch (conn->state) {
8452             case RECEIVED_DISCONNECTION_COMPLETE:
8453                 // connection was just disconnected, reset state and allow re-connect
8454                 conn->role = HCI_ROLE_MASTER;
8455                 break;
8456             default:
8457                 return ERROR_CODE_COMMAND_DISALLOWED;
8458         }
8459     }
8460 
8461     // set le connecting state
8462     if (hci_is_le_connection_type(addr_type)){
8463         hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
8464     }
8465 
8466     // trigger connect
8467     log_info("gap_connect: send create connection next");
8468     conn->state = SEND_CREATE_CONNECTION;
8469     hci_run();
8470     return ERROR_CODE_SUCCESS;
8471 }
8472 
8473 // @assumption: only a single outgoing LE Connection exists
8474 static hci_connection_t * gap_get_outgoing_le_connection(void){
8475     btstack_linked_item_t *it;
8476     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
8477         hci_connection_t * conn = (hci_connection_t *) it;
8478         if (hci_is_le_connection(conn)){
8479             switch (conn->state){
8480                 case SEND_CREATE_CONNECTION:
8481                 case SENT_CREATE_CONNECTION:
8482                     return conn;
8483                 default:
8484                     break;
8485             };
8486         }
8487     }
8488     return NULL;
8489 }
8490 
8491 uint8_t gap_connect_cancel(void){
8492     hci_connection_t * conn;
8493     switch (hci_stack->le_connecting_request){
8494         case LE_CONNECTING_IDLE:
8495             break;
8496         case LE_CONNECTING_WHITELIST:
8497             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8498             hci_run();
8499             break;
8500         case LE_CONNECTING_DIRECT:
8501             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8502             conn = gap_get_outgoing_le_connection();
8503             if (conn == NULL){
8504                 hci_run();
8505             } else {
8506                 switch (conn->state){
8507                     case SEND_CREATE_CONNECTION:
8508                         // skip sending create connection and emit event instead
8509                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
8510                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
8511                         btstack_memory_hci_connection_free( conn );
8512                         break;
8513                     case SENT_CREATE_CONNECTION:
8514                         // let hci_run_general_gap_le cancel outgoing connection
8515                         hci_run();
8516                         break;
8517                     default:
8518                         break;
8519                 }
8520             }
8521             break;
8522         default:
8523             btstack_unreachable();
8524             break;
8525     }
8526     return ERROR_CODE_SUCCESS;
8527 }
8528 
8529 /**
8530  * @brief Set connection parameters for outgoing connections
8531  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
8532  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
8533  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
8534  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
8535  * @param conn_latency, default: 4
8536  * @param supervision_timeout (unit: 10ms), default: 720 ms
8537  * @param min_ce_length (unit: 0.625ms), default: 10 ms
8538  * @param max_ce_length (unit: 0.625ms), default: 30 ms
8539  */
8540 
8541 void gap_set_connection_phys(uint8_t phys){
8542     // LE Coded, LE 1M, LE 2M PHY
8543     hci_stack->le_connection_phys = phys & 7;
8544 }
8545 
8546 #endif
8547 
8548 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
8549                                    uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
8550                                    uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
8551     hci_stack->le_connection_scan_interval = conn_scan_interval;
8552     hci_stack->le_connection_scan_window = conn_scan_window;
8553     hci_stack->le_connection_interval_min = conn_interval_min;
8554     hci_stack->le_connection_interval_max = conn_interval_max;
8555     hci_stack->le_connection_latency = conn_latency;
8556     hci_stack->le_supervision_timeout = supervision_timeout;
8557     hci_stack->le_minimum_ce_length = min_ce_length;
8558     hci_stack->le_maximum_ce_length = max_ce_length;
8559 }
8560 
8561 /**
8562  * @brief Updates the connection parameters for a given LE connection
8563  * @param handle
8564  * @param conn_interval_min (unit: 1.25ms)
8565  * @param conn_interval_max (unit: 1.25ms)
8566  * @param conn_latency
8567  * @param supervision_timeout (unit: 10ms)
8568  * @return 0 if ok
8569  */
8570 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8571     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8572     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8573     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8574     connection->le_conn_interval_min = conn_interval_min;
8575     connection->le_conn_interval_max = conn_interval_max;
8576     connection->le_conn_latency = conn_latency;
8577     connection->le_supervision_timeout = supervision_timeout;
8578     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
8579     hci_run();
8580     return 0;
8581 }
8582 
8583 /**
8584  * @brief Request an update of the connection parameter for a given LE connection
8585  * @param handle
8586  * @param conn_interval_min (unit: 1.25ms)
8587  * @param conn_interval_max (unit: 1.25ms)
8588  * @param conn_latency
8589  * @param supervision_timeout (unit: 10ms)
8590  * @return 0 if ok
8591  */
8592 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8593     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8594     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8595     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8596     connection->le_conn_interval_min = conn_interval_min;
8597     connection->le_conn_interval_max = conn_interval_max;
8598     connection->le_conn_latency = conn_latency;
8599     connection->le_supervision_timeout = supervision_timeout;
8600     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
8601     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
8602     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
8603     return 0;
8604 }
8605 
8606 #ifdef ENABLE_LE_PERIPHERAL
8607 
8608 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8609 static void hci_assert_advertisement_set_0_ready(void){
8610     // force advertising set creation for legacy LE Advertising
8611     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) == 0){
8612         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8613     }
8614 }
8615 #endif
8616 
8617 /**
8618  * @brief Set Advertisement Data
8619  * @param advertising_data_length
8620  * @param advertising_data (max 31 octets)
8621  * @note data is not copied, pointer has to stay valid
8622  */
8623 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
8624     hci_stack->le_advertisements_data_len = advertising_data_length;
8625     hci_stack->le_advertisements_data = advertising_data;
8626     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8627 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8628     hci_assert_advertisement_set_0_ready();
8629 #endif
8630     hci_run();
8631 }
8632 
8633 /**
8634  * @brief Set Scan Response Data
8635  * @param advertising_data_length
8636  * @param advertising_data (max 31 octets)
8637  * @note data is not copied, pointer has to stay valid
8638  */
8639 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
8640     hci_stack->le_scan_response_data_len = scan_response_data_length;
8641     hci_stack->le_scan_response_data = scan_response_data;
8642     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8643 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8644     hci_assert_advertisement_set_0_ready();
8645 #endif
8646     hci_run();
8647 }
8648 
8649 /**
8650  * @brief Set Advertisement Parameters
8651  * @param adv_int_min
8652  * @param adv_int_max
8653  * @param adv_type
8654  * @param direct_address_type
8655  * @param direct_address
8656  * @param channel_map
8657  * @param filter_policy
8658  *
8659  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
8660  */
8661  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
8662     uint8_t direct_address_typ, bd_addr_t direct_address,
8663     uint8_t channel_map, uint8_t filter_policy) {
8664 
8665     hci_stack->le_advertisements_interval_min = adv_int_min;
8666     hci_stack->le_advertisements_interval_max = adv_int_max;
8667     hci_stack->le_advertisements_type = adv_type;
8668     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
8669     hci_stack->le_advertisements_channel_map = channel_map;
8670     hci_stack->le_advertisements_filter_policy = filter_policy;
8671     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
8672                  6);
8673 
8674     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8675     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
8676     hci_run();
8677  }
8678 
8679 /**
8680  * @brief Enable/Disable Advertisements
8681  * @param enabled
8682  */
8683 void gap_advertisements_enable(int enabled){
8684     if (enabled == 0){
8685         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8686     } else {
8687         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
8688     }
8689     hci_update_advertisements_enabled_for_current_roles();
8690     hci_run();
8691 }
8692 
8693 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8694 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
8695     btstack_linked_list_iterator_t it;
8696     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
8697     while (btstack_linked_list_iterator_has_next(&it)){
8698         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
8699         if ( item->advertising_handle == advertising_handle ) {
8700             return item;
8701         }
8702     }
8703     return NULL;
8704 }
8705 
8706 uint8_t gap_extended_advertising_set_resolvable_private_address_update(uint16_t update_s){
8707     hci_stack->le_resolvable_private_address_update_s = update_s;
8708     hci_run();
8709     return ERROR_CODE_SUCCESS;
8710 }
8711 
8712 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
8713     // find free advertisement handle
8714     uint8_t advertisement_handle;
8715     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
8716         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
8717     }
8718     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8719     // clear
8720     memset(storage, 0, sizeof(le_advertising_set_t));
8721     // copy params
8722     storage->advertising_handle = advertisement_handle;
8723     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8724     // add to list
8725     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
8726     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
8727     *out_advertising_handle = advertisement_handle;
8728     // set tasks and start
8729     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8730     hci_run();
8731     return ERROR_CODE_SUCCESS;
8732 }
8733 
8734 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
8735     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8736     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8737     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8738     // set tasks and start
8739     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8740     hci_run();
8741     return ERROR_CODE_SUCCESS;
8742 }
8743 
8744 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
8745     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8746     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8747     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
8748     return ERROR_CODE_SUCCESS;
8749 }
8750 
8751 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
8752     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8753     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8754     memcpy(advertising_set->random_address, random_address, 6);
8755     // set tasks and start
8756     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8757     hci_run();
8758     return ERROR_CODE_SUCCESS;
8759 }
8760 
8761 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
8762     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8763     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8764     advertising_set->adv_data = advertising_data;
8765     advertising_set->adv_data_len = advertising_data_length;
8766     // set tasks and start
8767     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8768     hci_run();
8769     return ERROR_CODE_SUCCESS;
8770 }
8771 
8772 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){
8773     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8774     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8775     advertising_set->scan_data = scan_response_data;
8776     advertising_set->scan_data_len = scan_response_data_length;
8777     // set tasks and start
8778     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8779     hci_run();
8780     return ERROR_CODE_SUCCESS;
8781 }
8782 
8783 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
8784     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8785     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8786     advertising_set->enable_timeout = timeout;
8787     advertising_set->enable_max_scan_events = num_extended_advertising_events;
8788     // set tasks and start
8789     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
8790     hci_run();
8791     return ERROR_CODE_SUCCESS;
8792 }
8793 
8794 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
8795     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8796     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8797     // set tasks and start
8798     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8799     hci_run();
8800     return ERROR_CODE_SUCCESS;
8801 }
8802 
8803 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8804     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8805     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8806     // set tasks and start
8807     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8808     hci_run();
8809     return ERROR_CODE_SUCCESS;
8810 }
8811 
8812 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8813 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8814     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8815     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8816     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8817     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8818     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8819     // set tasks and start
8820     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8821     hci_run();
8822     return ERROR_CODE_SUCCESS;
8823 }
8824 
8825 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8826     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8827     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8828     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8829     return ERROR_CODE_SUCCESS;
8830 }
8831 
8832 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8833     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8834     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8835     advertising_set->periodic_data = periodic_data;
8836     advertising_set->periodic_data_len = periodic_data_length;
8837     // set tasks and start
8838     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8839     hci_run();
8840     return ERROR_CODE_SUCCESS;
8841 }
8842 
8843 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
8844     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8845     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8846     // set tasks and start
8847     advertising_set->periodic_include_adi = include_adi;
8848     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8849     hci_run();
8850     return ERROR_CODE_SUCCESS;
8851 }
8852 
8853 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
8854     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8855     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8856     // set tasks and start
8857     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8858     hci_run();
8859     return ERROR_CODE_SUCCESS;
8860 }
8861 
8862 uint8_t gap_periodic_advertising_sync_transfer_set_default_parameters(uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type){
8863     hci_stack->le_past_mode = mode;
8864     hci_stack->le_past_skip = skip;
8865     hci_stack->le_past_sync_timeout = sync_timeout;
8866     hci_stack->le_past_cte_type = cte_type;
8867     hci_stack->le_past_set_default_params = true;
8868     hci_run();
8869     return ERROR_CODE_SUCCESS;
8870 }
8871 
8872 uint8_t gap_periodic_advertising_sync_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, hci_con_handle_t sync_handle){
8873     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8874     if (hci_connection == NULL){
8875         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8876     }
8877     hci_connection->le_past_sync_handle = sync_handle;
8878     hci_connection->le_past_service_data = service_data;
8879     hci_run();
8880     return ERROR_CODE_SUCCESS;
8881 }
8882 
8883 uint8_t gap_periodic_advertising_set_info_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, uint8_t advertising_handle){
8884     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8885     if (hci_connection == NULL){
8886         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8887     }
8888     hci_connection->le_past_advertising_handle = advertising_handle;
8889     hci_connection->le_past_service_data = service_data;
8890     hci_run();
8891     return ERROR_CODE_SUCCESS;
8892 }
8893 
8894 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
8895 
8896 #endif
8897 
8898 #endif
8899 
8900 void hci_le_set_own_address_type(uint8_t own_address_type){
8901     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
8902     if (own_address_type == hci_stack->le_own_addr_type) return;
8903     hci_stack->le_own_addr_type = own_address_type;
8904 
8905 #ifdef ENABLE_LE_PERIPHERAL
8906     // update advertisement parameters, too
8907     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8908     hci_run();
8909 #endif
8910 #ifdef ENABLE_LE_CENTRAL
8911     // note: we don't update scan parameters or modify ongoing connection attempts
8912 #endif
8913 }
8914 
8915 void hci_le_random_address_set(const bd_addr_t random_address){
8916     log_info("gap_privacy: hci_le_random_address_set %s", bd_addr_to_str(random_address));
8917     memcpy(hci_stack->le_random_address, random_address, 6);
8918     hci_stack->le_random_address_set = true;
8919     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
8920 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8921     if (hci_le_extended_advertising_supported()){
8922         hci_assert_advertisement_set_0_ready();
8923         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
8924     }
8925 #endif
8926     hci_run();
8927 }
8928 
8929 #endif
8930 
8931 uint8_t gap_disconnect(hci_con_handle_t handle){
8932     hci_connection_t * conn = hci_connection_for_handle(handle);
8933     if (!conn){
8934         hci_emit_disconnection_complete(handle, 0);
8935         return 0;
8936     }
8937     // ignore if already disconnected
8938     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
8939         return 0;
8940     }
8941     conn->state = SEND_DISCONNECT;
8942     hci_run();
8943     return 0;
8944 }
8945 
8946 int gap_read_rssi(hci_con_handle_t con_handle){
8947     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8948     if (hci_connection == NULL) return 0;
8949     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
8950     hci_run();
8951     return 1;
8952 }
8953 
8954 /**
8955  * @brief Get connection type
8956  * @param con_handle
8957  * @result connection_type
8958  */
8959 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
8960     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8961     if (!conn) return GAP_CONNECTION_INVALID;
8962     switch (conn->address_type){
8963         case BD_ADDR_TYPE_LE_PUBLIC:
8964         case BD_ADDR_TYPE_LE_RANDOM:
8965         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
8966         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
8967             return GAP_CONNECTION_LE;
8968         case BD_ADDR_TYPE_SCO:
8969             return GAP_CONNECTION_SCO;
8970         case BD_ADDR_TYPE_ACL:
8971             return GAP_CONNECTION_ACL;
8972         default:
8973             return GAP_CONNECTION_INVALID;
8974     }
8975 }
8976 
8977 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
8978     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8979     if (!conn) return HCI_ROLE_INVALID;
8980     return (hci_role_t) conn->role;
8981 }
8982 
8983 
8984 #ifdef ENABLE_CLASSIC
8985 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
8986     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8987     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8988     conn->request_role = role;
8989     hci_run();
8990     return ERROR_CODE_SUCCESS;
8991 }
8992 #endif
8993 
8994 #ifdef ENABLE_BLE
8995 
8996 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){
8997     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8998     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8999 
9000     conn->le_phy_update_all_phys    = all_phys;
9001     conn->le_phy_update_tx_phys     = tx_phys;
9002     conn->le_phy_update_rx_phys     = rx_phys;
9003     conn->le_phy_update_phy_options = (uint8_t) phy_options;
9004 
9005     hci_run();
9006 
9007     return 0;
9008 }
9009 
9010 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9011 
9012 #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_WHITELIST_ENTRIES) || (MAX_NR_WHITELIST_ENTRIES == 0))
9013     // incorrect configuration:
9014     // - as MAX_NR_WHITELIST_ENTRIES is not defined or zero this function always fails
9015     // - please set MAX_NR_WHITELIST_ENTRIES in btstack_config.h
9016     btstack_assert(false);
9017 #endif
9018 
9019     // check if already in list
9020     btstack_linked_list_iterator_t it;
9021     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9022     while (btstack_linked_list_iterator_has_next(&it)) {
9023         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
9024         if (entry->address_type != address_type) {
9025             continue;
9026         }
9027         if (memcmp(entry->address, address, 6) != 0) {
9028             continue;
9029         }
9030 
9031         // if already on controller:
9032         if ((entry->state & LE_WHITELIST_ON_CONTROLLER) != 0){
9033             if ((entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER) != 0){
9034                 // drop remove request
9035                 entry->state = LE_WHITELIST_ON_CONTROLLER;
9036                 return ERROR_CODE_SUCCESS;
9037             } else {
9038                 // disallow as already on controller
9039                 return ERROR_CODE_COMMAND_DISALLOWED;
9040             }
9041         }
9042 
9043         // assume scheduled to add
9044 		return ERROR_CODE_COMMAND_DISALLOWED;
9045     }
9046 
9047     // alloc and add to list
9048     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
9049     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9050     entry->address_type = address_type;
9051     (void)memcpy(entry->address, address, 6);
9052     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
9053     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
9054     return ERROR_CODE_SUCCESS;
9055 }
9056 
9057 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9058     btstack_linked_list_iterator_t it;
9059     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9060     while (btstack_linked_list_iterator_has_next(&it)){
9061         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
9062         if (entry->address_type != address_type) {
9063             continue;
9064         }
9065         if (memcmp(entry->address, address, 6) != 0) {
9066             continue;
9067         }
9068         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9069             // remove from controller if already present
9070             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9071         }  else {
9072             // directly remove entry from whitelist
9073             btstack_linked_list_iterator_remove(&it);
9074             btstack_memory_whitelist_entry_free(entry);
9075         }
9076         return ERROR_CODE_SUCCESS;
9077     }
9078     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9079 }
9080 
9081 static void hci_whitelist_clear(void){
9082     btstack_linked_list_iterator_t it;
9083     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9084     while (btstack_linked_list_iterator_has_next(&it)){
9085         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
9086         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9087             // remove from controller if already present
9088             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9089             continue;
9090         }
9091         // directly remove entry from whitelist
9092         btstack_linked_list_iterator_remove(&it);
9093         btstack_memory_whitelist_entry_free(entry);
9094     }
9095 }
9096 
9097 /**
9098  * @brief Clear Whitelist
9099  * @return 0 if ok
9100  */
9101 uint8_t gap_whitelist_clear(void){
9102     hci_whitelist_clear();
9103     hci_run();
9104     return ERROR_CODE_SUCCESS;
9105 }
9106 
9107 /**
9108  * @brief Add Device to Whitelist
9109  * @param address_typ
9110  * @param address
9111  * @return 0 if ok
9112  */
9113 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9114     uint8_t status = hci_whitelist_add(address_type, address);
9115     if (status){
9116         return status;
9117     }
9118     hci_run();
9119     return ERROR_CODE_SUCCESS;
9120 }
9121 
9122 /**
9123  * @brief Remove Device from Whitelist
9124  * @param address_typ
9125  * @param address
9126  * @return 0 if ok
9127  */
9128 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9129     uint8_t status = hci_whitelist_remove(address_type, address);
9130     if (status){
9131         return status;
9132     }
9133     hci_run();
9134     return ERROR_CODE_SUCCESS;
9135 }
9136 
9137 #ifdef ENABLE_LE_CENTRAL
9138 /**
9139  * @brief Connect with Whitelist
9140  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
9141  * @return - if ok
9142  */
9143 uint8_t gap_connect_with_whitelist(void){
9144     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
9145         return ERROR_CODE_COMMAND_DISALLOWED;
9146     }
9147     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
9148     hci_run();
9149     return ERROR_CODE_SUCCESS;
9150 }
9151 
9152 /**
9153  * @brief Auto Connection Establishment - Start Connecting to device
9154  * @param address_typ
9155  * @param address
9156  * @return 0 if ok
9157  */
9158 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
9159     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
9160         return ERROR_CODE_COMMAND_DISALLOWED;
9161     }
9162 
9163     uint8_t status = hci_whitelist_add(address_type, address);
9164     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
9165         return status;
9166     }
9167 
9168     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
9169 
9170     hci_run();
9171     return ERROR_CODE_SUCCESS;
9172 }
9173 
9174 /**
9175  * @brief Auto Connection Establishment - Stop Connecting to device
9176  * @param address_typ
9177  * @param address
9178  * @return 0 if ok
9179  */
9180 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
9181     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
9182         return ERROR_CODE_COMMAND_DISALLOWED;
9183     }
9184 
9185     hci_whitelist_remove(address_type, address);
9186     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
9187         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
9188     }
9189     hci_run();
9190     return 0;
9191 }
9192 
9193 /**
9194  * @brief Auto Connection Establishment - Stop everything
9195  * @note  Convenience function to stop all active auto connection attempts
9196  */
9197 uint8_t gap_auto_connection_stop_all(void){
9198     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
9199         return ERROR_CODE_COMMAND_DISALLOWED;
9200     }
9201     hci_whitelist_clear();
9202     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
9203     hci_run();
9204     return ERROR_CODE_SUCCESS;
9205 }
9206 
9207 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
9208     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9209     if (!conn) return 0;
9210     return conn->le_connection_interval;
9211 }
9212 #endif
9213 #endif
9214 
9215 #ifdef ENABLE_CLASSIC
9216 /**
9217  * @brief Set Extended Inquiry Response data
9218  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
9219  * @note has to be done before stack starts up
9220  */
9221 void gap_set_extended_inquiry_response(const uint8_t * data){
9222     hci_stack->eir_data = data;
9223     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
9224     hci_run();
9225 }
9226 
9227 /**
9228  * @brief Start GAP Classic Inquiry
9229  * @param duration in 1.28s units
9230  * @return 0 if ok
9231  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
9232  */
9233 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
9234     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
9235     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9236     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
9237         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9238     }
9239     hci_stack->inquiry_state = duration_in_1280ms_units;
9240     hci_stack->inquiry_max_period_length = 0;
9241     hci_stack->inquiry_min_period_length = 0;
9242     hci_run();
9243     return 0;
9244 }
9245 
9246 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
9247     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
9248     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
9249     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9250     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9251     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
9252     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
9253 
9254     hci_stack->inquiry_state = duration;
9255     hci_stack->inquiry_max_period_length = max_period_length;
9256     hci_stack->inquiry_min_period_length = min_period_length;
9257     hci_run();
9258     return 0;
9259 }
9260 
9261 /**
9262  * @brief Stop GAP Classic Inquiry
9263  * @return 0 if ok
9264  */
9265 int gap_inquiry_stop(void){
9266     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
9267         // emit inquiry complete event, before it even started
9268         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
9269         hci_emit_event(event, sizeof(event), 1);
9270         return 0;
9271     }
9272     switch (hci_stack->inquiry_state){
9273         case GAP_INQUIRY_STATE_ACTIVE:
9274             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
9275             hci_run();
9276             return ERROR_CODE_SUCCESS;
9277         case GAP_INQUIRY_STATE_PERIODIC:
9278             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
9279             hci_run();
9280             return ERROR_CODE_SUCCESS;
9281         default:
9282             return ERROR_CODE_COMMAND_DISALLOWED;
9283     }
9284 }
9285 
9286 void gap_inquiry_set_lap(uint32_t lap){
9287     hci_stack->inquiry_lap = lap;
9288 }
9289 
9290 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
9291     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
9292     hci_stack->inquiry_scan_window   = inquiry_scan_window;
9293     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
9294     hci_run();
9295 }
9296 
9297 void gap_inquiry_set_transmit_power_level(int8_t tx_power)
9298 {
9299     hci_stack->inquiry_tx_power_level = tx_power;
9300     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
9301     hci_run();
9302 }
9303 
9304 
9305 /**
9306  * @brief Remote Name Request
9307  * @param addr
9308  * @param page_scan_repetition_mode
9309  * @param clock_offset only used when bit 15 is set
9310  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
9311  */
9312 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
9313     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9314     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
9315     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
9316     hci_stack->remote_name_clock_offset = clock_offset;
9317     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
9318     hci_run();
9319     return 0;
9320 }
9321 
9322 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
9323     hci_stack->gap_pairing_state = state;
9324     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
9325     hci_run();
9326     return 0;
9327 }
9328 
9329 /**
9330  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
9331  * @param addr
9332  * @param pin_data
9333  * @param pin_len
9334  * @return 0 if ok
9335  */
9336 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
9337     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9338     if (pin_len > PIN_CODE_LEN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9339     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
9340     hci_stack->gap_pairing_pin_len = pin_len;
9341     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
9342 }
9343 
9344 /**
9345  * @brief Legacy Pairing Pin Code Response
9346  * @param addr
9347  * @param pin
9348  * @return 0 if ok
9349  */
9350 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
9351     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
9352 }
9353 
9354 /**
9355  * @brief Abort Legacy Pairing
9356  * @param addr
9357  * @param pin
9358  * @return 0 if ok
9359  */
9360 int gap_pin_code_negative(bd_addr_t addr){
9361     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9362     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
9363 }
9364 
9365 /**
9366  * @brief SSP Passkey Response
9367  * @param addr
9368  * @param passkey
9369  * @return 0 if ok
9370  */
9371 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
9372     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9373     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
9374     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
9375 }
9376 
9377 /**
9378  * @brief Abort SSP Passkey Entry/Pairing
9379  * @param addr
9380  * @param pin
9381  * @return 0 if ok
9382  */
9383 int gap_ssp_passkey_negative(const bd_addr_t addr){
9384     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9385     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
9386 }
9387 
9388 /**
9389  * @brief Accept SSP Numeric Comparison
9390  * @param addr
9391  * @param passkey
9392  * @return 0 if ok
9393  */
9394 int gap_ssp_confirmation_response(const bd_addr_t addr){
9395     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9396     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
9397 }
9398 
9399 /**
9400  * @brief Abort SSP Numeric Comparison/Pairing
9401  * @param addr
9402  * @param pin
9403  * @return 0 if ok
9404  */
9405 int gap_ssp_confirmation_negative(const bd_addr_t addr){
9406     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9407     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
9408 }
9409 
9410 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
9411 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
9412     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9413     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9414     connectionSetAuthenticationFlags(conn, flag);
9415     hci_run();
9416     return ERROR_CODE_SUCCESS;
9417 }
9418 #endif
9419 
9420 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
9421 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
9422     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
9423 }
9424 
9425 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
9426     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
9427 }
9428 #endif
9429 
9430 #ifdef ENABLE_CLASSIC_PAIRING_OOB
9431 /**
9432  * @brief Report Remote OOB Data
9433  * @param bd_addr
9434  * @param c_192 Simple Pairing Hash C derived from P-192 public key
9435  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
9436  * @param c_256 Simple Pairing Hash C derived from P-256 public key
9437  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
9438  */
9439 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){
9440     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9441     if (connection == NULL) {
9442         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9443     }
9444     connection->classic_oob_c_192 = c_192;
9445     connection->classic_oob_r_192 = r_192;
9446 
9447     // ignore P-256 if not supported by us
9448     if (hci_stack->secure_connections_active){
9449         connection->classic_oob_c_256 = c_256;
9450         connection->classic_oob_r_256 = r_256;
9451     }
9452 
9453     return ERROR_CODE_SUCCESS;
9454 }
9455 /**
9456  * @brief Generate new OOB data
9457  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
9458  */
9459 void gap_ssp_generate_oob_data(void){
9460     hci_stack->classic_read_local_oob_data = true;
9461     hci_run();
9462 }
9463 
9464 #endif
9465 
9466 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
9467 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
9468     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9469     if (connection == NULL) {
9470         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9471     }
9472 
9473     memcpy(connection->link_key, link_key, sizeof(link_key_t));
9474     connection->link_key_type = type;
9475 
9476     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
9477 }
9478 
9479 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
9480 /**
9481  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
9482  * @param inquiry_mode see bluetooth_defines.h
9483  */
9484 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
9485     hci_stack->inquiry_mode = inquiry_mode;
9486 }
9487 
9488 /**
9489  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
9490  */
9491 void hci_set_sco_voice_setting(uint16_t voice_setting){
9492     hci_stack->sco_voice_setting = voice_setting;
9493 }
9494 
9495 /**
9496  * @brief Get SCO Voice Setting
9497  * @return current voice setting
9498  */
9499 uint16_t hci_get_sco_voice_setting(void){
9500     return hci_stack->sco_voice_setting;
9501 }
9502 
9503 static int hci_have_usb_transport(void){
9504     if (!hci_stack->hci_transport) return 0;
9505     const char * transport_name = hci_stack->hci_transport->name;
9506     if (!transport_name) return 0;
9507     return (transport_name[0] == 'H') && (transport_name[1] == '2');
9508 }
9509 
9510 static uint16_t hci_sco_packet_length_for_payload_length(uint16_t payload_size){
9511     uint16_t sco_packet_length = 0;
9512 
9513 #if defined(ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
9514     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
9515     int multiplier;
9516     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) &&
9517         ((hci_stack->sco_voice_setting_active & 0x20) == 0x20)) {
9518         multiplier = 2;
9519     } else {
9520         multiplier = 1;
9521     }
9522 #endif
9523 
9524 #ifdef ENABLE_SCO_OVER_HCI
9525     if (hci_have_usb_transport()){
9526         // see Core Spec for H2 USB Transfer.
9527         // 3 byte SCO header + 24 bytes per connection
9528         // @note multiple sco connections not supported currently
9529         sco_packet_length = 3 + 24 * multiplier;
9530     } else {
9531         // 3 byte SCO header + SCO packet length over the air
9532         sco_packet_length = 3 + payload_size * multiplier;
9533         // assert that it still fits inside an SCO buffer
9534         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
9535             sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9536         }
9537     }
9538 #endif
9539 #ifdef HAVE_SCO_TRANSPORT
9540     // 3 byte SCO header + SCO packet length over the air
9541     sco_packet_length = 3 + payload_size * multiplier;
9542     // assert that it still fits inside an SCO buffer
9543     if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
9544         sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9545     }
9546 #endif
9547     return sco_packet_length;
9548 }
9549 
9550 uint16_t hci_get_sco_packet_length_for_connection(hci_con_handle_t sco_con_handle){
9551     hci_connection_t * connection = hci_connection_for_handle(sco_con_handle);
9552     if (connection != NULL){
9553         return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);
9554     }
9555     return 0;
9556 }
9557 
9558 uint16_t hci_get_sco_packet_length(void){
9559     btstack_linked_list_iterator_t it;
9560     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9561     while (btstack_linked_list_iterator_has_next(&it)){
9562         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
9563         if ( connection->address_type == BD_ADDR_TYPE_SCO ) {
9564             return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);;
9565         }
9566     }
9567     return 0;
9568 }
9569 
9570 /**
9571 * @brief Sets the master/slave policy
9572 * @param policy (0: attempt to become master, 1: let connecting device decide)
9573 */
9574 void hci_set_master_slave_policy(uint8_t policy){
9575     hci_stack->master_slave_policy = policy;
9576 }
9577 
9578 #endif
9579 
9580 HCI_STATE hci_get_state(void){
9581     return hci_stack->state;
9582 }
9583 
9584 #ifdef ENABLE_CLASSIC
9585 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
9586     hci_stack->gap_classic_accept_callback = accept_callback;
9587 }
9588 #endif
9589 
9590 /**
9591  * @brief Set callback for Bluetooth Hardware Error
9592  */
9593 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
9594     hci_stack->hardware_error_callback = fn;
9595 }
9596 
9597 void hci_disconnect_all(void){
9598     btstack_linked_list_iterator_t it;
9599     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9600     while (btstack_linked_list_iterator_has_next(&it)){
9601         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9602         if (con->state == SENT_DISCONNECT) continue;
9603         con->state = SEND_DISCONNECT;
9604     }
9605     hci_run();
9606 }
9607 
9608 uint16_t hci_get_manufacturer(void){
9609     return hci_stack->manufacturer;
9610 }
9611 
9612 #ifdef ENABLE_BLE
9613 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
9614     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
9615     if (!hci_con) return NULL;
9616     return &hci_con->sm_connection;
9617 }
9618 
9619 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
9620 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
9621 #endif
9622 
9623 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
9624     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9625     if (hci_connection == NULL) return 0;
9626     if (hci_is_le_connection(hci_connection)){
9627 #ifdef ENABLE_BLE
9628         sm_connection_t * sm_conn = &hci_connection->sm_connection;
9629         if (sm_conn->sm_connection_encrypted != 0u) {
9630             return sm_conn->sm_actual_encryption_key_size;
9631         }
9632 #endif
9633     } else {
9634 #ifdef ENABLE_CLASSIC
9635         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
9636             return hci_connection->encryption_key_size;
9637         }
9638 #endif
9639     }
9640     return 0;
9641 }
9642 
9643 bool gap_authenticated(hci_con_handle_t con_handle){
9644     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9645     if (hci_connection == NULL) return false;
9646 
9647     switch (hci_connection->address_type){
9648 #ifdef ENABLE_BLE
9649         case BD_ADDR_TYPE_LE_PUBLIC:
9650         case BD_ADDR_TYPE_LE_RANDOM:
9651         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9652         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9653             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
9654             return hci_connection->sm_connection.sm_connection_authenticated != 0;
9655 #endif
9656 #ifdef ENABLE_CLASSIC
9657         case BD_ADDR_TYPE_SCO:
9658         case BD_ADDR_TYPE_ACL:
9659             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
9660 #endif
9661         default:
9662             return false;
9663     }
9664 }
9665 
9666 bool gap_secure_connection(hci_con_handle_t con_handle){
9667     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9668     if (hci_connection == NULL) return 0;
9669 
9670     switch (hci_connection->address_type){
9671 #ifdef ENABLE_BLE
9672         case BD_ADDR_TYPE_LE_PUBLIC:
9673         case BD_ADDR_TYPE_LE_RANDOM:
9674         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9675         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9676             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
9677             return hci_connection->sm_connection.sm_connection_sc;
9678 #endif
9679 #ifdef ENABLE_CLASSIC
9680         case BD_ADDR_TYPE_SCO:
9681         case BD_ADDR_TYPE_ACL:
9682             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
9683 #endif
9684         default:
9685             return false;
9686     }
9687 }
9688 
9689 bool gap_bonded(hci_con_handle_t con_handle){
9690 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9691 	if (hci_connection == NULL) return 0;
9692 
9693 #ifdef ENABLE_CLASSIC
9694 	link_key_t link_key;
9695 	link_key_type_t link_key_type;
9696 #endif
9697 	switch (hci_connection->address_type){
9698 #ifdef ENABLE_BLE
9699 		case BD_ADDR_TYPE_LE_PUBLIC:
9700 		case BD_ADDR_TYPE_LE_RANDOM:
9701 	    case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9702         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9703             return hci_connection->sm_connection.sm_le_db_index >= 0;
9704 #endif
9705 #ifdef ENABLE_CLASSIC
9706 		case BD_ADDR_TYPE_SCO:
9707 		case BD_ADDR_TYPE_ACL:
9708 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
9709 #endif
9710 		default:
9711 			return false;
9712 	}
9713 }
9714 
9715 #ifdef ENABLE_BLE
9716 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
9717     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
9718     if (sm_conn == NULL)                             return AUTHORIZATION_UNKNOWN; // wrong connection
9719     if (sm_conn->sm_connection_encrypted == 0u)      return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
9720     if (sm_conn->sm_connection_authenticated == 0u)  return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
9721     return sm_conn->sm_connection_authorization_state;
9722 }
9723 #endif
9724 
9725 #ifdef ENABLE_CLASSIC
9726 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){
9727     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9728     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9729     conn->sniff_min_interval = sniff_min_interval;
9730     conn->sniff_max_interval = sniff_max_interval;
9731     conn->sniff_attempt = sniff_attempt;
9732     conn->sniff_timeout = sniff_timeout;
9733     hci_run();
9734     return 0;
9735 }
9736 
9737 /**
9738  * @brief Exit Sniff mode
9739  * @param con_handle
9740  @ @return 0 if ok
9741  */
9742 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
9743     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9744     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9745     conn->sniff_min_interval = 0xffff;
9746     hci_run();
9747     return 0;
9748 }
9749 
9750 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){
9751     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9752     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9753     conn->sniff_subrating_max_latency = max_latency;
9754     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
9755     conn->sniff_subrating_min_local_timeout = min_local_timeout;
9756     hci_run();
9757     return ERROR_CODE_SUCCESS;
9758 }
9759 
9760 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){
9761     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9762     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9763     conn->qos_service_type = service_type;
9764     conn->qos_token_rate = token_rate;
9765     conn->qos_peak_bandwidth = peak_bandwidth;
9766     conn->qos_latency = latency;
9767     conn->qos_delay_variation = delay_variation;
9768     hci_run();
9769     return ERROR_CODE_SUCCESS;
9770 }
9771 
9772 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
9773     hci_stack->new_page_scan_interval = page_scan_interval;
9774     hci_stack->new_page_scan_window = page_scan_window;
9775     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
9776     hci_run();
9777 }
9778 
9779 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
9780     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
9781     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
9782     hci_run();
9783 }
9784 
9785 void gap_set_page_timeout(uint16_t page_timeout){
9786     hci_stack->page_timeout = page_timeout;
9787     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
9788     hci_run();
9789 }
9790 
9791 #endif
9792 
9793 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
9794 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
9795     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9796     if (le_device_db_index >= le_device_db_max_count()) return;
9797     uint8_t offset = le_device_db_index >> 3;
9798     uint8_t mask = 1 << (le_device_db_index & 7);
9799     hci_stack->le_resolving_list_add_entries[offset] |= mask;
9800     hci_stack->le_resolving_list_set_privacy_mode[offset] |= mask;
9801     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9802     	// note: go back to remove entries, otherwise, a remove + add will skip the add
9803         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9804     }
9805 }
9806 
9807 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
9808 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9809 	if (le_device_db_index >= le_device_db_max_count()) return;
9810 	uint8_t offset = le_device_db_index >> 3;
9811 	uint8_t mask = 1 << (le_device_db_index & 7);
9812 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
9813 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9814 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9815 	}
9816 }
9817 
9818 uint8_t gap_load_resolving_list_from_le_device_db(void){
9819     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
9820 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
9821 	}
9822 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
9823 		// restart le resolving list update
9824 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
9825 	}
9826 	return ERROR_CODE_SUCCESS;
9827 }
9828 
9829 void gap_set_peer_privacy_mode(le_privacy_mode_t privacy_mode ){
9830     hci_stack->le_privacy_mode = privacy_mode;
9831 }
9832 #endif
9833 
9834 #ifdef ENABLE_BLE
9835 #ifdef ENABLE_LE_CENTRAL
9836 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
9837 
9838 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9839 
9840 #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES) || (MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES == 0))
9841     // incorrect configuration:
9842     // - as MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES is not defined or zero this function always fails
9843     // - please set MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES in btstack_config.h
9844     btstack_assert(false);
9845 #endif
9846 
9847     // check if already in list
9848     btstack_linked_list_iterator_t it;
9849     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9850     while (btstack_linked_list_iterator_has_next(&it)) {
9851         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
9852         if (entry->sid != advertising_sid) {
9853             continue;
9854         }
9855         if (entry->address_type != address_type) {
9856             continue;
9857         }
9858         if (memcmp(entry->address, address, 6) != 0) {
9859             continue;
9860         }
9861         // disallow if already scheduled to add
9862         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
9863             return ERROR_CODE_COMMAND_DISALLOWED;
9864         }
9865         // still on controller, but scheduled to remove -> re-add
9866         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9867         return ERROR_CODE_SUCCESS;
9868     }
9869     // alloc and add to list
9870     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
9871     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9872     entry->sid = advertising_sid;
9873     entry->address_type = address_type;
9874     (void)memcpy(entry->address, address, 6);
9875     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9876     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
9877     return ERROR_CODE_SUCCESS;
9878 }
9879 
9880 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9881     btstack_linked_list_iterator_t it;
9882     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9883     while (btstack_linked_list_iterator_has_next(&it)){
9884         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9885         if (entry->sid != advertising_sid) {
9886             continue;
9887         }
9888         if (entry->address_type != address_type) {
9889             continue;
9890         }
9891         if (memcmp(entry->address, address, 6) != 0) {
9892             continue;
9893         }
9894         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9895             // remove from controller if already present
9896             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9897         }  else {
9898             // directly remove entry from whitelist
9899             btstack_linked_list_iterator_remove(&it);
9900             btstack_memory_periodic_advertiser_list_entry_free(entry);
9901         }
9902         return ERROR_CODE_SUCCESS;
9903     }
9904     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9905 }
9906 
9907 static void hci_periodic_advertiser_list_clear(void){
9908     btstack_linked_list_iterator_t it;
9909     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9910     while (btstack_linked_list_iterator_has_next(&it)){
9911         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9912         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9913             // remove from controller if already present
9914             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9915             continue;
9916         }
9917         // directly remove entry from whitelist
9918         btstack_linked_list_iterator_remove(&it);
9919         btstack_memory_periodic_advertiser_list_entry_free(entry);
9920     }
9921 }
9922 
9923 uint8_t gap_periodic_advertiser_list_clear(void){
9924     hci_periodic_advertiser_list_clear();
9925     hci_run();
9926     return ERROR_CODE_SUCCESS;
9927 }
9928 
9929 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9930     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
9931     if (status){
9932         return status;
9933     }
9934     hci_run();
9935     return ERROR_CODE_SUCCESS;
9936 }
9937 
9938 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9939     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
9940     if (status){
9941         return status;
9942     }
9943     hci_run();
9944     return ERROR_CODE_SUCCESS;
9945 }
9946 
9947 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
9948                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
9949     // abort if already active
9950     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
9951         return ERROR_CODE_COMMAND_DISALLOWED;
9952     }
9953     // store request
9954     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
9955     hci_stack->le_periodic_sync_options = options;
9956     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
9957     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
9958     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
9959     hci_stack->le_periodic_sync_skip = skip;
9960     hci_stack->le_periodic_sync_timeout = sync_timeout;
9961     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
9962 
9963     hci_run();
9964     return ERROR_CODE_SUCCESS;
9965 }
9966 
9967 uint8_t gap_periodic_advertising_create_sync_cancel(void){
9968     // abort if not requested
9969     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
9970         return ERROR_CODE_COMMAND_DISALLOWED;
9971     }
9972     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
9973     hci_run();
9974     return ERROR_CODE_SUCCESS;
9975 }
9976 
9977 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
9978     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
9979         return ERROR_CODE_COMMAND_DISALLOWED;
9980     }
9981     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
9982     hci_run();
9983     return ERROR_CODE_SUCCESS;
9984 }
9985 
9986 #endif
9987 #endif
9988 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
9989 static hci_iso_stream_t *
9990 hci_iso_stream_create(hci_iso_type_t iso_type, hci_iso_stream_state_t state, uint8_t group_id, uint8_t stream_id) {
9991     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
9992     if (iso_stream != NULL){
9993         iso_stream->iso_type = iso_type;
9994         iso_stream->state = state;
9995         iso_stream->group_id = group_id;
9996         iso_stream->stream_id = stream_id;
9997         iso_stream->cis_handle = HCI_CON_HANDLE_INVALID;
9998         iso_stream->acl_handle = HCI_CON_HANDLE_INVALID;
9999         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
10000     }
10001     return iso_stream;
10002 }
10003 
10004 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
10005     btstack_linked_list_iterator_t it;
10006     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10007     while (btstack_linked_list_iterator_has_next(&it)){
10008         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10009         if (iso_stream->cis_handle == con_handle ) {
10010             return iso_stream;
10011         }
10012     }
10013     return NULL;
10014 }
10015 
10016 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
10017     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->cis_handle, iso_stream->group_id);
10018     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
10019     btstack_memory_hci_iso_stream_free(iso_stream);
10020 }
10021 
10022 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
10023     btstack_linked_list_iterator_t it;
10024     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10025     while (btstack_linked_list_iterator_has_next(&it)){
10026         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10027         if ((iso_stream->group_id == group_id) &&
10028             (iso_stream->iso_type == iso_type)){
10029             btstack_linked_list_iterator_remove(&it);
10030             btstack_memory_hci_iso_stream_free(iso_stream);
10031         }
10032     }
10033 }
10034 
10035 static void hci_iso_stream_requested_finalize(uint8_t group_id) {
10036     btstack_linked_list_iterator_t it;
10037     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10038     while (btstack_linked_list_iterator_has_next(&it)){
10039         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10040         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
10041             (iso_stream->group_id == group_id)){
10042             btstack_linked_list_iterator_remove(&it);
10043             btstack_memory_hci_iso_stream_free(iso_stream);
10044         }
10045     }
10046 }
10047 static void hci_iso_stream_requested_confirm(uint8_t big_handle){
10048     btstack_linked_list_iterator_t it;
10049     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10050     while (btstack_linked_list_iterator_has_next(&it)){
10051         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10052         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
10053             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
10054         }
10055     }
10056 }
10057 
10058 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
10059     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
10060     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
10061     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
10062     return (sdu_len_offset + 2 + sdu_len) == size;
10063 }
10064 
10065 static void hci_iso_packet_handler(hci_iso_stream_t *iso_stream, uint8_t *packet, uint16_t size) {
10066     if (iso_stream == NULL){
10067         log_error("acl_handler called with non-registered handle %u!" , READ_ISO_CONNECTION_HANDLE(packet));
10068         return;
10069     }
10070 
10071     if (hci_stack->iso_packet_handler == NULL) {
10072         return;
10073     }
10074 
10075     // parse header
10076     uint16_t con_handle_and_flags = little_endian_read_16(packet, 0);
10077     uint16_t data_total_length = little_endian_read_16(packet, 2);
10078     uint8_t  pb_flag = (con_handle_and_flags >> 12) & 3;
10079 
10080     // assert packet is complete
10081     if ((data_total_length + 4u) != size){
10082         return;
10083     }
10084 
10085     if ((pb_flag & 0x01) == 0){
10086         if (pb_flag == 0x02){
10087             // The ISO_SDU_Fragment field contains a header and a complete SDU.
10088             if (hci_iso_sdu_complete(packet, size)) {
10089                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
10090             }
10091         } else {
10092             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
10093             if (size > sizeof(iso_stream->reassembly_buffer)){
10094                 return;
10095             }
10096             memcpy(iso_stream->reassembly_buffer, packet, size);
10097             // fix pb_flag
10098             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
10099             iso_stream->reassembly_pos = size;
10100         }
10101     } else {
10102         // ISO_SDU_Fragment contains continuation or last fragment of an SDU
10103         uint8_t ts_flag = (con_handle_and_flags >> 14) & 1;
10104         if (ts_flag != 0){
10105            return;
10106         }
10107         // append fragment
10108         if (iso_stream->reassembly_pos == 0){
10109             return;
10110         }
10111 
10112         if ((iso_stream->reassembly_pos + data_total_length) > sizeof(iso_stream->reassembly_buffer)){
10113             // reset reassembly buffer
10114             iso_stream->reassembly_pos = 0;
10115             return;
10116         }
10117         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], data_total_length);
10118         iso_stream->reassembly_pos += data_total_length;
10119 
10120         // deliver if last fragment and SDU complete
10121         if (pb_flag == 0x03){
10122             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
10123                 // fix data_total_length
10124                 little_endian_store_16(iso_stream->reassembly_buffer, 2, iso_stream->reassembly_pos - HCI_ISO_HEADER_SIZE);
10125                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
10126             }
10127             // reset reassembly buffer
10128             iso_stream->reassembly_pos = 0;
10129         }
10130     }
10131 }
10132 
10133 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
10134     uint8_t event [6 + (MAX_NR_BIS * 2)];
10135     uint16_t pos = 0;
10136     event[pos++] = HCI_EVENT_META_GAP;
10137     event[pos++] = 4 + (2 * big->num_bis);
10138     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
10139     event[pos++] = status;
10140     event[pos++] = big->big_handle;
10141     event[pos++] = big->num_bis;
10142     uint8_t i;
10143     for (i=0;i<big->num_bis;i++){
10144         little_endian_store_16(event, pos, big->bis_con_handles[i]);
10145         pos += 2;
10146     }
10147     hci_emit_event(event, pos, 0);
10148 }
10149 
10150 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
10151     uint8_t event [6 + (MAX_NR_CIS * 2)];
10152     uint16_t pos = 0;
10153     event[pos++] = HCI_EVENT_META_GAP;
10154     event[pos++] = 4 + (2 * cig->num_cis);
10155     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
10156     event[pos++] = status;
10157     event[pos++] = cig->cig_id;
10158     event[pos++] = cig->num_cis;
10159     uint8_t i;
10160     for (i=0;i<cig->num_cis;i++){
10161         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
10162         pos += 2;
10163     }
10164     hci_emit_event(event, pos, 0);
10165 }
10166 
10167 static uint16_t hci_setup_cis_created(uint8_t * event, hci_iso_stream_t * iso_stream, uint8_t status) {
10168     uint16_t pos = 0;
10169     event[pos++] = HCI_EVENT_META_GAP;
10170     event[pos++] = 8;
10171     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
10172     event[pos++] = status;
10173     event[pos++] = iso_stream->group_id;
10174     event[pos++] = iso_stream->stream_id;
10175     little_endian_store_16(event, pos, iso_stream->cis_handle);
10176     pos += 2;
10177     little_endian_store_16(event, pos, iso_stream->acl_handle);
10178     pos += 2;
10179     little_endian_store_16(event, pos, iso_stream->iso_interval_1250us);
10180     pos += 2;
10181     event[pos++] = iso_stream->number_of_subevents;
10182     event[pos++] = iso_stream->burst_number_c_to_p;
10183     event[pos++] = iso_stream->burst_number_p_to_c;
10184     event[pos++] = iso_stream->flush_timeout_c_to_p;
10185     event[pos++] = iso_stream->flush_timeout_p_to_c;
10186     return pos;
10187 }
10188 
10189 // emits GAP_SUBEVENT_CIS_CREATED after calling hci_iso_finalize
10190 static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status){
10191     // cache data before finalizing struct
10192     uint8_t event [17];
10193     uint16_t pos = hci_setup_cis_created(event, iso_stream, status);
10194     btstack_assert(pos <= sizeof(event));
10195     if (status != ERROR_CODE_SUCCESS){
10196         hci_iso_stream_finalize(iso_stream);
10197     }
10198     hci_emit_event(event, pos, 0);
10199 }
10200 
10201 static void hci_emit_big_terminated(const le_audio_big_t * big){
10202     uint8_t event [4];
10203     uint16_t pos = 0;
10204     event[pos++] = HCI_EVENT_META_GAP;
10205     event[pos++] = 2;
10206     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
10207     event[pos++] = big->big_handle;
10208     hci_emit_event(event, pos, 0);
10209 }
10210 
10211 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
10212     uint8_t event [6 + (MAX_NR_BIS * 2)];
10213     uint16_t pos = 0;
10214     event[pos++] = HCI_EVENT_META_GAP;
10215     event[pos++] = 4;
10216     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
10217     event[pos++] = status;
10218     event[pos++] = big_sync->big_handle;
10219     event[pos++] = big_sync->num_bis;
10220     uint8_t i;
10221     for (i=0;i<big_sync->num_bis;i++){
10222         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
10223         pos += 2;
10224     }
10225     hci_emit_event(event, pos, 0);
10226 }
10227 
10228 static void hci_emit_big_sync_stopped(uint8_t big_handle){
10229     uint8_t event [4];
10230     uint16_t pos = 0;
10231     event[pos++] = HCI_EVENT_META_GAP;
10232     event[pos++] = 2;
10233     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
10234     event[pos++] = big_handle;
10235     hci_emit_event(event, pos, 0);
10236 }
10237 
10238 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
10239     uint8_t event[6];
10240     uint16_t pos = 0;
10241     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
10242     event[pos++] = sizeof(event) - 2;
10243     event[pos++] = big->big_handle;
10244     event[pos++] = bis_index;
10245     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
10246     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
10247 }
10248 
10249 static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) {
10250     uint8_t event[4];
10251     uint16_t pos = 0;
10252     event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW;
10253     event[pos++] = sizeof(event) - 2;
10254     little_endian_store_16(event, pos, cis_con_handle);
10255     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
10256 }
10257 
10258 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
10259     btstack_linked_list_iterator_t it;
10260     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10261     while (btstack_linked_list_iterator_has_next(&it)){
10262         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10263         if ( big->big_handle == big_handle ) {
10264             return big;
10265         }
10266     }
10267     return NULL;
10268 }
10269 
10270 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
10271     btstack_linked_list_iterator_t it;
10272     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
10273     while (btstack_linked_list_iterator_has_next(&it)){
10274         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
10275         if ( big_sync->big_handle == big_handle ) {
10276             return big_sync;
10277         }
10278     }
10279     return NULL;
10280 }
10281 
10282 void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
10283     hci_stack->iso_packets_to_queue = num_packets;
10284 }
10285 
10286 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
10287     btstack_linked_list_iterator_t it;
10288     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
10289     while (btstack_linked_list_iterator_has_next(&it)){
10290         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
10291         if ( cig->cig_id == cig_id ) {
10292             return cig;
10293         }
10294     }
10295     return NULL;
10296 }
10297 
10298 static void hci_iso_notify_can_send_now(void){
10299 
10300     // BIG
10301 
10302     btstack_linked_list_iterator_t it;
10303     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10304     while (btstack_linked_list_iterator_has_next(&it)){
10305         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10306         // track number completed packet timestamps
10307         if (big->num_completed_timestamp_current_valid){
10308             big->num_completed_timestamp_current_valid = false;
10309             if (big->num_completed_timestamp_previous_valid){
10310                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
10311                 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
10312                 int32_t  num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
10313                                                                                big->num_completed_timestamp_previous_ms);
10314                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
10315                     // to catch up, skip packet on all BIS
10316                     uint8_t i;
10317                     for (i=0;i<big->num_bis;i++){
10318                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10319                         if (iso_stream){
10320                             iso_stream->num_packets_to_skip++;
10321                         }
10322                     }
10323                 }
10324             }
10325             big->num_completed_timestamp_previous_valid = true;
10326             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
10327         }
10328 
10329         if (big->can_send_now_requested){
10330             // check if no outgoing iso packets pending and no can send now have to be emitted
10331             uint8_t i;
10332             bool can_send = true;
10333             uint8_t num_iso_queued_minimum = 0;
10334             for (i=0;i<big->num_bis;i++){
10335                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10336                 if (iso_stream == NULL) continue;
10337                 // handle case where individual ISO packet was sent too late:
10338                 // for each additionally queued packet, a new one needs to get skipped
10339                 if (i==0){
10340                     num_iso_queued_minimum = iso_stream->num_packets_sent;
10341                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
10342                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
10343                     iso_stream->num_packets_to_skip += num_packets_to_skip;
10344                     iso_stream->num_packets_sent    -= num_packets_to_skip;
10345                 }
10346                 // check if we can send now
10347                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
10348                     can_send = false;
10349                     break;
10350                 }
10351             }
10352             if (can_send){
10353                 // propagate can send now to individual streams
10354                 big->can_send_now_requested = false;
10355                 for (i=0;i<big->num_bis;i++){
10356                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10357                     iso_stream->emit_ready_to_send = true;
10358                 }
10359             }
10360         }
10361     }
10362 
10363     if (hci_stack->hci_packet_buffer_reserved) return;
10364 
10365     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10366     while (btstack_linked_list_iterator_has_next(&it)){
10367         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10368         // report bis ready
10369         uint8_t i;
10370         for (i=0;i<big->num_bis;i++){
10371             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10372             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
10373                 iso_stream->emit_ready_to_send = false;
10374                 hci_emit_bis_can_send_now(big, i);
10375                 break;
10376             }
10377         }
10378     }
10379 
10380     // CIS
10381     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10382     while (btstack_linked_list_iterator_has_next(&it)) {
10383         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10384         if ((iso_stream->can_send_now_requested) &&
10385             (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){
10386             iso_stream->can_send_now_requested = false;
10387             hci_emit_cis_can_send_now(iso_stream->cis_handle);
10388         }
10389     }
10390 }
10391 
10392 static uint8_t gap_big_setup_iso_streams(uint8_t num_bis, uint8_t big_handle){
10393     // make big handle unique and usuable for big and big sync
10394     if (hci_big_for_handle(big_handle) != NULL){
10395         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10396     }
10397     if (hci_big_sync_for_handle(big_handle) != NULL){
10398         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10399     }
10400     if (num_bis == 0){
10401         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10402     }
10403     if (num_bis > MAX_NR_BIS){
10404         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10405     }
10406 
10407     // reserve ISO Streams
10408     uint8_t i;
10409     uint8_t status = ERROR_CODE_SUCCESS;
10410     for (i=0;i<num_bis;i++){
10411         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_ISO_STREAM_STATE_REQUESTED, big_handle, i);
10412         if (iso_stream == NULL) {
10413             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10414             break;
10415         }
10416     }
10417 
10418     // free structs on error
10419     if (status != ERROR_CODE_SUCCESS){
10420         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_handle);
10421     }
10422 
10423     return status;
10424 }
10425 
10426 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
10427     uint8_t status = gap_big_setup_iso_streams(big_params->num_bis, big_params->big_handle);
10428     if (status != ERROR_CODE_SUCCESS){
10429         return status;
10430     }
10431 
10432     le_audio_big_t * big = storage;
10433     big->big_handle = big_params->big_handle;
10434     big->params = big_params;
10435     big->state = LE_AUDIO_BIG_STATE_CREATE;
10436     big->num_bis = big_params->num_bis;
10437     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
10438 
10439     hci_run();
10440 
10441     return ERROR_CODE_SUCCESS;
10442 }
10443 
10444 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
10445     uint8_t status = gap_big_setup_iso_streams(big_sync_params->num_bis, big_sync_params->big_handle);
10446     if (status != ERROR_CODE_SUCCESS){
10447         return status;
10448     }
10449 
10450     le_audio_big_sync_t * big_sync = storage;
10451     big_sync->big_handle = big_sync_params->big_handle;
10452     big_sync->params = big_sync_params;
10453     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
10454     big_sync->num_bis = big_sync_params->num_bis;
10455     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10456 
10457     hci_run();
10458 
10459     return ERROR_CODE_SUCCESS;
10460 }
10461 
10462 uint8_t gap_big_terminate(uint8_t big_handle){
10463     le_audio_big_t * big = hci_big_for_handle(big_handle);
10464     if (big == NULL){
10465         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10466     }
10467     switch (big->state){
10468         case LE_AUDIO_BIG_STATE_CREATE:
10469             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
10470             hci_emit_big_terminated(big);
10471             break;
10472         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
10473             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
10474             break;
10475         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
10476         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
10477         case LE_AUDIO_BIG_STATE_ACTIVE:
10478             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
10479             hci_run();
10480             break;
10481         default:
10482             return ERROR_CODE_COMMAND_DISALLOWED;
10483     }
10484     return ERROR_CODE_SUCCESS;
10485 }
10486 
10487 uint8_t gap_big_sync_terminate(uint8_t big_handle){
10488     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
10489     if (big_sync == NULL){
10490         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10491     }
10492     switch (big_sync->state){
10493         case LE_AUDIO_BIG_STATE_CREATE:
10494             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10495             hci_emit_big_sync_stopped(big_handle);
10496             break;
10497         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
10498             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
10499             break;
10500         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
10501         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
10502         case LE_AUDIO_BIG_STATE_ACTIVE:
10503             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
10504             hci_run();
10505             break;
10506         default:
10507             return ERROR_CODE_COMMAND_DISALLOWED;
10508     }
10509     return ERROR_CODE_SUCCESS;
10510 }
10511 
10512 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
10513     le_audio_big_t * big = hci_big_for_handle(big_handle);
10514     if (big == NULL){
10515         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10516     }
10517     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
10518         return ERROR_CODE_COMMAND_DISALLOWED;
10519     }
10520     big->can_send_now_requested = true;
10521     hci_iso_notify_can_send_now();
10522     return ERROR_CODE_SUCCESS;
10523 }
10524 
10525 uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){
10526     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
10527     if (iso_stream == NULL){
10528         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10529     }
10530     if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) {
10531         return ERROR_CODE_COMMAND_DISALLOWED;
10532     }
10533     iso_stream->can_send_now_requested = true;
10534     hci_iso_notify_can_send_now();
10535     return ERROR_CODE_SUCCESS;
10536 }
10537 
10538 uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
10539     if (hci_cig_for_id(cig_params->cig_id) != NULL){
10540         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10541     }
10542     if (cig_params->num_cis == 0){
10543         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10544     }
10545     if (cig_params->num_cis > MAX_NR_CIS){
10546         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10547     }
10548 
10549     // reserve ISO Streams
10550     uint8_t i;
10551     uint8_t status = ERROR_CODE_SUCCESS;
10552     for (i=0;i<cig_params->num_cis;i++){
10553         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS,HCI_ISO_STREAM_STATE_REQUESTED, cig_params->cig_id, i);
10554         if (iso_stream == NULL) {
10555             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10556             break;
10557         }
10558     }
10559 
10560     // free structs on error
10561     if (status != ERROR_CODE_SUCCESS){
10562         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
10563         return status;
10564     }
10565 
10566     le_audio_cig_t * cig = storage;
10567     cig->cig_id = cig_params->cig_id;
10568     cig->num_cis = cig_params->num_cis;
10569     cig->params = cig_params;
10570     cig->state = LE_AUDIO_CIG_STATE_CREATE;
10571     for (i=0;i<cig->num_cis;i++){
10572         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
10573         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
10574         cig->cis_setup_active[i] = false;
10575         cig->cis_established[i] = false;
10576     }
10577     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
10578 
10579     hci_run();
10580 
10581     return ERROR_CODE_SUCCESS;
10582 }
10583 
10584 uint8_t gap_cig_remove(uint8_t cig_id){
10585     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10586     if (cig == NULL){
10587         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10588     }
10589 
10590     // close active CIS
10591     uint8_t i;
10592     for (i=0;i<cig->num_cis;i++){
10593         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
10594         if (stream != NULL){
10595             stream->state = HCI_ISO_STREAM_STATE_W2_CLOSE;
10596         }
10597     }
10598     cig->state = LE_AUDIO_CIG_STATE_REMOVE;
10599 
10600     hci_run();
10601 
10602     return ERROR_CODE_SUCCESS;
10603 }
10604 
10605 uint8_t gap_cis_create(uint8_t cig_id, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
10606     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10607     if (cig == NULL){
10608         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10609     }
10610 
10611     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
10612         return ERROR_CODE_COMMAND_DISALLOWED;
10613     }
10614 
10615     // store ACL Connection Handles
10616     uint8_t i;
10617     for (i=0;i<cig->num_cis;i++){
10618         // check that all con handles exist and store
10619         hci_con_handle_t cis_handle = cis_con_handles[i];
10620         if (cis_handle == HCI_CON_HANDLE_INVALID){
10621             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10622         }
10623         uint8_t j;
10624         bool found = false;
10625         for (j=0;j<cig->num_cis;j++){
10626             if (cig->cis_con_handles[j] == cis_handle){
10627                 cig->acl_con_handles[j] = acl_con_handles[j];
10628                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
10629                 btstack_assert(iso_stream != NULL);
10630                 iso_stream->acl_handle = acl_con_handles[j];
10631                 found = true;
10632                 break;
10633             }
10634         }
10635         if (!found){
10636             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10637         }
10638     }
10639 
10640     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
10641     hci_run();
10642 
10643     return ERROR_CODE_SUCCESS;
10644 }
10645 
10646 static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_handle, hci_iso_stream_state_t state){
10647     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
10648     if (iso_stream == NULL){
10649         // if we got a CIS Request but fail to allocate a hci_iso_stream_t object, we won't find it here
10650         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10651     }
10652 
10653     // set next state and continue
10654     iso_stream->state = state;
10655     hci_run();
10656     return ERROR_CODE_SUCCESS;
10657 }
10658 
10659 uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){
10660     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT);
10661 }
10662 
10663 uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){
10664     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT);
10665 }
10666 
10667 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
10668 
10669 // GAP Privacy - notify clients before random address update
10670 
10671 static bool gap_privacy_client_all_ready(void){
10672     // check if all ready
10673     btstack_linked_list_iterator_t it;
10674     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10675     while (btstack_linked_list_iterator_has_next(&it)) {
10676         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10677         if (client->state != GAP_PRIVACY_CLIENT_STATE_READY){
10678             return false;
10679         }
10680     }
10681     return true;
10682 }
10683 
10684 static void gap_privacy_clients_handle_ready(void){
10685     // clear 'ready'
10686     btstack_linked_list_iterator_t it;
10687     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10688     while (btstack_linked_list_iterator_has_next(&it)) {
10689         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10690         client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10691     }
10692     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
10693     hci_run();
10694 }
10695 
10696 static void gap_privacy_clients_notify(bd_addr_t new_random_address){
10697     btstack_linked_list_iterator_t it;
10698     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10699     while (btstack_linked_list_iterator_has_next(&it)) {
10700         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10701         if (client->state == GAP_PRIVACY_CLIENT_STATE_IDLE){
10702             client->state = GAP_PRIVACY_CLIENT_STATE_PENDING;
10703             (*client->callback)(client, new_random_address);
10704         }
10705     }
10706     if (gap_privacy_client_all_ready()){
10707         gap_privacy_clients_handle_ready();
10708     }
10709 }
10710 
10711 void gap_privacy_client_register(gap_privacy_client_t * client){
10712     client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10713     btstack_linked_list_add(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10714 }
10715 
10716 void gap_privacy_client_ready(gap_privacy_client_t * client){
10717     client->state = GAP_PRIVACY_CLIENT_STATE_READY;
10718     if (gap_privacy_client_all_ready()){
10719         gap_privacy_clients_handle_ready();
10720     }
10721 }
10722 
10723 void gap_privacy_client_unregister(gap_privacy_client_t * client){
10724     btstack_linked_list_remove(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10725 }
10726 
10727 #endif /* ENABLE_BLE */
10728 
10729 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
10730 void hci_setup_test_connections_fuzz(void){
10731     hci_connection_t * conn;
10732 
10733     // default address: 66:55:44:33:00:01
10734     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
10735 
10736     // setup Controller info
10737     hci_stack->num_cmd_packets = 255;
10738     hci_stack->acl_packets_total_num = 255;
10739 
10740     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
10741     addr[5] = 0x01;
10742     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
10743     conn->con_handle = addr[5];
10744     conn->state = RECEIVED_CONNECTION_REQUEST;
10745     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10746 
10747     // setup incoming Classic SCO connection with con handle 0x0002
10748     addr[5] = 0x02;
10749     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
10750     conn->con_handle = addr[5];
10751     conn->state = RECEIVED_CONNECTION_REQUEST;
10752     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10753 
10754     // setup ready Classic ACL connection with con handle 0x0003
10755     addr[5] = 0x03;
10756     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
10757     conn->con_handle = addr[5];
10758     conn->state = OPEN;
10759     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10760 
10761     // setup ready Classic SCO connection with con handle 0x0004
10762     addr[5] = 0x04;
10763     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
10764     conn->con_handle = addr[5];
10765     conn->state = OPEN;
10766     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10767 
10768     // setup ready LE ACL connection with con handle 0x005 and public address
10769     addr[5] = 0x05;
10770     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC, HCI_ROLE_SLAVE);
10771     conn->con_handle = addr[5];
10772     conn->state = OPEN;
10773     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10774     conn->sm_connection.sm_connection_encrypted = 1;
10775 }
10776 
10777 void hci_free_connections_fuzz(void){
10778     btstack_linked_list_iterator_t it;
10779     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
10780     while (btstack_linked_list_iterator_has_next(&it)){
10781         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
10782         btstack_linked_list_iterator_remove(&it);
10783         btstack_memory_hci_connection_free(con);
10784     }
10785 }
10786 void hci_simulate_working_fuzz(void){
10787     hci_stack->le_scanning_param_update = false;
10788     hci_init_done();
10789     hci_stack->num_cmd_packets = 255;
10790 }
10791 #endif
10792