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