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