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