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