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