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