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