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