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