xref: /btstack/src/hci.c (revision bbce5fac02e7c3fe4c462c8b329e4dc586c0f952)
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_setup_active[i] = false;
4094                                         cig->cis_established[i] = true;
4095                                     } else {
4096                                         hci_emit_cis_created(cig->cig_id, handle, status);
4097                                     }
4098                                 }
4099                             }
4100 
4101                             // trigger iso path setup if complete
4102                             bool setup_active = false;
4103                             for (i=0;i<cig->num_cis;i++){
4104                                 setup_active |= cig->cis_setup_active[i];
4105                             }
4106                             if (setup_active == false){
4107                                 cig->state_vars.next_cis = 0;
4108                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
4109                                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4110                             }
4111                         }
4112                     }
4113                     break;
4114                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
4115                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4116                     big = hci_big_for_handle(packet[4]);
4117                     if (big != NULL){
4118                         uint8_t status = packet[3];
4119                         if (status == ERROR_CODE_SUCCESS){
4120                             // store bis_con_handles and trigger iso path setup
4121                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[20]);
4122                             uint8_t i;
4123                             for (i=0;i<num_bis;i++){
4124                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4125                                 big->bis_con_handles[i] = bis_handle;
4126                                 // assign bis handle
4127                                 btstack_linked_list_iterator_t it;
4128                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4129                                 while (btstack_linked_list_iterator_has_next(&it)){
4130                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4131                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4132                                         (iso_stream->group_id == big->big_handle)){
4133                                         iso_stream->con_handle = bis_handle;
4134                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4135                                         break;
4136                                     }
4137                                 }
4138                             }
4139                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4140                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4141                                 big->state_vars.next_bis = 0;
4142                             }
4143                         } else {
4144                             // create BIG failed or has been stopped by us
4145                             hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
4146                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4147                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
4148                                 hci_emit_big_created(big, status);
4149                             } else {
4150                                 hci_emit_big_terminated(big);
4151                             }
4152                         }
4153                     }
4154                     break;
4155                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4156                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4157                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
4158                     if (big != NULL){
4159                         // finalize associated ISO streams
4160                         btstack_linked_list_iterator_t it;
4161                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4162                         while (btstack_linked_list_iterator_has_next(&it)){
4163                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4164                             if (iso_stream->group_id == big->big_handle){
4165                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->con_handle);
4166                                 btstack_linked_list_iterator_remove(&it);
4167                                 btstack_memory_hci_iso_stream_free(iso_stream);
4168                             }
4169                         }
4170                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4171                         switch (big->state){
4172                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
4173                                 hci_emit_big_created(big, big->state_vars.status);
4174                                 break;
4175                             default:
4176                                 hci_emit_big_terminated(big);
4177                                 break;
4178                         }
4179                     }
4180                     break;
4181                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4182                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4183                     big_sync = hci_big_sync_for_handle(packet[4]);
4184                     if (big_sync != NULL){
4185                         uint8_t status = packet[3];
4186                         uint8_t big_handle = packet[4];
4187                         if (status == ERROR_CODE_SUCCESS){
4188                             // store bis_con_handles and trigger iso path setup
4189                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[16]);
4190                             uint8_t i;
4191                             for (i=0;i<num_bis;i++){
4192                                 big_sync->bis_con_handles[i] = little_endian_read_16(packet, 17 + (2 * i));
4193                             }
4194                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4195                                 // trigger iso path setup
4196                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4197                                 big_sync->state_vars.next_bis = 0;
4198                             }
4199                         } else {
4200                             // create BIG Sync failed or has been stopped by us
4201                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4202                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4203                                 hci_emit_big_sync_created(big_sync, status);
4204                             } else {
4205                                 hci_emit_big_sync_stopped(big_handle);
4206                             }
4207                         }
4208                     }
4209                     break;
4210                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4211                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4212                     big_sync = hci_big_sync_for_handle(packet[4]);
4213                     if (big_sync != NULL){
4214                         uint8_t big_handle = packet[4];
4215                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4216                         hci_emit_big_sync_stopped(big_handle);
4217                     }
4218                     break;
4219 #endif
4220                 default:
4221                     break;
4222             }
4223             break;
4224 #endif
4225         case HCI_EVENT_VENDOR_SPECIFIC:
4226             // Vendor specific commands often create vendor specific event instead of num completed packets
4227             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
4228             switch (hci_stack->manufacturer){
4229                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
4230                     hci_stack->num_cmd_packets = 1;
4231                     break;
4232                 default:
4233                     break;
4234             }
4235             break;
4236         default:
4237             break;
4238     }
4239 
4240     handle_event_for_current_stack_state(packet, size);
4241 
4242     // notify upper stack
4243 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
4244 
4245     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4246     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4247 		handle = little_endian_read_16(packet, 3);
4248 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4249 		// discard connection if app did not trigger a reconnect in the event handler
4250 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
4251 			hci_shutdown_connection(aConn);
4252 		}
4253 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
4254         hci_controller_dump_packets();
4255 #endif
4256     }
4257 
4258 	// execute main loop
4259 	hci_run();
4260 }
4261 
4262 #ifdef ENABLE_CLASSIC
4263 
4264 #ifdef ENABLE_SCO_OVER_HCI
4265 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
4266 static void sco_schedule_tx(hci_connection_t * conn);
4267 
4268 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
4269     log_debug("SCO TX Timeout");
4270     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
4271     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4272     if (!conn) return;
4273 
4274     // trigger send
4275     conn->sco_tx_ready = 1;
4276     // extra packet if CVSD but SCO buffer is too short
4277     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
4278         conn->sco_tx_ready++;
4279     }
4280     hci_notify_if_sco_can_send_now();
4281 }
4282 
4283 
4284 #define SCO_TX_AFTER_RX_MS (6)
4285 
4286 static void sco_schedule_tx(hci_connection_t * conn){
4287 
4288     uint32_t now = btstack_run_loop_get_time_ms();
4289     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
4290     int time_delta_ms = sco_tx_ms - now;
4291 
4292     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
4293 
4294     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
4295     btstack_run_loop_remove_timer(timer);
4296     btstack_run_loop_set_timer(timer, time_delta_ms);
4297     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
4298     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
4299     btstack_run_loop_add_timer(timer);
4300 }
4301 #endif
4302 
4303 static void sco_handler(uint8_t * packet, uint16_t size){
4304     // lookup connection struct
4305     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
4306     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
4307     if (!conn) return;
4308 
4309 #ifdef ENABLE_SCO_OVER_HCI
4310     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4311     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4312         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4313             packet[2] = 0x3c;
4314             memmove(&packet[3], &packet[23], 63);
4315             size = 63;
4316         }
4317     }
4318 
4319     if (hci_have_usb_transport()){
4320         // Nothing to do
4321     } else {
4322         // 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);
4323         if (hci_stack->synchronous_flow_control_enabled == 0){
4324             uint32_t now = btstack_run_loop_get_time_ms();
4325 
4326             if (!conn->sco_rx_valid){
4327                 // ignore first 10 packets
4328                 conn->sco_rx_count++;
4329                 // log_debug("sco rx count %u", conn->sco_rx_count);
4330                 if (conn->sco_rx_count == 10) {
4331                     // use first timestamp as is and pretent it just started
4332                     conn->sco_rx_ms = now;
4333                     conn->sco_rx_valid = 1;
4334                     conn->sco_rx_count = 0;
4335                     sco_schedule_tx(conn);
4336                 }
4337             } else {
4338                 // track expected arrival timme
4339                 conn->sco_rx_count++;
4340                 conn->sco_rx_ms += 7;
4341                 int delta = (int32_t) (now - conn->sco_rx_ms);
4342                 if (delta > 0){
4343                     conn->sco_rx_ms++;
4344                 }
4345                 // log_debug("sco rx %u", conn->sco_rx_ms);
4346                 sco_schedule_tx(conn);
4347             }
4348         }
4349     }
4350 #endif
4351 
4352     // deliver to app
4353     if (hci_stack->sco_packet_handler) {
4354         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
4355     }
4356 
4357 #ifdef HAVE_SCO_TRANSPORT
4358     // We can send one packet for each received packet
4359     conn->sco_tx_ready++;
4360     hci_notify_if_sco_can_send_now();
4361 #endif
4362 
4363 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4364     conn->num_packets_completed++;
4365     hci_stack->host_completed_packets = 1;
4366     hci_run();
4367 #endif
4368 }
4369 #endif
4370 
4371 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
4372     hci_dump_packet(packet_type, 1, packet, size);
4373     switch (packet_type) {
4374         case HCI_EVENT_PACKET:
4375             event_handler(packet, size);
4376             break;
4377         case HCI_ACL_DATA_PACKET:
4378             acl_handler(packet, size);
4379             break;
4380 #ifdef ENABLE_CLASSIC
4381         case HCI_SCO_DATA_PACKET:
4382             sco_handler(packet, size);
4383             break;
4384 #endif
4385 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4386         case HCI_ISO_DATA_PACKET:
4387             hci_iso_packet_handler(packet, size);
4388             break;
4389 #endif
4390         default:
4391             break;
4392     }
4393 }
4394 
4395 /**
4396  * @brief Add event packet handler.
4397  */
4398 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4399     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4400 }
4401 
4402 /**
4403  * @brief Remove event packet handler.
4404  */
4405 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
4406     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4407 }
4408 
4409 /** Register HCI packet handlers */
4410 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4411     hci_stack->acl_packet_handler = handler;
4412 }
4413 
4414 #ifdef ENABLE_CLASSIC
4415 /**
4416  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
4417  */
4418 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
4419     hci_stack->sco_packet_handler = handler;
4420 }
4421 #endif
4422 
4423 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4424 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
4425     hci_stack->iso_packet_handler = handler;
4426 }
4427 #endif
4428 
4429 static void hci_state_reset(void){
4430     // no connections yet
4431     hci_stack->connections = NULL;
4432 
4433     // keep discoverable/connectable as this has been requested by the client(s)
4434     // hci_stack->discoverable = 0;
4435     // hci_stack->connectable = 0;
4436     // hci_stack->bondable = 1;
4437     // hci_stack->own_addr_type = 0;
4438 
4439     // buffer is free
4440     hci_stack->hci_packet_buffer_reserved = false;
4441 
4442     // no pending cmds
4443     hci_stack->decline_reason = 0;
4444 
4445     hci_stack->secure_connections_active = false;
4446 
4447 #ifdef ENABLE_CLASSIC
4448     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
4449     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
4450 
4451     hci_stack->gap_tasks_classic =
4452             GAP_TASK_SET_DEFAULT_LINK_POLICY |
4453             GAP_TASK_SET_CLASS_OF_DEVICE |
4454             GAP_TASK_SET_LOCAL_NAME |
4455             GAP_TASK_SET_EIR_DATA |
4456             GAP_TASK_WRITE_SCAN_ENABLE |
4457             GAP_TASK_WRITE_PAGE_TIMEOUT;
4458 #endif
4459 
4460 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4461     hci_stack->classic_read_local_oob_data = false;
4462     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4463 #endif
4464 
4465     // LE
4466 #ifdef ENABLE_BLE
4467     memset(hci_stack->le_random_address, 0, 6);
4468     hci_stack->le_random_address_set = 0;
4469 #endif
4470 #ifdef ENABLE_LE_CENTRAL
4471     hci_stack->le_scanning_active  = false;
4472     hci_stack->le_scanning_param_update = true;
4473     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4474     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4475     hci_stack->le_whitelist_capacity = 0;
4476 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4477     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
4478 #endif
4479 #endif
4480 #ifdef ENABLE_LE_PERIPHERAL
4481     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4482     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4483         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4484     }
4485     if (hci_stack->le_advertisements_data != NULL){
4486         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4487     }
4488 #endif
4489 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4490     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION;
4491 #endif
4492 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4493     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4494     hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID;
4495 #endif
4496 }
4497 
4498 #ifdef ENABLE_CLASSIC
4499 /**
4500  * @brief Configure Bluetooth hardware control. Has to be called before power on.
4501  */
4502 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
4503     // store and open remote device db
4504     hci_stack->link_key_db = link_key_db;
4505     if (hci_stack->link_key_db) {
4506         hci_stack->link_key_db->open();
4507     }
4508 }
4509 #endif
4510 
4511 void hci_init(const hci_transport_t *transport, const void *config){
4512 
4513 #ifdef HAVE_MALLOC
4514     if (!hci_stack) {
4515         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
4516     }
4517 #else
4518     hci_stack = &hci_stack_static;
4519 #endif
4520     memset(hci_stack, 0, sizeof(hci_stack_t));
4521 
4522     // reference to use transport layer implementation
4523     hci_stack->hci_transport = transport;
4524 
4525     // reference to used config
4526     hci_stack->config = config;
4527 
4528     // setup pointer for outgoing packet buffer
4529     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
4530 
4531     // max acl payload size defined in config.h
4532     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4533 
4534     // register packet handlers with transport
4535     transport->register_packet_handler(&packet_handler);
4536 
4537     hci_stack->state = HCI_STATE_OFF;
4538 
4539     // class of device
4540     hci_stack->class_of_device = 0x007a020c; // Smartphone
4541 
4542     // bondable by default
4543     hci_stack->bondable = 1;
4544 
4545 #ifdef ENABLE_CLASSIC
4546     // classic name
4547     hci_stack->local_name = default_classic_name;
4548 
4549     // Master slave policy
4550     hci_stack->master_slave_policy = 1;
4551 
4552     // Allow Role Switch
4553     hci_stack->allow_role_switch = 1;
4554 
4555     // Default / minimum security level = 2
4556     hci_stack->gap_security_level = LEVEL_2;
4557 
4558     // Default Security Mode 4
4559     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
4560 
4561     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4562     hci_stack->gap_required_encyrption_key_size = 7;
4563 
4564     // Link Supervision Timeout
4565     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4566 
4567 #endif
4568 
4569     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
4570     hci_stack->ssp_enable = 1;
4571     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
4572     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4573     hci_stack->ssp_auto_accept = 1;
4574 
4575     // Secure Connections: enable (requires support from Controller)
4576     hci_stack->secure_connections_enable = true;
4577 
4578     // voice setting - signed 16 bit pcm data with CVSD over the air
4579     hci_stack->sco_voice_setting = 0x60;
4580 
4581 #ifdef ENABLE_LE_CENTRAL
4582     // connection parameter to use for outgoing connections
4583     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
4584     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
4585     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
4586     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
4587     hci_stack->le_connection_latency      = 4;         // 4
4588     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
4589     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
4590     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
4591 
4592     // default LE Scanning
4593     hci_stack->le_scan_type     =   0x1; // active
4594     hci_stack->le_scan_interval = 0x1e0; // 300 ms
4595     hci_stack->le_scan_window   =  0x30; //  30 ms
4596 #endif
4597 
4598 #ifdef ENABLE_LE_PERIPHERAL
4599     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4600 #endif
4601 
4602     // connection parameter range used to answer connection parameter update requests in l2cap
4603     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4604     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4605     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4606     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4607     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4608     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4609 
4610 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4611     hci_stack->iso_packets_to_queue = 1;
4612 #endif
4613 
4614     hci_state_reset();
4615 }
4616 
4617 void hci_deinit(void){
4618     btstack_run_loop_remove_timer(&hci_stack->timeout);
4619 #ifdef HAVE_MALLOC
4620     if (hci_stack) {
4621         free(hci_stack);
4622     }
4623 #endif
4624     hci_stack = NULL;
4625 
4626 #ifdef ENABLE_CLASSIC
4627     disable_l2cap_timeouts = 0;
4628 #endif
4629 }
4630 
4631 /**
4632  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
4633  */
4634 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
4635     hci_stack->chipset = chipset_driver;
4636 
4637     // reset chipset driver - init is also called on power_up
4638     if (hci_stack->chipset && hci_stack->chipset->init){
4639         hci_stack->chipset->init(hci_stack->config);
4640     }
4641 }
4642 
4643 /**
4644  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
4645  */
4646 void hci_set_control(const btstack_control_t *hardware_control){
4647     // references to used control implementation
4648     hci_stack->control = hardware_control;
4649     // init with transport config
4650     hardware_control->init(hci_stack->config);
4651 }
4652 
4653 static void hci_discard_connections(void){
4654     btstack_linked_list_iterator_t it;
4655     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4656     while (btstack_linked_list_iterator_has_next(&it)){
4657         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
4658         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4659         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
4660         hci_shutdown_connection(connection);
4661     }
4662 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4663     while (hci_stack->iso_streams != NULL){
4664         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
4665     }
4666 #endif
4667 }
4668 
4669 void hci_close(void){
4670 
4671 #ifdef ENABLE_CLASSIC
4672     // close remote device db
4673     if (hci_stack->link_key_db) {
4674         hci_stack->link_key_db->close();
4675     }
4676 #endif
4677 
4678     hci_discard_connections();
4679 
4680     hci_power_control(HCI_POWER_OFF);
4681 
4682 #ifdef HAVE_MALLOC
4683     free(hci_stack);
4684 #endif
4685     hci_stack = NULL;
4686 }
4687 
4688 #ifdef HAVE_SCO_TRANSPORT
4689 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
4690     hci_stack->sco_transport = sco_transport;
4691     sco_transport->register_packet_handler(&packet_handler);
4692 }
4693 #endif
4694 
4695 #ifdef ENABLE_CLASSIC
4696 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
4697     // validate ranage and set
4698     if (encryption_key_size < 7)  return;
4699     if (encryption_key_size > 16) return;
4700     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
4701 }
4702 
4703 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
4704     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
4705         hci_stack->gap_security_mode = security_mode;
4706         return ERROR_CODE_SUCCESS;
4707     } else {
4708         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
4709     }
4710 }
4711 
4712 gap_security_mode_t gap_get_security_mode(void){
4713     return hci_stack->gap_security_mode;
4714 }
4715 
4716 void gap_set_security_level(gap_security_level_t security_level){
4717     hci_stack->gap_security_level = security_level;
4718 }
4719 
4720 gap_security_level_t gap_get_security_level(void){
4721     if (hci_stack->gap_secure_connections_only_mode){
4722         return LEVEL_4;
4723     }
4724     return hci_stack->gap_security_level;
4725 }
4726 
4727 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
4728     hci_stack->gap_minimal_service_security_level = security_level;
4729 }
4730 
4731 void gap_set_secure_connections_only_mode(bool enable){
4732     hci_stack->gap_secure_connections_only_mode = enable;
4733 }
4734 
4735 bool gap_get_secure_connections_only_mode(void){
4736     return hci_stack->gap_secure_connections_only_mode;
4737 }
4738 #endif
4739 
4740 #ifdef ENABLE_CLASSIC
4741 void gap_set_class_of_device(uint32_t class_of_device){
4742     hci_stack->class_of_device = class_of_device;
4743     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
4744     hci_run();
4745 }
4746 
4747 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4748     hci_stack->default_link_policy_settings = default_link_policy_settings;
4749     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
4750     hci_run();
4751 }
4752 
4753 void gap_set_allow_role_switch(bool allow_role_switch){
4754     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4755 }
4756 
4757 uint8_t hci_get_allow_role_switch(void){
4758     return  hci_stack->allow_role_switch;
4759 }
4760 
4761 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
4762     hci_stack->link_supervision_timeout = link_supervision_timeout;
4763 }
4764 
4765 void gap_enable_link_watchdog(uint16_t timeout_ms){
4766     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
4767 }
4768 
4769 uint16_t hci_automatic_flush_timeout(void){
4770     return hci_stack->automatic_flush_timeout;
4771 }
4772 
4773 void hci_disable_l2cap_timeout_check(void){
4774     disable_l2cap_timeouts = 1;
4775 }
4776 #endif
4777 
4778 #ifndef HAVE_HOST_CONTROLLER_API
4779 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4780 void hci_set_bd_addr(bd_addr_t addr){
4781     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4782     hci_stack->custom_bd_addr_set = 1;
4783 }
4784 #endif
4785 
4786 // State-Module-Driver overview
4787 // state                    module  low-level
4788 // HCI_STATE_OFF             off      close
4789 // HCI_STATE_INITIALIZING,   on       open
4790 // HCI_STATE_WORKING,        on       open
4791 // HCI_STATE_HALTING,        on       open
4792 // HCI_STATE_SLEEPING,    off/sleep   close
4793 // HCI_STATE_FALLING_ASLEEP  on       open
4794 
4795 static int hci_power_control_on(void){
4796 
4797     // power on
4798     int err = 0;
4799     if (hci_stack->control && hci_stack->control->on){
4800         err = (*hci_stack->control->on)();
4801     }
4802     if (err){
4803         log_error( "POWER_ON failed");
4804         hci_emit_hci_open_failed();
4805         return err;
4806     }
4807 
4808     // int chipset driver
4809     if (hci_stack->chipset && hci_stack->chipset->init){
4810         hci_stack->chipset->init(hci_stack->config);
4811     }
4812 
4813     // init transport
4814     if (hci_stack->hci_transport->init){
4815         hci_stack->hci_transport->init(hci_stack->config);
4816     }
4817 
4818     // open transport
4819     err = hci_stack->hci_transport->open();
4820     if (err){
4821         log_error( "HCI_INIT failed, turning Bluetooth off again");
4822         if (hci_stack->control && hci_stack->control->off){
4823             (*hci_stack->control->off)();
4824         }
4825         hci_emit_hci_open_failed();
4826         return err;
4827     }
4828     return 0;
4829 }
4830 
4831 static void hci_power_control_off(void){
4832 
4833     log_info("hci_power_control_off");
4834 
4835     // close low-level device
4836     hci_stack->hci_transport->close();
4837 
4838     log_info("hci_power_control_off - hci_transport closed");
4839 
4840     // power off
4841     if (hci_stack->control && hci_stack->control->off){
4842         (*hci_stack->control->off)();
4843     }
4844 
4845     log_info("hci_power_control_off - control closed");
4846 
4847     hci_stack->state = HCI_STATE_OFF;
4848 }
4849 
4850 static void hci_power_control_sleep(void){
4851 
4852     log_info("hci_power_control_sleep");
4853 
4854 #if 0
4855     // don't close serial port during sleep
4856 
4857     // close low-level device
4858     hci_stack->hci_transport->close(hci_stack->config);
4859 #endif
4860 
4861     // sleep mode
4862     if (hci_stack->control && hci_stack->control->sleep){
4863         (*hci_stack->control->sleep)();
4864     }
4865 
4866     hci_stack->state = HCI_STATE_SLEEPING;
4867 }
4868 
4869 static int hci_power_control_wake(void){
4870 
4871     log_info("hci_power_control_wake");
4872 
4873     // wake on
4874     if (hci_stack->control && hci_stack->control->wake){
4875         (*hci_stack->control->wake)();
4876     }
4877 
4878 #if 0
4879     // open low-level device
4880     int err = hci_stack->hci_transport->open(hci_stack->config);
4881     if (err){
4882         log_error( "HCI_INIT failed, turning Bluetooth off again");
4883         if (hci_stack->control && hci_stack->control->off){
4884             (*hci_stack->control->off)();
4885         }
4886         hci_emit_hci_open_failed();
4887         return err;
4888     }
4889 #endif
4890 
4891     return 0;
4892 }
4893 
4894 static void hci_power_enter_initializing_state(void){
4895     // set up state machine
4896     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
4897     hci_stack->hci_packet_buffer_reserved = false;
4898     hci_stack->state = HCI_STATE_INITIALIZING;
4899     hci_stack->substate = HCI_INIT_SEND_RESET;
4900 }
4901 
4902 static void hci_power_enter_halting_state(void){
4903 #ifdef ENABLE_BLE
4904     // drop entries scheduled for removal, mark others for re-adding
4905     btstack_linked_list_iterator_t it;
4906     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4907     while (btstack_linked_list_iterator_has_next(&it)){
4908         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4909         if ((entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)) == LE_WHITELIST_REMOVE_FROM_CONTROLLER){
4910             btstack_linked_list_iterator_remove(&it);
4911             btstack_memory_whitelist_entry_free(entry);
4912         } else {
4913             entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4914         }
4915     }
4916 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4917     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
4918     const uint8_t mask = LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
4919     while (btstack_linked_list_iterator_has_next(&it)){
4920         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
4921         if ((entry->state & mask) == LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER) {
4922             btstack_linked_list_iterator_remove(&it);
4923             btstack_memory_periodic_advertiser_list_entry_free(entry);
4924         } else {
4925             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
4926             continue;
4927         }
4928     }
4929 #endif
4930 #endif
4931     // see hci_run
4932     hci_stack->state = HCI_STATE_HALTING;
4933     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
4934     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
4935     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
4936     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4937     btstack_run_loop_add_timer(&hci_stack->timeout);
4938 }
4939 
4940 // returns error
4941 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
4942     int err;
4943     switch (power_mode){
4944         case HCI_POWER_ON:
4945             err = hci_power_control_on();
4946             if (err != 0) {
4947                 log_error("hci_power_control_on() error %d", err);
4948                 return err;
4949             }
4950             hci_power_enter_initializing_state();
4951             break;
4952         case HCI_POWER_OFF:
4953             // do nothing
4954             break;
4955         case HCI_POWER_SLEEP:
4956             // do nothing (with SLEEP == OFF)
4957             break;
4958         default:
4959             btstack_assert(false);
4960             break;
4961     }
4962     return ERROR_CODE_SUCCESS;
4963 }
4964 
4965 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
4966     switch (power_mode){
4967         case HCI_POWER_ON:
4968             // do nothing
4969             break;
4970         case HCI_POWER_OFF:
4971             // no connections yet, just turn it off
4972             hci_power_control_off();
4973             break;
4974         case HCI_POWER_SLEEP:
4975             // no connections yet, just turn it off
4976             hci_power_control_sleep();
4977             break;
4978         default:
4979             btstack_assert(false);
4980             break;
4981     }
4982     return ERROR_CODE_SUCCESS;
4983 }
4984 
4985 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
4986     switch (power_mode){
4987         case HCI_POWER_ON:
4988             // do nothing
4989             break;
4990         case HCI_POWER_OFF:
4991             hci_power_enter_halting_state();
4992             break;
4993         case HCI_POWER_SLEEP:
4994             // see hci_run
4995             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4996             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4997             break;
4998         default:
4999             btstack_assert(false);
5000             break;
5001     }
5002     return ERROR_CODE_SUCCESS;
5003 }
5004 
5005 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
5006     switch (power_mode){
5007         case HCI_POWER_ON:
5008             hci_power_enter_initializing_state();
5009             break;
5010         case HCI_POWER_OFF:
5011             // do nothing
5012             break;
5013         case HCI_POWER_SLEEP:
5014             // see hci_run
5015             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5016             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5017             break;
5018         default:
5019             btstack_assert(false);
5020             break;
5021     }
5022     return ERROR_CODE_SUCCESS;
5023 }
5024 
5025 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
5026     switch (power_mode){
5027         case HCI_POWER_ON:
5028             hci_power_enter_initializing_state();
5029             break;
5030         case HCI_POWER_OFF:
5031             hci_power_enter_halting_state();
5032             break;
5033         case HCI_POWER_SLEEP:
5034             // do nothing
5035             break;
5036         default:
5037             btstack_assert(false);
5038             break;
5039     }
5040     return ERROR_CODE_SUCCESS;
5041 }
5042 
5043 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
5044     int err;
5045     switch (power_mode){
5046         case HCI_POWER_ON:
5047             err = hci_power_control_wake();
5048             if (err) return err;
5049             hci_power_enter_initializing_state();
5050             break;
5051         case HCI_POWER_OFF:
5052             hci_power_enter_halting_state();
5053             break;
5054         case HCI_POWER_SLEEP:
5055             // do nothing
5056             break;
5057         default:
5058             btstack_assert(false);
5059             break;
5060     }
5061     return ERROR_CODE_SUCCESS;
5062 }
5063 
5064 int hci_power_control(HCI_POWER_MODE power_mode){
5065     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
5066     btstack_run_loop_remove_timer(&hci_stack->timeout);
5067     int err = 0;
5068     switch (hci_stack->state){
5069         case HCI_STATE_OFF:
5070             err = hci_power_control_state_off(power_mode);
5071             break;
5072         case HCI_STATE_INITIALIZING:
5073             err = hci_power_control_state_initializing(power_mode);
5074             break;
5075         case HCI_STATE_WORKING:
5076             err = hci_power_control_state_working(power_mode);
5077             break;
5078         case HCI_STATE_HALTING:
5079             err = hci_power_control_state_halting(power_mode);
5080             break;
5081         case HCI_STATE_FALLING_ASLEEP:
5082             err = hci_power_control_state_falling_asleep(power_mode);
5083             break;
5084         case HCI_STATE_SLEEPING:
5085             err = hci_power_control_state_sleeping(power_mode);
5086             break;
5087         default:
5088             btstack_assert(false);
5089             break;
5090     }
5091     if (err != 0){
5092         return err;
5093     }
5094 
5095     // create internal event
5096 	hci_emit_state();
5097 
5098 	// trigger next/first action
5099 	hci_run();
5100 
5101     return 0;
5102 }
5103 
5104 
5105 static void hci_halting_run(void) {
5106 
5107     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5108 
5109     hci_connection_t *connection;
5110 #ifdef ENABLE_BLE
5111 #ifdef ENABLE_LE_PERIPHERAL
5112     bool stop_advertismenets;
5113 #endif
5114 #endif
5115 
5116     switch (hci_stack->substate) {
5117         case HCI_HALTING_CLASSIC_STOP:
5118 #ifdef ENABLE_CLASSIC
5119             if (!hci_can_send_command_packet_now()) return;
5120 
5121             if (hci_stack->connectable || hci_stack->discoverable){
5122                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5123                 hci_send_cmd(&hci_write_scan_enable, 0);
5124                 return;
5125             }
5126 #endif
5127             /* fall through */
5128 
5129         case HCI_HALTING_LE_ADV_STOP:
5130             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5131 
5132 #ifdef ENABLE_BLE
5133 #ifdef ENABLE_LE_PERIPHERAL
5134             if (!hci_can_send_command_packet_now()) return;
5135 
5136             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5137 
5138 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5139             if (hci_extended_advertising_supported()){
5140 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5141                 btstack_linked_list_iterator_t it;
5142                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5143                 // stop all periodic advertisements and check if an extended set is active
5144                 while (btstack_linked_list_iterator_has_next(&it)){
5145                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5146                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5147                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5148                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
5149                         return;
5150                     }
5151                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5152                         stop_advertismenets = true;
5153                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5154                     }
5155                 }
5156 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5157                 if (stop_advertismenets){
5158                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5159                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5160                     return;
5161                 }
5162             }
5163             else
5164 #else /* ENABLE_LE_PERIPHERAL */
5165             {
5166                 if (stop_advertismenets) {
5167                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5168                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5169                     return;
5170                 }
5171             }
5172 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5173 #endif  /* ENABLE_LE_PERIPHERAL */
5174 #endif  /* ENABLE_BLE */
5175 
5176             /* fall through */
5177 
5178         case HCI_HALTING_LE_SCAN_STOP:
5179             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5180             if (!hci_can_send_command_packet_now()) return;
5181 
5182 #ifdef ENABLE_BLE
5183 #ifdef ENABLE_LE_CENTRAL
5184             if (hci_stack->le_scanning_active){
5185                 hci_le_scan_stop();
5186                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5187                 return;
5188             }
5189 #endif
5190 #endif
5191 
5192             /* fall through */
5193 
5194         case HCI_HALTING_DISCONNECT_ALL:
5195             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5196             if (!hci_can_send_command_packet_now()) return;
5197 
5198             // close all open connections
5199             connection = (hci_connection_t *) hci_stack->connections;
5200             if (connection) {
5201                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5202 
5203                 log_info("HCI_STATE_HALTING, connection %p, handle %u, state %u", connection, con_handle, connection->state);
5204 
5205                 // check state
5206                 switch(connection->state) {
5207                     case SENT_DISCONNECT:
5208                     case RECEIVED_DISCONNECTION_COMPLETE:
5209                         // wait until connection is gone
5210                         return;
5211                     default:
5212                         break;
5213                 }
5214 
5215                 // finally, send the disconnect command
5216                 connection->state = SENT_DISCONNECT;
5217                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5218                 return;
5219             }
5220 
5221 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5222             // stop BIGs and BIG Syncs
5223             if (hci_stack->le_audio_bigs != NULL){
5224                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5225                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5226                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5227                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5228                 return;
5229             }
5230             if (hci_stack->le_audio_big_syncs != NULL){
5231                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5232                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5233                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5234                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5235                 return;
5236             }
5237 #endif
5238 
5239             btstack_run_loop_remove_timer(&hci_stack->timeout);
5240 
5241             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5242             log_info("HCI_STATE_HALTING: wait 50 ms");
5243             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5244             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5245             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5246             btstack_run_loop_add_timer(&hci_stack->timeout);
5247             break;
5248 
5249         case HCI_HALTING_W4_CLOSE_TIMER:
5250             // keep waiting
5251             break;
5252 
5253         case HCI_HALTING_CLOSE:
5254             // close left over connections (that had not been properly closed before)
5255             hci_stack->substate = HCI_HALTING_CLOSE_DISCARDING_CONNECTIONS;
5256             hci_discard_connections();
5257 
5258             log_info("HCI_STATE_HALTING, calling off");
5259 
5260             // switch mode
5261             hci_power_control_off();
5262 
5263             log_info("HCI_STATE_HALTING, emitting state");
5264             hci_emit_state();
5265             log_info("HCI_STATE_HALTING, done");
5266             break;
5267 
5268         default:
5269             break;
5270     }
5271 };
5272 
5273 static void hci_falling_asleep_run(void){
5274     hci_connection_t * connection;
5275     switch(hci_stack->substate) {
5276         case HCI_FALLING_ASLEEP_DISCONNECT:
5277             log_info("HCI_STATE_FALLING_ASLEEP");
5278             // close all open connections
5279             connection =  (hci_connection_t *) hci_stack->connections;
5280             if (connection){
5281 
5282                 // send disconnect
5283                 if (!hci_can_send_command_packet_now()) return;
5284 
5285                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5286                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5287 
5288                 // send disconnected event right away - causes higher layer connections to get closed, too.
5289                 hci_shutdown_connection(connection);
5290                 return;
5291             }
5292 
5293             if (hci_classic_supported()){
5294                 // disable page and inquiry scan
5295                 if (!hci_can_send_command_packet_now()) return;
5296 
5297                 log_info("HCI_STATE_HALTING, disabling inq scans");
5298                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5299 
5300                 // continue in next sub state
5301                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5302                 break;
5303             }
5304 
5305             /* fall through */
5306 
5307             case HCI_FALLING_ASLEEP_COMPLETE:
5308                 log_info("HCI_STATE_HALTING, calling sleep");
5309                 // switch mode
5310                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5311                 hci_emit_state();
5312                 break;
5313 
5314                 default:
5315                     break;
5316     }
5317 }
5318 
5319 #ifdef ENABLE_CLASSIC
5320 
5321 static void hci_update_scan_enable(void){
5322     // 2 = page scan, 1 = inq scan
5323     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5324     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5325     hci_run();
5326 }
5327 
5328 void gap_discoverable_control(uint8_t enable){
5329     if (enable) enable = 1; // normalize argument
5330 
5331     if (hci_stack->discoverable == enable){
5332         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5333         return;
5334     }
5335 
5336     hci_stack->discoverable = enable;
5337     hci_update_scan_enable();
5338 }
5339 
5340 void gap_connectable_control(uint8_t enable){
5341     if (enable) enable = 1; // normalize argument
5342 
5343     // don't emit event
5344     if (hci_stack->connectable == enable) return;
5345 
5346     hci_stack->connectable = enable;
5347     hci_update_scan_enable();
5348 }
5349 #endif
5350 
5351 void gap_local_bd_addr(bd_addr_t address_buffer){
5352     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5353 }
5354 
5355 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5356 static void hci_host_num_completed_packets(void){
5357 
5358     // create packet manually as arrays are not supported and num_commands should not get reduced
5359     hci_reserve_packet_buffer();
5360     uint8_t * packet = hci_get_outgoing_packet_buffer();
5361 
5362     uint16_t size = 0;
5363     uint16_t num_handles = 0;
5364     packet[size++] = 0x35;
5365     packet[size++] = 0x0c;
5366     size++;  // skip param len
5367     size++;  // skip num handles
5368 
5369     // add { handle, packets } entries
5370     btstack_linked_item_t * it;
5371     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5372         hci_connection_t * connection = (hci_connection_t *) it;
5373         if (connection->num_packets_completed){
5374             little_endian_store_16(packet, size, connection->con_handle);
5375             size += 2;
5376             little_endian_store_16(packet, size, connection->num_packets_completed);
5377             size += 2;
5378             //
5379             num_handles++;
5380             connection->num_packets_completed = 0;
5381         }
5382     }
5383 
5384     packet[2] = size - 3;
5385     packet[3] = num_handles;
5386 
5387     hci_stack->host_completed_packets = 0;
5388 
5389     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5390     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5391 
5392     // release packet buffer for synchronous transport implementations
5393     if (hci_transport_synchronous()){
5394         hci_release_packet_buffer();
5395         hci_emit_transport_packet_sent();
5396     }
5397 }
5398 #endif
5399 
5400 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5401     UNUSED(ds);
5402     hci_stack->substate = HCI_HALTING_CLOSE;
5403     hci_halting_run();
5404 }
5405 
5406 static bool hci_run_acl_fragments(void){
5407     if (hci_stack->acl_fragmentation_total_size > 0u) {
5408         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5409         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5410         if (connection) {
5411             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5412                 hci_send_acl_packet_fragments(connection);
5413                 return true;
5414             }
5415         } else {
5416             // connection gone -> discard further fragments
5417             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5418             hci_stack->acl_fragmentation_total_size = 0;
5419             hci_stack->acl_fragmentation_pos = 0;
5420         }
5421     }
5422     return false;
5423 }
5424 
5425 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5426 static bool hci_run_iso_fragments(void){
5427     if (hci_stack->iso_fragmentation_total_size > 0u) {
5428         // TODO: flow control
5429         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5430             hci_send_iso_packet_fragments();
5431             return true;
5432         }
5433     }
5434     return false;
5435 }
5436 #endif
5437 
5438 #ifdef ENABLE_CLASSIC
5439 
5440 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5441 static bool hci_classic_operation_active(void) {
5442     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5443         return true;
5444     }
5445     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5446         return true;
5447     }
5448     btstack_linked_item_t * it;
5449     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5450         hci_connection_t *connection = (hci_connection_t *) it;
5451         switch (connection->state) {
5452             case SENT_CREATE_CONNECTION:
5453             case SENT_CANCEL_CONNECTION:
5454             case SENT_DISCONNECT:
5455                 return true;
5456             default:
5457                 break;
5458         }
5459     }
5460     return false;
5461 }
5462 #endif
5463 
5464 static bool hci_run_general_gap_classic(void){
5465 
5466     // assert stack is working and classic is active
5467     if (hci_classic_supported() == false)      return false;
5468     if (hci_stack->state != HCI_STATE_WORKING) return false;
5469 
5470     // decline incoming connections
5471     if (hci_stack->decline_reason){
5472         uint8_t reason = hci_stack->decline_reason;
5473         hci_stack->decline_reason = 0;
5474         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5475         return true;
5476     }
5477 
5478     if (hci_stack->gap_tasks_classic != 0){
5479         hci_run_gap_tasks_classic();
5480         return true;
5481     }
5482 
5483     // start/stop inquiry
5484     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5485 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5486         if (hci_classic_operation_active() == false)
5487 #endif
5488         {
5489             uint8_t duration = hci_stack->inquiry_state;
5490             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5491             if (hci_stack->inquiry_max_period_length != 0){
5492                 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);
5493             } else {
5494                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5495             }
5496             return true;
5497         }
5498     }
5499     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5500         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5501         hci_send_cmd(&hci_inquiry_cancel);
5502         return true;
5503     }
5504 
5505     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5506         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5507         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5508         return true;
5509     }
5510 
5511     // remote name request
5512     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5513 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5514         if (hci_classic_operation_active() == false)
5515 #endif
5516         {
5517             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5518             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5519                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5520             return true;
5521         }
5522     }
5523 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5524     // Local OOB data
5525     if (hci_stack->classic_read_local_oob_data){
5526         hci_stack->classic_read_local_oob_data = false;
5527         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5528             hci_send_cmd(&hci_read_local_extended_oob_data);
5529         } else {
5530             hci_send_cmd(&hci_read_local_oob_data);
5531         }
5532     }
5533 #endif
5534     // pairing
5535     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5536         uint8_t state = hci_stack->gap_pairing_state;
5537         uint8_t pin_code[16];
5538         switch (state){
5539             case GAP_PAIRING_STATE_SEND_PIN:
5540                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5541                 memset(pin_code, 0, 16);
5542                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5543                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5544                 break;
5545             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5546                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5547                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5548                 break;
5549             case GAP_PAIRING_STATE_SEND_PASSKEY:
5550                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5551                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5552                 break;
5553             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5554                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5555                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5556                 break;
5557             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5558                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5559                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5560                 break;
5561             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5562                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5563                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5564                 break;
5565             default:
5566                 break;
5567         }
5568         return true;
5569     }
5570     return false;
5571 }
5572 #endif
5573 
5574 #ifdef ENABLE_BLE
5575 
5576 #ifdef ENABLE_LE_CENTRAL
5577 static void hci_le_scan_stop(void){
5578 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5579     if (hci_extended_advertising_supported()) {
5580             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5581         } else
5582 #endif
5583     {
5584         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5585     }
5586 }
5587 
5588 static void
5589 hci_send_le_create_connection(uint8_t initiator_filter_policy, bd_addr_type_t address_type, uint8_t *address) {
5590 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5591     if (hci_extended_advertising_supported()) {
5592         uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval };
5593         uint16_t le_connection_scan_window[1]   = { hci_stack->le_connection_scan_window };
5594         uint16_t le_connection_interval_min[1]  = { hci_stack->le_connection_interval_min };
5595         uint16_t le_connection_interval_max[1]  = { hci_stack->le_connection_interval_max };
5596         uint16_t le_connection_latency[1]       = { hci_stack->le_connection_latency };
5597         uint16_t le_supervision_timeout[1]      = { hci_stack->le_supervision_timeout };
5598         uint16_t le_minimum_ce_length[1]        = { hci_stack->le_minimum_ce_length };
5599         uint16_t le_maximum_ce_length[1]        = { hci_stack->le_maximum_ce_length };
5600         hci_send_cmd(&hci_le_extended_create_connection,
5601                      initiator_filter_policy,
5602                      hci_stack->le_connection_own_addr_type,   // our addr type:
5603                      address_type,                  // peer address type
5604                      address,                       // peer bd addr
5605                      1,                             // initiating PHY - 1M
5606                      le_connection_scan_interval,   // conn scan interval
5607                      le_connection_scan_window,     // conn scan windows
5608                      le_connection_interval_min,    // conn interval min
5609                      le_connection_interval_max,    // conn interval max
5610                      le_connection_latency,         // conn latency
5611                      le_supervision_timeout,        // conn latency
5612                      le_minimum_ce_length,          // min ce length
5613                      le_maximum_ce_length           // max ce length
5614         );
5615     }
5616     else
5617 #endif
5618     {
5619         hci_send_cmd(&hci_le_create_connection,
5620                      hci_stack->le_connection_scan_interval,  // conn scan interval
5621                      hci_stack->le_connection_scan_window,    // conn scan windows
5622                      initiator_filter_policy,                 // don't use whitelist
5623                      address_type,                            // peer address type
5624                      address,                                 // peer bd addr
5625                      hci_stack->le_connection_own_addr_type,  // our addr type:
5626                      hci_stack->le_connection_interval_min,   // conn interval min
5627                      hci_stack->le_connection_interval_max,   // conn interval max
5628                      hci_stack->le_connection_latency,        // conn latency
5629                      hci_stack->le_supervision_timeout,       // conn latency
5630                      hci_stack->le_minimum_ce_length,         // min ce length
5631                      hci_stack->le_maximum_ce_length          // max ce length
5632         );
5633     }
5634 }
5635 #endif
5636 
5637 #ifdef ENABLE_LE_PERIPHERAL
5638 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5639 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
5640     uint8_t  operation = 0;
5641     if (pos == 0){
5642         // first fragment or complete data
5643         operation |= 1;
5644     }
5645     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
5646         // last fragment or complete data
5647         operation |= 2;
5648     }
5649     return operation;
5650 }
5651 #endif
5652 #endif
5653 
5654 static bool hci_run_general_gap_le(void){
5655 
5656     btstack_linked_list_iterator_t lit;
5657 
5658     // Phase 1: collect what to stop
5659 
5660 #ifdef ENABLE_LE_CENTRAL
5661     bool scanning_stop = false;
5662     bool connecting_stop = false;
5663 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5664 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5665     bool periodic_sync_stop = false;
5666 #endif
5667 #endif
5668 #endif
5669 
5670 #ifdef ENABLE_LE_PERIPHERAL
5671     bool advertising_stop = false;
5672 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5673     le_advertising_set_t * advertising_stop_set = NULL;
5674 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5675     bool periodic_advertising_stop = false;
5676 #endif
5677 #endif
5678 #endif
5679 
5680     // check if own address changes
5681     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5682 
5683     // check if whitelist needs modification
5684     bool whitelist_modification_pending = false;
5685     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5686     while (btstack_linked_list_iterator_has_next(&lit)){
5687         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5688         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
5689             whitelist_modification_pending = true;
5690             break;
5691         }
5692     }
5693 
5694     // check if resolving list needs modification
5695     bool resolving_list_modification_pending = false;
5696 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5697     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
5698 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
5699         resolving_list_modification_pending = true;
5700     }
5701 #endif
5702 
5703 #ifdef ENABLE_LE_CENTRAL
5704 
5705 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5706     // check if periodic advertiser list needs modification
5707     bool periodic_list_modification_pending = false;
5708     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5709     while (btstack_linked_list_iterator_has_next(&lit)){
5710         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5711         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
5712             periodic_list_modification_pending = true;
5713             break;
5714         }
5715     }
5716 #endif
5717 
5718     // scanning control
5719     if (hci_stack->le_scanning_active) {
5720         // stop if:
5721         // - parameter change required
5722         // - it's disabled
5723         // - whitelist change required but used for scanning
5724         // - resolving list modified
5725         // - own address changes
5726         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
5727         if ((hci_stack->le_scanning_param_update) ||
5728             !hci_stack->le_scanning_enabled ||
5729             (scanning_uses_whitelist && whitelist_modification_pending) ||
5730             resolving_list_modification_pending ||
5731             random_address_change){
5732 
5733             scanning_stop = true;
5734         }
5735     }
5736 
5737     // connecting control
5738     bool connecting_with_whitelist;
5739     switch (hci_stack->le_connecting_state){
5740         case LE_CONNECTING_DIRECT:
5741         case LE_CONNECTING_WHITELIST:
5742             // stop connecting if:
5743             // - connecting uses white and whitelist modification pending
5744             // - if it got disabled
5745             // - resolving list modified
5746             // - own address changes
5747             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
5748             if ((connecting_with_whitelist && whitelist_modification_pending) ||
5749                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
5750                 resolving_list_modification_pending ||
5751                 random_address_change) {
5752 
5753                 connecting_stop = true;
5754             }
5755             break;
5756         default:
5757             break;
5758     }
5759 
5760 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5761 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5762     // periodic sync control
5763     bool sync_with_advertiser_list;
5764     switch(hci_stack->le_periodic_sync_state){
5765         case LE_CONNECTING_DIRECT:
5766         case LE_CONNECTING_WHITELIST:
5767             // stop sync if:
5768             // - sync with advertiser list and advertiser list modification pending
5769             // - if it got disabled
5770             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
5771             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
5772                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
5773                 periodic_sync_stop = true;
5774             }
5775             break;
5776         default:
5777             break;
5778     }
5779 #endif
5780 #endif
5781 
5782 #endif /* ENABLE_LE_CENTRAL */
5783 
5784 #ifdef ENABLE_LE_PERIPHERAL
5785     // le advertisement control
5786     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
5787         // stop if:
5788         // - parameter change required
5789         // - random address used in advertising and changes
5790         // - it's disabled
5791         // - whitelist change required but used for advertisement filter policy
5792         // - resolving list modified
5793         // - own address changes
5794         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
5795         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
5796         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
5797         if (advertising_change ||
5798             (advertising_uses_random_address && random_address_change) ||
5799             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
5800             (advertising_uses_whitelist && whitelist_modification_pending) ||
5801             resolving_list_modification_pending ||
5802             random_address_change) {
5803 
5804             advertising_stop = true;
5805         }
5806     }
5807 
5808 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5809     if (hci_extended_advertising_supported() && (advertising_stop == false)){
5810         btstack_linked_list_iterator_t it;
5811         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5812         while (btstack_linked_list_iterator_has_next(&it)){
5813             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5814             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5815                 // stop if:
5816                 // - parameter change required
5817                 // - random address used in connectable advertising and changes
5818                 // - it's disabled
5819                 // - whitelist change required but used for advertisement filter policy
5820                 // - resolving list modified
5821                 // - own address changes
5822                 // - advertisement set will be removed
5823                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
5824                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
5825                 bool advertising_uses_random_address =
5826                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
5827                         advertising_connectable;
5828                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
5829                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
5830                 bool advertising_set_random_address_change =
5831                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5832                 bool advertising_set_will_be_removed =
5833                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
5834                 if (advertising_parameter_change ||
5835                     (advertising_uses_random_address && advertising_set_random_address_change) ||
5836                     (advertising_enabled == false) ||
5837                     (advertising_uses_whitelist && whitelist_modification_pending) ||
5838                     resolving_list_modification_pending ||
5839                     advertising_set_will_be_removed) {
5840 
5841                     advertising_stop = true;
5842                     advertising_stop_set = advertising_set;
5843                     break;
5844                 }
5845             }
5846 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5847             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5848                 // stop if:
5849                 // - it's disabled
5850                 // - parameter change required
5851                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
5852                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
5853                 if ((periodic_enabled == false) || periodic_parameter_change){
5854                     periodic_advertising_stop = true;
5855                     advertising_stop_set = advertising_set;
5856                 }
5857             }
5858 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5859         }
5860     }
5861 #endif
5862 
5863 #endif
5864 
5865 
5866     // Phase 2: stop everything that should be off during modifications
5867 
5868 
5869     // 2.1 Outgoing connection
5870 #ifdef ENABLE_LE_CENTRAL
5871     if (connecting_stop){
5872         hci_send_cmd(&hci_le_create_connection_cancel);
5873         return true;
5874     }
5875 #endif
5876 
5877     // 2.2 Scanning
5878 #ifdef ENABLE_LE_CENTRAL
5879     if (scanning_stop){
5880         hci_stack->le_scanning_active = false;
5881         hci_le_scan_stop();
5882         return true;
5883     }
5884 
5885     // 2.3 Periodic Sync
5886 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5887     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
5888         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
5889         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
5890         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
5891         return true;
5892     }
5893 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5894     if (periodic_sync_stop){
5895         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
5896         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
5897         return true;
5898     }
5899 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5900 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5901 #endif /* ENABLE_LE_CENTRAL */
5902 
5903     // 2.4 Advertising: legacy, extended, periodic
5904 #ifdef ENABLE_LE_PERIPHERAL
5905     if (advertising_stop){
5906 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5907         if (hci_extended_advertising_supported()) {
5908             uint8_t advertising_stop_handle;
5909             if (advertising_stop_set != NULL){
5910                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5911                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5912             } else {
5913                 advertising_stop_handle = 0;
5914                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5915             }
5916             const uint8_t advertising_handles[] = { advertising_stop_handle };
5917             const uint16_t durations[] = { 0 };
5918             const uint16_t max_events[] = { 0 };
5919             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5920         } else
5921 #endif
5922         {
5923             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5924             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5925         }
5926         return true;
5927     }
5928 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5929 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5930     if (periodic_advertising_stop){
5931         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5932         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
5933         return true;
5934     }
5935 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5936 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5937 #endif /* ENABLE_LE_PERIPHERAL */
5938 
5939 
5940     // Phase 3: modify
5941 
5942     if (random_address_change){
5943         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5944 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5945         if (hci_extended_advertising_supported()) {
5946             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5947         }
5948 #endif
5949         {
5950             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5951         }
5952         return true;
5953     }
5954 
5955 #ifdef ENABLE_LE_CENTRAL
5956     if (hci_stack->le_scanning_param_update){
5957         hci_stack->le_scanning_param_update = false;
5958 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5959         if (hci_extended_advertising_supported()){
5960             // prepare arrays for all PHYs
5961             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
5962             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
5963             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
5964             uint8_t  scanning_phys     = 1;  // LE 1M PHY
5965             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
5966                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
5967         } else
5968 #endif
5969         {
5970             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5971                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
5972         }
5973         return true;
5974     }
5975 #endif
5976 
5977 #ifdef ENABLE_LE_PERIPHERAL
5978     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
5979         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5980         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5981 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5982         if (hci_extended_advertising_supported()){
5983             // map advertisment type to advertising event properties
5984             uint16_t adv_event_properties = 0;
5985             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5986             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5987                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5988             }
5989             hci_stack->le_advertising_set_in_current_command = 0;
5990             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5991                          0,
5992                          adv_event_properties,
5993                          hci_stack->le_advertisements_interval_min,
5994                          hci_stack->le_advertisements_interval_max,
5995                          hci_stack->le_advertisements_channel_map,
5996                          hci_stack->le_advertisements_own_addr_type,
5997                          hci_stack->le_advertisements_direct_address_type,
5998                          hci_stack->le_advertisements_direct_address,
5999                          hci_stack->le_advertisements_filter_policy,
6000                          0x7f,  // tx power: no preference
6001                          0x01,  // primary adv phy: LE 1M
6002                          0,     // secondary adv max skip
6003                          0,     // secondary adv phy
6004                          0,     // adv sid
6005                          0      // scan request notification
6006                          );
6007         }
6008 #endif
6009         {
6010             hci_send_cmd(&hci_le_set_advertising_parameters,
6011                          hci_stack->le_advertisements_interval_min,
6012                          hci_stack->le_advertisements_interval_max,
6013                          hci_stack->le_advertisements_type,
6014                          hci_stack->le_advertisements_own_addr_type,
6015                          hci_stack->le_advertisements_direct_address_type,
6016                          hci_stack->le_advertisements_direct_address,
6017                          hci_stack->le_advertisements_channel_map,
6018                          hci_stack->le_advertisements_filter_policy);
6019         }
6020         return true;
6021     }
6022 
6023     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
6024         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6025         uint8_t adv_data_clean[31];
6026         memset(adv_data_clean, 0, sizeof(adv_data_clean));
6027         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
6028                      hci_stack->le_advertisements_data_len);
6029         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
6030 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6031         if (hci_extended_advertising_supported()){
6032             hci_stack->le_advertising_set_in_current_command = 0;
6033             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
6034         } else
6035 #endif
6036         {
6037             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
6038         }
6039         return true;
6040     }
6041 
6042     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
6043         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6044         uint8_t scan_data_clean[31];
6045         memset(scan_data_clean, 0, sizeof(scan_data_clean));
6046         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
6047                      hci_stack->le_scan_response_data_len);
6048         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6049 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6050         if (hci_extended_advertising_supported()){
6051             hci_stack->le_advertising_set_in_current_command = 0;
6052             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6053         } else
6054 #endif
6055         {
6056             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6057         }
6058         return true;
6059     }
6060 
6061 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6062     if (hci_extended_advertising_supported()) {
6063         btstack_linked_list_iterator_t it;
6064         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6065         while (btstack_linked_list_iterator_has_next(&it)){
6066             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6067             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6068                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6069                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6070                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6071                 return true;
6072             }
6073             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
6074                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6075                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
6076                 return true;
6077             }
6078             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6079                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6080                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6081                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6082                              advertising_set->advertising_handle,
6083                              advertising_set->extended_params.advertising_event_properties,
6084                              advertising_set->extended_params.primary_advertising_interval_min,
6085                              advertising_set->extended_params.primary_advertising_interval_max,
6086                              advertising_set->extended_params.primary_advertising_channel_map,
6087                              advertising_set->extended_params.own_address_type,
6088                              advertising_set->extended_params.peer_address_type,
6089                              advertising_set->extended_params.peer_address,
6090                              advertising_set->extended_params.advertising_filter_policy,
6091                              advertising_set->extended_params.advertising_tx_power,
6092                              advertising_set->extended_params.primary_advertising_phy,
6093                              advertising_set->extended_params.secondary_advertising_max_skip,
6094                              advertising_set->extended_params.secondary_advertising_phy,
6095                              advertising_set->extended_params.advertising_sid,
6096                              advertising_set->extended_params.scan_request_notification_enable
6097                 );
6098                 return true;
6099             }
6100             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6101                 uint16_t pos = advertising_set->adv_data_pos;
6102                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6103                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6104                 if ((operation & 0x02) != 0){
6105                     // last fragment or complete data
6106                     operation |= 2;
6107                     advertising_set->adv_data_pos = 0;
6108                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6109                 } else {
6110                     advertising_set->adv_data_pos += data_to_upload;
6111                 }
6112                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6113                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6114                 return true;
6115             }
6116             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6117                 uint16_t pos = advertising_set->scan_data_pos;
6118                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6119                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6120                 if ((operation & 0x02) != 0){
6121                     advertising_set->scan_data_pos = 0;
6122                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6123                 } else {
6124                     advertising_set->scan_data_pos += data_to_upload;
6125                 }
6126                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6127                 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]);
6128                 return true;
6129             }
6130 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6131             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
6132                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
6133                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6134                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
6135                              advertising_set->advertising_handle,
6136                              advertising_set->periodic_params.periodic_advertising_interval_min,
6137                              advertising_set->periodic_params.periodic_advertising_interval_max,
6138                              advertising_set->periodic_params.periodic_advertising_properties);
6139                 return true;
6140             }
6141             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
6142                 uint16_t pos = advertising_set->periodic_data_pos;
6143                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
6144                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6145                 if ((operation & 0x02) != 0){
6146                     // last fragment or complete data
6147                     operation |= 2;
6148                     advertising_set->periodic_data_pos = 0;
6149                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
6150                 } else {
6151                     advertising_set->periodic_data_pos += data_to_upload;
6152                 }
6153                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6154                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
6155                 return true;
6156             }
6157 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6158         }
6159     }
6160 #endif
6161 
6162 #endif
6163 
6164 #ifdef ENABLE_LE_CENTRAL
6165     // if connect with whitelist was active and is not cancelled yet, wait until next time
6166     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
6167 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6168     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
6169     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
6170 #endif
6171 #endif
6172 
6173     // LE Whitelist Management
6174     if (whitelist_modification_pending){
6175         // add/remove entries
6176         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6177         while (btstack_linked_list_iterator_has_next(&lit)){
6178             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6179 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
6180 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6181 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
6182 				return true;
6183 			}
6184             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
6185 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
6186                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
6187                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
6188                 return true;
6189             }
6190             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
6191 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6192 				btstack_memory_whitelist_entry_free(entry);
6193             }
6194         }
6195     }
6196 
6197 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6198     // LE Resolving List Management
6199     if (resolving_list_supported) {
6200 		uint16_t i;
6201 		switch (hci_stack->le_resolving_list_state) {
6202 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
6203 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6204 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
6205 				return true;
6206 			case LE_RESOLVING_LIST_READ_SIZE:
6207 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
6208 				hci_send_cmd(&hci_le_read_resolving_list_size);
6209 				return true;
6210 			case LE_RESOLVING_LIST_SEND_CLEAR:
6211 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
6212 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6213 							  sizeof(hci_stack->le_resolving_list_add_entries));
6214 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6215 							  sizeof(hci_stack->le_resolving_list_remove_entries));
6216 				hci_send_cmd(&hci_le_clear_resolving_list);
6217 				return true;
6218 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
6219                 // first remove old entries
6220 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6221 					uint8_t offset = i >> 3;
6222 					uint8_t mask = 1 << (i & 7);
6223 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
6224 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
6225 					bd_addr_t peer_identity_addreses;
6226 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6227 					sm_key_t peer_irk;
6228 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6229 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6230 
6231 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6232 					// trigger whitelist entry 'update' (work around for controller bug)
6233 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6234 					while (btstack_linked_list_iterator_has_next(&lit)) {
6235 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6236 						if (entry->address_type != peer_identity_addr_type) continue;
6237 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6238 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6239 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6240 					}
6241 #endif
6242 
6243 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6244 								 peer_identity_addreses);
6245 					return true;
6246 				}
6247 
6248                 // then add new entries
6249 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6250 					uint8_t offset = i >> 3;
6251 					uint8_t mask = 1 << (i & 7);
6252 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
6253 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
6254 					bd_addr_t peer_identity_addreses;
6255 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6256 					sm_key_t peer_irk;
6257 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6258 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6259                     if (btstack_is_null(peer_irk, 16)) continue;
6260 					const uint8_t *local_irk = gap_get_persistent_irk();
6261 					// command uses format specifier 'P' that stores 16-byte value without flip
6262 					uint8_t local_irk_flipped[16];
6263 					uint8_t peer_irk_flipped[16];
6264 					reverse_128(local_irk, local_irk_flipped);
6265 					reverse_128(peer_irk, peer_irk_flipped);
6266 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6267 								 peer_irk_flipped, local_irk_flipped);
6268 					return true;
6269 				}
6270 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6271 				break;
6272 
6273 			default:
6274 				break;
6275 		}
6276 	}
6277     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6278 #endif
6279 
6280 #ifdef ENABLE_LE_CENTRAL
6281 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6282     // LE Whitelist Management
6283     if (periodic_list_modification_pending){
6284         // add/remove entries
6285         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6286         while (btstack_linked_list_iterator_has_next(&lit)){
6287             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6288             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6289                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6290                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
6291                 return true;
6292             }
6293             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6294                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6295                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
6296                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6297                 return true;
6298             }
6299             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6300                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6301                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6302             }
6303         }
6304     }
6305 #endif
6306 #endif
6307 
6308 #ifdef ENABLE_LE_CENTRAL
6309 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6310 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6311     if (hci_stack->le_past_set_default_params){
6312         hci_stack->le_past_set_default_params = false;
6313         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
6314                      hci_stack->le_past_mode,
6315                      hci_stack->le_past_skip,
6316                      hci_stack->le_past_sync_timeout,
6317                      hci_stack->le_past_cte_type);
6318         return true;
6319     }
6320 #endif
6321 #endif
6322 #endif
6323 
6324     // post-pone all actions until stack is fully working
6325     if (hci_stack->state != HCI_STATE_WORKING) return false;
6326 
6327     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6328     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6329 
6330     // Phase 4: restore state
6331 
6332 #ifdef ENABLE_LE_CENTRAL
6333     // re-start scanning
6334     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6335         hci_stack->le_scanning_active = true;
6336 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6337         if (hci_extended_advertising_supported()){
6338             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
6339         } else
6340 #endif
6341         {
6342             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
6343         }
6344         return true;
6345     }
6346 #endif
6347 
6348 #ifdef ENABLE_LE_CENTRAL
6349     // re-start connecting
6350     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6351         bd_addr_t null_addr;
6352         memset(null_addr, 0, 6);
6353         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6354         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6355         hci_send_le_create_connection(1, 0, null_addr);
6356         return true;
6357     }
6358 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6359     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6360         switch(hci_stack->le_periodic_sync_request){
6361             case LE_CONNECTING_DIRECT:
6362             case LE_CONNECTING_WHITELIST:
6363                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6364                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6365                              hci_stack->le_periodic_sync_options,
6366                              hci_stack->le_periodic_sync_advertising_sid,
6367                              hci_stack->le_periodic_sync_advertiser_address_type,
6368                              hci_stack->le_periodic_sync_advertiser_address,
6369                              hci_stack->le_periodic_sync_skip,
6370                              hci_stack->le_periodic_sync_timeout,
6371                              hci_stack->le_periodic_sync_cte_type);
6372                 return true;
6373             default:
6374                 break;
6375         }
6376     }
6377 #endif
6378 #endif
6379 
6380 #ifdef ENABLE_LE_PERIPHERAL
6381     // re-start advertising
6382     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6383         // check if advertisements should be enabled given
6384         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6385         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6386 
6387 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6388         if (hci_extended_advertising_supported()){
6389             const uint8_t advertising_handles[] = { 0 };
6390             const uint16_t durations[] = { 0 };
6391             const uint16_t max_events[] = { 0 };
6392             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6393         } else
6394 #endif
6395         {
6396             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6397         }
6398         return true;
6399     }
6400 
6401 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6402     if (hci_extended_advertising_supported()) {
6403         btstack_linked_list_iterator_t it;
6404         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6405         while (btstack_linked_list_iterator_has_next(&it)) {
6406             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6407             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6408                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6409                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6410                 const uint16_t durations[] = { advertising_set->enable_timeout };
6411                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6412                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6413                 return true;
6414             }
6415 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6416             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6417                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6418                 uint8_t enable = 1;
6419                 if (advertising_set->periodic_include_adi){
6420                     enable |= 2;
6421                 }
6422                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6423                 return true;
6424             }
6425 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6426         }
6427     }
6428 #endif
6429 #endif
6430 
6431     return false;
6432 }
6433 
6434 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6435 static bool hci_run_iso_tasks(void){
6436     btstack_linked_list_iterator_t it;
6437 
6438     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
6439         return false;
6440     }
6441 
6442     // BIG
6443     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6444     while (btstack_linked_list_iterator_has_next(&it)){
6445         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6446         switch (big->state){
6447             case LE_AUDIO_BIG_STATE_CREATE:
6448                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
6449                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6450                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6451                 hci_send_cmd(&hci_le_create_big,
6452                              big->params->big_handle,
6453                              big->params->advertising_handle,
6454                              big->params->num_bis,
6455                              big->params->sdu_interval_us,
6456                              big->params->max_sdu,
6457                              big->params->max_transport_latency_ms,
6458                              big->params->rtn,
6459                              big->params->phy,
6460                              big->params->packing,
6461                              big->params->framing,
6462                              big->params->encryption,
6463                              big->params->broadcast_code);
6464                 return true;
6465             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6466                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6467                 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);
6468                 return true;
6469             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6470                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6471                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6472                 return true;
6473             case LE_AUDIO_BIG_STATE_TERMINATE:
6474                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6475                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6476                 return true;
6477             default:
6478                 break;
6479         }
6480     }
6481 
6482     // BIG Sync
6483     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6484     while (btstack_linked_list_iterator_has_next(&it)){
6485         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6486         switch (big_sync->state){
6487             case LE_AUDIO_BIG_STATE_CREATE:
6488                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
6489                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6490                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6491                 hci_send_cmd(&hci_le_big_create_sync,
6492                              big_sync->params->big_handle,
6493                              big_sync->params->sync_handle,
6494                              big_sync->params->encryption,
6495                              big_sync->params->broadcast_code,
6496                              big_sync->params->mse,
6497                              big_sync->params->big_sync_timeout_10ms,
6498                              big_sync->params->num_bis,
6499                              big_sync->params->bis_indices);
6500                 return true;
6501             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6502                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6503                 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);
6504                 return true;
6505             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6506                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6507                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6508                 return true;
6509             case LE_AUDIO_BIG_STATE_TERMINATE:
6510                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6511                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6512                 return true;
6513             default:
6514                 break;
6515         }
6516     }
6517 
6518     // CIG
6519     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
6520     while (btstack_linked_list_iterator_has_next(&it)) {
6521         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
6522         uint8_t i;
6523         // Set CIG Parameters
6524         uint8_t cis_id[MAX_NR_CIS];
6525         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
6526         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
6527         uint8_t phy_c_to_p[MAX_NR_CIS];
6528         uint8_t phy_p_to_c[MAX_NR_CIS];
6529         uint8_t rtn_c_to_p[MAX_NR_CIS];
6530         uint8_t rtn_p_to_c[MAX_NR_CIS];
6531         switch (cig->state) {
6532             case LE_AUDIO_CIG_STATE_CREATE:
6533                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6534                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6535                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
6536                 le_audio_cig_params_t * params = cig->params;
6537                 for (i = 0; i < params->num_cis; i++) {
6538                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
6539                     cis_id[i]         = cis_params->cis_id;
6540                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
6541                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
6542                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
6543                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
6544                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
6545                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
6546                 }
6547                 hci_send_cmd(&hci_le_set_cig_parameters,
6548                              cig->cig_id,
6549                              params->sdu_interval_c_to_p,
6550                              params->sdu_interval_p_to_c,
6551                              params->worst_case_sca,
6552                              params->packing,
6553                              params->framing,
6554                              params->max_transport_latency_c_to_p,
6555                              params->max_transport_latency_p_to_c,
6556                              params->num_cis,
6557                              cis_id,
6558                              max_sdu_c_to_p,
6559                              max_sdu_p_to_c,
6560                              phy_c_to_p,
6561                              phy_p_to_c,
6562                              rtn_c_to_p,
6563                              rtn_p_to_c
6564                 );
6565                 return true;
6566             case LE_AUDIO_CIG_STATE_CREATE_CIS:
6567                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6568                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6569                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
6570                 for (i=0;i<cig->num_cis;i++){
6571                     cig->cis_setup_active[i] = true;
6572                 }
6573                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
6574                 return true;
6575             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
6576                 while (cig->state_vars.next_cis < (cig->num_cis * 2)){
6577                     // find next path to setup
6578                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
6579                     if (cig->cis_established[cis_index] == false) {
6580                         continue;
6581                     }
6582                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
6583                     bool setup = true;
6584                     if (cis_direction == 0){
6585                         // 0 - input - host to controller
6586                         // we are central => central to peripheral
6587                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
6588                     } else {
6589                         // 1 - output - controller to host
6590                         // we are central => peripheral to central
6591                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
6592                     }
6593                     if (setup){
6594                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6595                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6596                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
6597                         hci_send_cmd(&hci_le_setup_iso_data_path, cig->cis_con_handles[cis_index], cis_direction, 0, 0, 0, 0, 0, 0, NULL);
6598                         return true;
6599                     }
6600                     cig->state_vars.next_cis++;
6601                 }
6602                 // emit done
6603                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
6604             default:
6605                 break;
6606         }
6607     }
6608 
6609     // CIS Accept/Reject
6610     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
6611     while (btstack_linked_list_iterator_has_next(&it)) {
6612         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
6613         hci_con_handle_t con_handle;
6614         switch (iso_stream->state){
6615             case HCI_ISO_STREAM_W2_ACCEPT:
6616                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
6617                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6618                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6619                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->con_handle);
6620                 return true;
6621             case HCI_ISO_STREAM_W2_REJECT:
6622                 con_handle = iso_stream->con_handle;
6623                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6624                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6625                 hci_iso_stream_finalize(iso_stream);
6626                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
6627                 return true;
6628             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
6629                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6630                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6631                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
6632                 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->con_handle, 0, 0, 0, 0, 0, 0, 0, NULL);
6633                 break;
6634             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
6635                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6636                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6637                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT;
6638                 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->con_handle, 1, 0, 0, 0, 0, 0, 0, NULL);
6639                 break;
6640             default:
6641                 break;
6642         }
6643     }
6644 
6645     return false;
6646 }
6647 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6648 #endif
6649 
6650 static bool hci_run_general_pending_commands(void){
6651     btstack_linked_item_t * it;
6652     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6653         hci_connection_t * connection = (hci_connection_t *) it;
6654 
6655         switch(connection->state){
6656             case SEND_CREATE_CONNECTION:
6657                 switch(connection->address_type){
6658 #ifdef ENABLE_CLASSIC
6659                     case BD_ADDR_TYPE_ACL:
6660                         log_info("sending hci_create_connection");
6661                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
6662                         break;
6663 #endif
6664                     default:
6665 #ifdef ENABLE_BLE
6666 #ifdef ENABLE_LE_CENTRAL
6667                         log_info("sending hci_le_create_connection");
6668                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6669                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6670                         hci_send_le_create_connection(0, connection->address_type, connection->address);
6671                         connection->state = SENT_CREATE_CONNECTION;
6672 #endif
6673 #endif
6674                         break;
6675                 }
6676                 return true;
6677 
6678 #ifdef ENABLE_CLASSIC
6679             case RECEIVED_CONNECTION_REQUEST:
6680                 connection->role  = HCI_ROLE_SLAVE;
6681                 if (connection->address_type == BD_ADDR_TYPE_ACL){
6682                     log_info("sending hci_accept_connection_request");
6683                     connection->state = ACCEPTED_CONNECTION_REQUEST;
6684                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
6685                     return true;
6686                 }
6687                 break;
6688 #endif
6689             case SEND_DISCONNECT:
6690                 connection->state = SENT_DISCONNECT;
6691                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6692                 return true;
6693 
6694             default:
6695                 break;
6696         }
6697 
6698         // no further commands if connection is about to get shut down
6699         if (connection->state == SENT_DISCONNECT) continue;
6700 
6701 #ifdef ENABLE_CLASSIC
6702 
6703         // Handling link key request requires remote supported features
6704         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
6705             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
6706             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
6707 
6708             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
6709             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
6710             if (have_link_key && security_level_sufficient){
6711                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
6712             } else {
6713                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
6714             }
6715             return true;
6716         }
6717 
6718         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
6719             log_info("denying to pin request");
6720             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
6721             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
6722             return true;
6723         }
6724 
6725         // security assessment requires remote features
6726         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
6727             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
6728             hci_ssp_assess_security_on_io_cap_request(connection);
6729             // 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
6730         }
6731 
6732         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
6733             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6734             // set authentication requirements:
6735             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
6736             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
6737             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
6738             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
6739                 authreq |= 1;
6740             }
6741             bool bonding = hci_stack->bondable;
6742             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
6743                 // if we have received IO Cap Response, we're in responder role
6744                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6745                 if (bonding && !remote_bonding){
6746                     log_info("Remote not bonding, dropping local flag");
6747                     bonding = false;
6748                 }
6749             }
6750             if (bonding){
6751                 if (connection->bonding_flags & BONDING_DEDICATED){
6752                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6753                 } else {
6754                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
6755                 }
6756             }
6757             uint8_t have_oob_data = 0;
6758 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6759             if (connection->classic_oob_c_192 != NULL){
6760                     have_oob_data |= 1;
6761             }
6762             if (connection->classic_oob_c_256 != NULL){
6763                 have_oob_data |= 2;
6764             }
6765 #endif
6766             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
6767             return true;
6768         }
6769 
6770         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
6771             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6772             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
6773             return true;
6774         }
6775 
6776 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6777         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
6778             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
6779             const uint8_t zero[16] = { 0 };
6780             const uint8_t * r_192 = zero;
6781             const uint8_t * c_192 = zero;
6782             const uint8_t * r_256 = zero;
6783             const uint8_t * c_256 = zero;
6784             // verify P-256 OOB
6785             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
6786                 c_256 = connection->classic_oob_c_256;
6787                 if (connection->classic_oob_r_256 != NULL) {
6788                     r_256 = connection->classic_oob_r_256;
6789                 }
6790             }
6791             // verify P-192 OOB
6792             if ((connection->classic_oob_c_192 != NULL)) {
6793                 c_192 = connection->classic_oob_c_192;
6794                 if (connection->classic_oob_r_192 != NULL) {
6795                     r_192 = connection->classic_oob_r_192;
6796                 }
6797             }
6798 
6799             // assess security
6800             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
6801             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
6802             if (need_level_4 && !can_reach_level_4){
6803                 log_info("Level 4 required, but not possible -> abort");
6804                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
6805                 // send oob negative reply
6806                 c_256 = NULL;
6807                 c_192 = NULL;
6808             }
6809 
6810             // Reply
6811             if (c_256 != zero) {
6812                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
6813             } else if (c_192 != zero){
6814                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
6815             } else {
6816                 hci_stack->classic_oob_con_handle = connection->con_handle;
6817                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
6818             }
6819             return true;
6820         }
6821 #endif
6822 
6823         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
6824             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
6825             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
6826             return true;
6827         }
6828 
6829         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
6830             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
6831             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
6832             return true;
6833         }
6834 
6835         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
6836             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
6837             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
6838             return true;
6839         }
6840 
6841         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
6842             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
6843             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
6844             connection->state = SENT_DISCONNECT;
6845             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6846             return true;
6847         }
6848 
6849         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
6850             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
6851             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
6852             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
6853             return true;
6854         }
6855 
6856         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
6857             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
6858             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
6859             return true;
6860         }
6861 
6862         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
6863             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
6864             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
6865             return true;
6866         }
6867 
6868         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
6869             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6870             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
6871             return true;
6872         }
6873 
6874         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
6875             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
6876             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
6877             return true;
6878         }
6879 
6880         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
6881             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
6882             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
6883             return true;
6884         }
6885 #endif
6886 
6887         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
6888             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
6889 #ifdef ENABLE_CLASSIC
6890             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
6891 #endif
6892             if (connection->state != SENT_DISCONNECT){
6893                 connection->state = SENT_DISCONNECT;
6894                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
6895                 return true;
6896             }
6897         }
6898 
6899 #ifdef ENABLE_CLASSIC
6900         uint16_t sniff_min_interval;
6901         switch (connection->sniff_min_interval){
6902             case 0:
6903                 break;
6904             case 0xffff:
6905                 connection->sniff_min_interval = 0;
6906                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
6907                 return true;
6908             default:
6909                 sniff_min_interval = connection->sniff_min_interval;
6910                 connection->sniff_min_interval = 0;
6911                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
6912                 return true;
6913         }
6914 
6915         if (connection->sniff_subrating_max_latency != 0xffff){
6916             uint16_t max_latency = connection->sniff_subrating_max_latency;
6917             connection->sniff_subrating_max_latency = 0;
6918             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
6919             return true;
6920         }
6921 
6922         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
6923             uint8_t service_type = (uint8_t) connection->qos_service_type;
6924             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
6925             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);
6926             return true;
6927         }
6928 
6929         if (connection->request_role != HCI_ROLE_INVALID){
6930             hci_role_t role = connection->request_role;
6931             connection->request_role = HCI_ROLE_INVALID;
6932             hci_send_cmd(&hci_switch_role_command, connection->address, role);
6933             return true;
6934         }
6935 #endif
6936 
6937         if (connection->gap_connection_tasks != 0){
6938 #ifdef ENABLE_CLASSIC
6939             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
6940                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
6941                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
6942                 return true;
6943             }
6944             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
6945                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
6946                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
6947                 return true;
6948             }
6949 #endif
6950             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
6951                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
6952                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
6953                 return true;
6954             }
6955 #ifdef ENABLE_BLE
6956             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
6957                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
6958                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
6959                 return true;
6960             }
6961 #endif
6962         }
6963 
6964 #ifdef ENABLE_BLE
6965         switch (connection->le_con_parameter_update_state){
6966             // response to L2CAP CON PARAMETER UPDATE REQUEST
6967             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
6968                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6969                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
6970                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6971                              0x0000, 0xffff);
6972                 return true;
6973             case CON_PARAMETER_UPDATE_REPLY:
6974                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6975                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
6976                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6977                              0x0000, 0xffff);
6978                 return true;
6979             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
6980                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6981                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
6982                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
6983                 return true;
6984             default:
6985                 break;
6986         }
6987         if (connection->le_phy_update_all_phys != 0xffu){
6988             uint8_t all_phys = connection->le_phy_update_all_phys;
6989             connection->le_phy_update_all_phys = 0xff;
6990             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);
6991             return true;
6992         }
6993 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6994         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
6995             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
6996             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
6997             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
6998             return true;
6999         }
7000 #endif
7001 #endif
7002     }
7003     return false;
7004 }
7005 
7006 static void hci_run(void){
7007 
7008     // stack state sub statemachines
7009     switch (hci_stack->state) {
7010         case HCI_STATE_INITIALIZING:
7011             hci_initializing_run();
7012             break;
7013         case HCI_STATE_HALTING:
7014             hci_halting_run();
7015             break;
7016         case HCI_STATE_FALLING_ASLEEP:
7017             hci_falling_asleep_run();
7018             break;
7019         default:
7020             break;
7021     }
7022 
7023     // allow to run after initialization to working transition
7024     if (hci_stack->state != HCI_STATE_WORKING){
7025         return;
7026     }
7027 
7028     bool done;
7029 
7030     // send continuation fragments first, as they block the prepared packet buffer
7031     done = hci_run_acl_fragments();
7032     if (done) return;
7033 
7034 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7035     done = hci_run_iso_fragments();
7036     if (done) return;
7037 #endif
7038 
7039 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7040     // send host num completed packets next as they don't require num_cmd_packets > 0
7041     if (!hci_can_send_comand_packet_transport()) return;
7042     if (hci_stack->host_completed_packets){
7043         hci_host_num_completed_packets();
7044         return;
7045     }
7046 #endif
7047 
7048     if (!hci_can_send_command_packet_now()) return;
7049 
7050     // global/non-connection oriented commands
7051 
7052 
7053 #ifdef ENABLE_CLASSIC
7054     // general gap classic
7055     done = hci_run_general_gap_classic();
7056     if (done) return;
7057 #endif
7058 
7059 #ifdef ENABLE_BLE
7060     // general gap le
7061     done = hci_run_general_gap_le();
7062     if (done) return;
7063 
7064 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7065     // ISO related tasks, e.g. BIG create/terminate/sync
7066     done = hci_run_iso_tasks();
7067     if (done) return;
7068 #endif
7069 #endif
7070 
7071     // send pending HCI commands
7072     hci_run_general_pending_commands();
7073 }
7074 
7075 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
7076     // house-keeping
7077 
7078 #ifdef ENABLE_CLASSIC
7079     bd_addr_t addr;
7080     hci_connection_t * conn;
7081 #endif
7082 #ifdef ENABLE_LE_CENTRAL
7083     uint8_t initiator_filter_policy;
7084 #endif
7085 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7086     uint8_t i;
7087     uint8_t num_cis;
7088     hci_con_handle_t cis_handle;
7089     uint8_t status;
7090 #endif
7091 
7092     uint16_t opcode = little_endian_read_16(packet, 0);
7093     switch (opcode) {
7094         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
7095             hci_stack->loopback_mode = packet[3];
7096             break;
7097 
7098 #ifdef ENABLE_CLASSIC
7099         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7100             reverse_bd_addr(&packet[3], addr);
7101             log_info("Create_connection to %s", bd_addr_to_str(addr));
7102 
7103             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
7104             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
7105                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
7106                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
7107             }
7108 
7109             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7110             if (!conn) {
7111                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7112                 if (!conn) {
7113                     // notify client that alloc failed
7114                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7115                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
7116                 }
7117                 conn->state = SEND_CREATE_CONNECTION;
7118                 conn->role  = HCI_ROLE_MASTER;
7119             }
7120 
7121             log_info("conn state %u", conn->state);
7122             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7123             switch (conn->state) {
7124                 // if connection active exists
7125                 case OPEN:
7126                     // and OPEN, emit connection complete command
7127                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
7128                     // packet not sent to controller
7129                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7130                 case RECEIVED_DISCONNECTION_COMPLETE:
7131                     // create connection triggered in disconnect complete event, let's do it now
7132                     break;
7133                 case SEND_CREATE_CONNECTION:
7134 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
7135                     if (hci_classic_operation_active()){
7136                         return ERROR_CODE_SUCCESS;
7137                     }
7138 #endif
7139                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7140                     break;
7141                 default:
7142                     // otherwise, just ignore as it is already in the open process
7143                     // packet not sent to controller
7144                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7145             }
7146             conn->state = SENT_CREATE_CONNECTION;
7147 
7148             // track outgoing connection
7149             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
7150             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7151             break;
7152 
7153 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
7154         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
7155             // setup_synchronous_connection? Voice setting at offset 22
7156             // TODO: compare to current setting if sco connection already active
7157             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7158             break;
7159         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
7160             // accept_synchronous_connection? Voice setting at offset 18
7161             // TODO: compare to current setting if sco connection already active
7162             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7163             // track outgoing connection
7164             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7165             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
7166             break;
7167 #endif
7168 #endif
7169 
7170 #ifdef ENABLE_BLE
7171 #ifdef ENABLE_LE_CENTRAL
7172         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7173             // white list used?
7174             initiator_filter_policy = packet[7];
7175             switch (initiator_filter_policy) {
7176                 case 0:
7177                     // whitelist not used
7178                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7179                     break;
7180                 case 1:
7181                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7182                     break;
7183                 default:
7184                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7185                     break;
7186             }
7187             // track outgoing connection
7188             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer address type
7189             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
7190             break;
7191 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7192         case HCI_OPCODE_HCI_LE_EXTENDED_CREATE_CONNECTION:
7193             // white list used?
7194             initiator_filter_policy = packet[3];
7195             switch (initiator_filter_policy) {
7196                 case 0:
7197                     // whitelist not used
7198                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7199                     break;
7200                 case 1:
7201                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7202                     break;
7203                 default:
7204                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7205                     break;
7206             }
7207             // track outgoing connection
7208             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[5]; // peer address type
7209             reverse_bd_addr( &packet[6], hci_stack->outgoing_addr); // peer address
7210             break;
7211 #endif
7212         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
7213             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
7214             break;
7215 #endif
7216 #endif /* ENABLE_BLE */
7217         default:
7218             break;
7219     }
7220 
7221     hci_stack->num_cmd_packets--;
7222 
7223     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
7224     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7225     if (err != 0){
7226         return ERROR_CODE_HARDWARE_FAILURE;
7227     }
7228     return ERROR_CODE_SUCCESS;
7229 }
7230 
7231 // disconnect because of security block
7232 void hci_disconnect_security_block(hci_con_handle_t con_handle){
7233     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7234     if (!connection) return;
7235     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
7236 }
7237 
7238 
7239 // Configure Secure Simple Pairing
7240 
7241 #ifdef ENABLE_CLASSIC
7242 
7243 // enable will enable SSP during init
7244 void gap_ssp_set_enable(int enable){
7245     hci_stack->ssp_enable = enable;
7246 }
7247 
7248 static int hci_local_ssp_activated(void){
7249     return gap_ssp_supported() && hci_stack->ssp_enable;
7250 }
7251 
7252 // if set, BTstack will respond to io capability request using authentication requirement
7253 void gap_ssp_set_io_capability(int io_capability){
7254     hci_stack->ssp_io_capability = io_capability;
7255 }
7256 void gap_ssp_set_authentication_requirement(int authentication_requirement){
7257     hci_stack->ssp_authentication_requirement = authentication_requirement;
7258 }
7259 
7260 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
7261 void gap_ssp_set_auto_accept(int auto_accept){
7262     hci_stack->ssp_auto_accept = auto_accept;
7263 }
7264 
7265 void gap_secure_connections_enable(bool enable){
7266     hci_stack->secure_connections_enable = enable;
7267 }
7268 bool gap_secure_connections_active(void){
7269     return hci_stack->secure_connections_active;
7270 }
7271 
7272 #endif
7273 
7274 // va_list part of hci_send_cmd
7275 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
7276     if (!hci_can_send_command_packet_now()){
7277         log_error("hci_send_cmd called but cannot send packet now");
7278         return ERROR_CODE_COMMAND_DISALLOWED;
7279     }
7280 
7281     // for HCI INITIALIZATION
7282     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
7283     hci_stack->last_cmd_opcode = cmd->opcode;
7284 
7285     hci_reserve_packet_buffer();
7286     uint8_t * packet = hci_stack->hci_packet_buffer;
7287     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
7288     uint8_t status = hci_send_cmd_packet(packet, size);
7289 
7290     // release packet buffer on error or for synchronous transport implementations
7291     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7292         hci_release_packet_buffer();
7293         hci_emit_transport_packet_sent();
7294     }
7295 
7296     return status;
7297 }
7298 
7299 /**
7300  * pre: numcmds >= 0 - it's allowed to send a command to the controller
7301  */
7302 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
7303     va_list argptr;
7304     va_start(argptr, cmd);
7305     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
7306     va_end(argptr);
7307     return status;
7308 }
7309 
7310 // Create various non-HCI events.
7311 // TODO: generalize, use table similar to hci_create_command
7312 
7313 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
7314     // dump packet
7315     if (dump) {
7316         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
7317     }
7318 
7319     // dispatch to all event handlers
7320     btstack_linked_list_iterator_t it;
7321     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
7322     while (btstack_linked_list_iterator_has_next(&it)){
7323         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
7324         entry->callback(HCI_EVENT_PACKET, 0, event, size);
7325     }
7326 }
7327 
7328 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
7329     if (!hci_stack->acl_packet_handler) return;
7330     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
7331 }
7332 
7333 #ifdef ENABLE_CLASSIC
7334 static void hci_notify_if_sco_can_send_now(void){
7335     // notify SCO sender if waiting
7336     if (!hci_stack->sco_waiting_for_can_send_now) return;
7337     if (hci_can_send_sco_packet_now()){
7338         hci_stack->sco_waiting_for_can_send_now = 0;
7339         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
7340         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
7341         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
7342     }
7343 }
7344 
7345 // parsing end emitting has been merged to reduce code size
7346 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
7347     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
7348 
7349     uint8_t * eir_data;
7350     ad_context_t context;
7351     const uint8_t * name;
7352     uint8_t         name_len;
7353 
7354     if (size < 3) return;
7355 
7356     int event_type = hci_event_packet_get_type(packet);
7357     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
7358     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
7359 
7360     switch (event_type){
7361         case HCI_EVENT_INQUIRY_RESULT:
7362         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7363             if (size != (3 + (num_responses * 14))) return;
7364             break;
7365         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7366             if (size != 257) return;
7367             if (num_responses != 1) return;
7368             break;
7369         default:
7370             return;
7371     }
7372 
7373     // event[1] is set at the end
7374     int i;
7375     for (i=0; i<num_responses;i++){
7376         memset(event, 0, sizeof(event));
7377         event[0] = GAP_EVENT_INQUIRY_RESULT;
7378         uint8_t event_size = 27;    // if name is not set by EIR
7379 
7380         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
7381         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
7382         (void)memcpy(&event[9],
7383                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
7384                      3); // class of device
7385         (void)memcpy(&event[12],
7386                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
7387                      2); // clock offset
7388 
7389         switch (event_type){
7390             case HCI_EVENT_INQUIRY_RESULT:
7391                 // 14,15,16,17 = 0, size 18
7392                 break;
7393             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7394                 event[14] = 1;
7395                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7396                 // 16,17 = 0, size 18
7397                 break;
7398             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7399                 event[14] = 1;
7400                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7401                 // EIR packets only contain a single inquiry response
7402                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
7403                 name = NULL;
7404                 // Iterate over EIR data
7405                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
7406                     uint8_t data_type    = ad_iterator_get_data_type(&context);
7407                     uint8_t data_size    = ad_iterator_get_data_len(&context);
7408                     const uint8_t * data = ad_iterator_get_data(&context);
7409                     // Prefer Complete Local Name over Shortened Local Name
7410                     switch (data_type){
7411                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
7412                             if (name) continue;
7413                             /* fall through */
7414                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
7415                             name = data;
7416                             name_len = data_size;
7417                             break;
7418                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
7419                             if (data_size != 8) break;
7420                             event[16] = 1;
7421                             memcpy(&event[17], data, 8);
7422                             break;
7423                         default:
7424                             break;
7425                     }
7426                 }
7427                 if (name){
7428                     event[25] = 1;
7429                     // truncate name if needed
7430                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
7431                     event[26] = len;
7432                     (void)memcpy(&event[27], name, len);
7433                     event_size += len;
7434                 }
7435                 break;
7436             default:
7437                 return;
7438         }
7439         event[1] = event_size - 2;
7440         hci_emit_event(event, event_size, 1);
7441     }
7442 }
7443 #endif
7444 
7445 void hci_emit_state(void){
7446     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
7447     uint8_t event[3];
7448     event[0] = BTSTACK_EVENT_STATE;
7449     event[1] = sizeof(event) - 2u;
7450     event[2] = hci_stack->state;
7451     hci_emit_event(event, sizeof(event), 1);
7452 }
7453 
7454 #ifdef ENABLE_CLASSIC
7455 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
7456     uint8_t event[13];
7457     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
7458     event[1] = sizeof(event) - 2;
7459     event[2] = status;
7460     little_endian_store_16(event, 3, con_handle);
7461     reverse_bd_addr(address, &event[5]);
7462     event[11] = 1; // ACL connection
7463     event[12] = 0; // encryption disabled
7464     hci_emit_event(event, sizeof(event), 1);
7465 }
7466 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
7467     if (disable_l2cap_timeouts) return;
7468     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
7469     uint8_t event[4];
7470     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
7471     event[1] = sizeof(event) - 2;
7472     little_endian_store_16(event, 2, conn->con_handle);
7473     hci_emit_event(event, sizeof(event), 1);
7474 }
7475 #endif
7476 
7477 #ifdef ENABLE_BLE
7478 #ifdef ENABLE_LE_CENTRAL
7479 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){
7480     uint8_t event[21];
7481     event[0] = HCI_EVENT_LE_META;
7482     event[1] = sizeof(event) - 2u;
7483     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
7484     event[3] = status;
7485     little_endian_store_16(event, 4, con_handle);
7486     event[6] = 0; // TODO: role
7487     event[7] = address_type;
7488     reverse_bd_addr(address, &event[8]);
7489     little_endian_store_16(event, 14, 0); // interval
7490     little_endian_store_16(event, 16, 0); // latency
7491     little_endian_store_16(event, 18, 0); // supervision timeout
7492     event[20] = 0; // master clock accuracy
7493     hci_emit_event(event, sizeof(event), 1);
7494 }
7495 #endif
7496 #endif
7497 
7498 static void hci_emit_transport_packet_sent(void){
7499     // notify upper stack that it might be possible to send again
7500     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
7501     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
7502 }
7503 
7504 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
7505     uint8_t event[6];
7506     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
7507     event[1] = sizeof(event) - 2u;
7508     event[2] = 0; // status = OK
7509     little_endian_store_16(event, 3, con_handle);
7510     event[5] = reason;
7511     hci_emit_event(event, sizeof(event), 1);
7512 }
7513 
7514 static void hci_emit_nr_connections_changed(void){
7515     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
7516     uint8_t event[3];
7517     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
7518     event[1] = sizeof(event) - 2u;
7519     event[2] = nr_hci_connections();
7520     hci_emit_event(event, sizeof(event), 1);
7521 }
7522 
7523 static void hci_emit_hci_open_failed(void){
7524     log_info("BTSTACK_EVENT_POWERON_FAILED");
7525     uint8_t event[2];
7526     event[0] = BTSTACK_EVENT_POWERON_FAILED;
7527     event[1] = sizeof(event) - 2u;
7528     hci_emit_event(event, sizeof(event), 1);
7529 }
7530 
7531 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
7532     log_info("hci_emit_dedicated_bonding_result %u ", status);
7533     uint8_t event[9];
7534     int pos = 0;
7535     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
7536     event[pos++] = sizeof(event) - 2u;
7537     event[pos++] = status;
7538     reverse_bd_addr(address, &event[pos]);
7539     hci_emit_event(event, sizeof(event), 1);
7540 }
7541 
7542 
7543 #ifdef ENABLE_CLASSIC
7544 
7545 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
7546     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
7547     uint8_t event[5];
7548     int pos = 0;
7549     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
7550     event[pos++] = sizeof(event) - 2;
7551     little_endian_store_16(event, 2, con_handle);
7552     pos += 2;
7553     event[pos++] = level;
7554     hci_emit_event(event, sizeof(event), 1);
7555 }
7556 
7557 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
7558     if (!connection) return LEVEL_0;
7559     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
7560     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
7561     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
7562     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
7563     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
7564     // LEVEL 4 always requires 128 bit encrytion key size
7565     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
7566         security_level = LEVEL_3;
7567     }
7568     return security_level;
7569 }
7570 
7571 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
7572     uint8_t event[4];
7573     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
7574     event[1] = sizeof(event) - 2;
7575     event[2] = discoverable;
7576     event[3] = connectable;
7577     hci_emit_event(event, sizeof(event), 1);
7578 }
7579 
7580 // query if remote side supports eSCO
7581 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
7582     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7583     if (!connection) return false;
7584     return (connection->remote_supported_features[0] & 1) != 0;
7585 }
7586 
7587 static bool hci_ssp_supported(hci_connection_t * connection){
7588     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
7589     return (connection->bonding_flags & mask) == mask;
7590 }
7591 
7592 // query if remote side supports SSP
7593 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
7594     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7595     if (!connection) return false;
7596     return hci_ssp_supported(connection) ? 1 : 0;
7597 }
7598 
7599 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
7600     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
7601 }
7602 
7603 /**
7604  * Check if remote supported features query has completed
7605  */
7606 bool hci_remote_features_available(hci_con_handle_t handle){
7607     hci_connection_t * connection = hci_connection_for_handle(handle);
7608     if (!connection) return false;
7609     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
7610 }
7611 
7612 /**
7613  * Trigger remote supported features query
7614  */
7615 
7616 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
7617     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
7618         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7619     }
7620 }
7621 
7622 void hci_remote_features_query(hci_con_handle_t con_handle){
7623     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7624     if (!connection) return;
7625     hci_trigger_remote_features_for_connection(connection);
7626     hci_run();
7627 }
7628 
7629 // GAP API
7630 /**
7631  * @bbrief enable/disable bonding. default is enabled
7632  * @praram enabled
7633  */
7634 void gap_set_bondable_mode(int enable){
7635     hci_stack->bondable = enable ? 1 : 0;
7636 }
7637 /**
7638  * @brief Get bondable mode.
7639  * @return 1 if bondable
7640  */
7641 int gap_get_bondable_mode(void){
7642     return hci_stack->bondable;
7643 }
7644 
7645 /**
7646  * @brief map link keys to security levels
7647  */
7648 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
7649     switch (link_key_type){
7650         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7651             return LEVEL_4;
7652         case COMBINATION_KEY:
7653         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7654             return LEVEL_3;
7655         default:
7656             return LEVEL_2;
7657     }
7658 }
7659 
7660 /**
7661  * @brief map link keys to secure connection yes/no
7662  */
7663 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
7664     switch (link_key_type){
7665         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7666         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7667             return true;
7668         default:
7669             return false;
7670     }
7671 }
7672 
7673 /**
7674  * @brief map link keys to authenticated
7675  */
7676 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
7677     switch (link_key_type){
7678         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7679         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7680             return true;
7681         default:
7682             return false;
7683     }
7684 }
7685 
7686 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
7687     log_info("gap_mitm_protection_required_for_security_level %u", level);
7688     return level > LEVEL_2;
7689 }
7690 
7691 /**
7692  * @brief get current security level
7693  */
7694 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
7695     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7696     if (!connection) return LEVEL_0;
7697     return gap_security_level_for_connection(connection);
7698 }
7699 
7700 /**
7701  * @brief request connection to device to
7702  * @result GAP_AUTHENTICATION_RESULT
7703  */
7704 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
7705     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7706     if (!connection){
7707         hci_emit_security_level(con_handle, LEVEL_0);
7708         return;
7709     }
7710 
7711     btstack_assert(hci_is_le_connection(connection) == false);
7712 
7713     // 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)
7714     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
7715     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
7716         requested_level = LEVEL_4;
7717     }
7718 
7719     gap_security_level_t current_level = gap_security_level(con_handle);
7720     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
7721         requested_level, connection->requested_security_level, current_level);
7722 
7723     // authentication active if authentication request was sent or planned level > 0
7724     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
7725     if (authentication_active){
7726         // authentication already active
7727         if (connection->requested_security_level < requested_level){
7728             // increase requested level as new level is higher
7729             // TODO: handle re-authentication when done
7730             connection->requested_security_level = requested_level;
7731         }
7732     } else {
7733         // no request active, notify if security sufficient
7734         if (requested_level <= current_level){
7735             hci_emit_security_level(con_handle, current_level);
7736             return;
7737         }
7738 
7739         // store request
7740         connection->requested_security_level = requested_level;
7741 
7742         // start to authenticate connection
7743         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
7744 
7745         // request remote features if not already active, also trigger hci_run
7746         hci_remote_features_query(con_handle);
7747     }
7748 }
7749 
7750 /**
7751  * @brief start dedicated bonding with device. disconnect after bonding
7752  * @param device
7753  * @param request MITM protection
7754  * @result GAP_DEDICATED_BONDING_COMPLETE
7755  */
7756 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
7757 
7758     // create connection state machine
7759     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
7760 
7761     if (!connection){
7762         return BTSTACK_MEMORY_ALLOC_FAILED;
7763     }
7764 
7765     // delete linkn key
7766     gap_drop_link_key_for_bd_addr(device);
7767 
7768     // configure LEVEL_2/3, dedicated bonding
7769     connection->state = SEND_CREATE_CONNECTION;
7770     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
7771     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
7772     connection->bonding_flags = BONDING_DEDICATED;
7773 
7774     // wait for GAP Security Result and send GAP Dedicated Bonding complete
7775 
7776     // handle: connnection failure (connection complete != ok)
7777     // handle: authentication failure
7778     // handle: disconnect on done
7779 
7780     hci_run();
7781 
7782     return 0;
7783 }
7784 
7785 void gap_set_local_name(const char * local_name){
7786     hci_stack->local_name = local_name;
7787     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
7788     // also update EIR if not set by user
7789     if (hci_stack->eir_data == NULL){
7790         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7791     }
7792     hci_run();
7793 }
7794 #endif
7795 
7796 
7797 #ifdef ENABLE_BLE
7798 
7799 #ifdef ENABLE_LE_CENTRAL
7800 void gap_start_scan(void){
7801     hci_stack->le_scanning_enabled = true;
7802     hci_run();
7803 }
7804 
7805 void gap_stop_scan(void){
7806     hci_stack->le_scanning_enabled = false;
7807     hci_run();
7808 }
7809 
7810 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
7811     hci_stack->le_scan_type          = scan_type;
7812     hci_stack->le_scan_filter_policy = scanning_filter_policy;
7813     hci_stack->le_scan_interval      = scan_interval;
7814     hci_stack->le_scan_window        = scan_window;
7815     hci_stack->le_scanning_param_update = true;
7816     hci_run();
7817 }
7818 
7819 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
7820     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
7821 }
7822 
7823 void gap_set_scan_duplicate_filter(bool enabled){
7824     hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0;
7825 }
7826 
7827 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
7828     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
7829     if (!conn){
7830         // disallow if le connection is already outgoing
7831         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7832             log_error("le connection already active");
7833             return ERROR_CODE_COMMAND_DISALLOWED;
7834         }
7835 
7836         log_info("gap_connect: no connection exists yet, creating context");
7837         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
7838         if (!conn){
7839             // notify client that alloc failed
7840             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7841             log_info("gap_connect: failed to alloc hci_connection_t");
7842             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
7843         }
7844 
7845         // set le connecting state
7846         if (hci_is_le_connection_type(addr_type)){
7847             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
7848         }
7849 
7850         conn->state = SEND_CREATE_CONNECTION;
7851         log_info("gap_connect: send create connection next");
7852         hci_run();
7853         return ERROR_CODE_SUCCESS;
7854     }
7855 
7856     if (!hci_is_le_connection(conn) ||
7857         (conn->state == SEND_CREATE_CONNECTION) ||
7858         (conn->state == SENT_CREATE_CONNECTION)) {
7859         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
7860         log_error("gap_connect: classic connection or connect is already being created");
7861         return GATT_CLIENT_IN_WRONG_STATE;
7862     }
7863 
7864     // check if connection was just disconnected
7865     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7866         log_info("gap_connect: send create connection (again)");
7867         conn->state = SEND_CREATE_CONNECTION;
7868         hci_run();
7869         return ERROR_CODE_SUCCESS;
7870     }
7871 
7872     log_info("gap_connect: context exists with state %u", conn->state);
7873     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
7874     hci_run();
7875     return ERROR_CODE_SUCCESS;
7876 }
7877 
7878 // @assumption: only a single outgoing LE Connection exists
7879 static hci_connection_t * gap_get_outgoing_connection(void){
7880     btstack_linked_item_t *it;
7881     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7882         hci_connection_t * conn = (hci_connection_t *) it;
7883         if (!hci_is_le_connection(conn)) continue;
7884         switch (conn->state){
7885             case SEND_CREATE_CONNECTION:
7886             case SENT_CREATE_CONNECTION:
7887                 return conn;
7888             default:
7889                 break;
7890         };
7891     }
7892     return NULL;
7893 }
7894 
7895 uint8_t gap_connect_cancel(void){
7896     hci_connection_t * conn;
7897     switch (hci_stack->le_connecting_request){
7898         case LE_CONNECTING_IDLE:
7899             break;
7900         case LE_CONNECTING_WHITELIST:
7901             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7902             hci_run();
7903             break;
7904         case LE_CONNECTING_DIRECT:
7905             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7906             conn = gap_get_outgoing_connection();
7907             if (conn == NULL){
7908                 hci_run();
7909             } else {
7910                 switch (conn->state){
7911                     case SEND_CREATE_CONNECTION:
7912                         // skip sending create connection and emit event instead
7913                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
7914                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
7915                         btstack_memory_hci_connection_free( conn );
7916                         break;
7917                     case SENT_CREATE_CONNECTION:
7918                         // let hci_run_general_gap_le cancel outgoing connection
7919                         hci_run();
7920                         break;
7921                     default:
7922                         break;
7923                 }
7924             }
7925             break;
7926         default:
7927             btstack_unreachable();
7928             break;
7929     }
7930     return ERROR_CODE_SUCCESS;
7931 }
7932 
7933 /**
7934  * @brief Set connection parameters for outgoing connections
7935  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
7936  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
7937  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
7938  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
7939  * @param conn_latency, default: 4
7940  * @param supervision_timeout (unit: 10ms), default: 720 ms
7941  * @param min_ce_length (unit: 0.625ms), default: 10 ms
7942  * @param max_ce_length (unit: 0.625ms), default: 30 ms
7943  */
7944 
7945 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
7946     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
7947     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
7948     hci_stack->le_connection_scan_interval = conn_scan_interval;
7949     hci_stack->le_connection_scan_window = conn_scan_window;
7950     hci_stack->le_connection_interval_min = conn_interval_min;
7951     hci_stack->le_connection_interval_max = conn_interval_max;
7952     hci_stack->le_connection_latency = conn_latency;
7953     hci_stack->le_supervision_timeout = supervision_timeout;
7954     hci_stack->le_minimum_ce_length = min_ce_length;
7955     hci_stack->le_maximum_ce_length = max_ce_length;
7956 }
7957 #endif
7958 
7959 /**
7960  * @brief Updates the connection parameters for a given LE connection
7961  * @param handle
7962  * @param conn_interval_min (unit: 1.25ms)
7963  * @param conn_interval_max (unit: 1.25ms)
7964  * @param conn_latency
7965  * @param supervision_timeout (unit: 10ms)
7966  * @return 0 if ok
7967  */
7968 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7969     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7970     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7971     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7972     connection->le_conn_interval_min = conn_interval_min;
7973     connection->le_conn_interval_max = conn_interval_max;
7974     connection->le_conn_latency = conn_latency;
7975     connection->le_supervision_timeout = supervision_timeout;
7976     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
7977     hci_run();
7978     return 0;
7979 }
7980 
7981 /**
7982  * @brief Request an update of the connection parameter for a given LE connection
7983  * @param handle
7984  * @param conn_interval_min (unit: 1.25ms)
7985  * @param conn_interval_max (unit: 1.25ms)
7986  * @param conn_latency
7987  * @param supervision_timeout (unit: 10ms)
7988  * @return 0 if ok
7989  */
7990 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7991     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7992     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7993     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7994     connection->le_conn_interval_min = conn_interval_min;
7995     connection->le_conn_interval_max = conn_interval_max;
7996     connection->le_conn_latency = conn_latency;
7997     connection->le_supervision_timeout = supervision_timeout;
7998     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
7999     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
8000     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
8001     return 0;
8002 }
8003 
8004 #ifdef ENABLE_LE_PERIPHERAL
8005 
8006 /**
8007  * @brief Set Advertisement Data
8008  * @param advertising_data_length
8009  * @param advertising_data (max 31 octets)
8010  * @note data is not copied, pointer has to stay valid
8011  */
8012 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
8013     hci_stack->le_advertisements_data_len = advertising_data_length;
8014     hci_stack->le_advertisements_data = advertising_data;
8015     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8016     hci_run();
8017 }
8018 
8019 /**
8020  * @brief Set Scan Response Data
8021  * @param advertising_data_length
8022  * @param advertising_data (max 31 octets)
8023  * @note data is not copied, pointer has to stay valid
8024  */
8025 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
8026     hci_stack->le_scan_response_data_len = scan_response_data_length;
8027     hci_stack->le_scan_response_data = scan_response_data;
8028     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8029     hci_run();
8030 }
8031 
8032 /**
8033  * @brief Set Advertisement Parameters
8034  * @param adv_int_min
8035  * @param adv_int_max
8036  * @param adv_type
8037  * @param direct_address_type
8038  * @param direct_address
8039  * @param channel_map
8040  * @param filter_policy
8041  *
8042  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
8043  */
8044  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
8045     uint8_t direct_address_typ, bd_addr_t direct_address,
8046     uint8_t channel_map, uint8_t filter_policy) {
8047 
8048     hci_stack->le_advertisements_interval_min = adv_int_min;
8049     hci_stack->le_advertisements_interval_max = adv_int_max;
8050     hci_stack->le_advertisements_type = adv_type;
8051     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
8052     hci_stack->le_advertisements_channel_map = channel_map;
8053     hci_stack->le_advertisements_filter_policy = filter_policy;
8054     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
8055                  6);
8056 
8057     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8058     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
8059     hci_run();
8060  }
8061 
8062 /**
8063  * @brief Enable/Disable Advertisements
8064  * @param enabled
8065  */
8066 void gap_advertisements_enable(int enabled){
8067     if (enabled == 0){
8068         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8069     } else {
8070         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
8071     }
8072     hci_update_advertisements_enabled_for_current_roles();
8073     hci_run();
8074 }
8075 
8076 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8077 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
8078     btstack_linked_list_iterator_t it;
8079     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
8080     while (btstack_linked_list_iterator_has_next(&it)){
8081         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
8082         if ( item->advertising_handle == advertising_handle ) {
8083             return item;
8084         }
8085     }
8086     return NULL;
8087 }
8088 
8089 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
8090     // find free advertisement handle
8091     uint8_t advertisement_handle;
8092     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
8093         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
8094     }
8095     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8096     // clear
8097     memset(storage, 0, sizeof(le_advertising_set_t));
8098     // copy params
8099     storage->advertising_handle = advertisement_handle;
8100     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8101     // add to list
8102     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
8103     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
8104     *out_advertising_handle = advertisement_handle;
8105     // set tasks and start
8106     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8107     hci_run();
8108     return ERROR_CODE_SUCCESS;
8109 }
8110 
8111 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
8112     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8113     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8114     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8115     // set tasks and start
8116     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8117     hci_run();
8118     return ERROR_CODE_SUCCESS;
8119 }
8120 
8121 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
8122     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8123     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8124     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
8125     return ERROR_CODE_SUCCESS;
8126 }
8127 
8128 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
8129     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8130     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8131     memcpy(advertising_set->random_address, random_address, 6);
8132     // set tasks and start
8133     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8134     hci_run();
8135     return ERROR_CODE_SUCCESS;
8136 }
8137 
8138 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
8139     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8140     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8141     advertising_set->adv_data = advertising_data;
8142     advertising_set->adv_data_len = advertising_data_length;
8143     // set tasks and start
8144     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8145     hci_run();
8146     return ERROR_CODE_SUCCESS;
8147 }
8148 
8149 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){
8150     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8151     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8152     advertising_set->scan_data = scan_response_data;
8153     advertising_set->scan_data_len = scan_response_data_length;
8154     // set tasks and start
8155     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8156     hci_run();
8157     return ERROR_CODE_SUCCESS;
8158 }
8159 
8160 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
8161     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8162     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8163     advertising_set->enable_timeout = timeout;
8164     advertising_set->enable_max_scan_events = num_extended_advertising_events;
8165     // set tasks and start
8166     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
8167     hci_run();
8168     return ERROR_CODE_SUCCESS;
8169 }
8170 
8171 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
8172     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8173     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8174     // set tasks and start
8175     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8176     hci_run();
8177     return ERROR_CODE_SUCCESS;
8178 }
8179 
8180 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8181     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8182     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8183     // set tasks and start
8184     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8185     hci_run();
8186     return ERROR_CODE_SUCCESS;
8187 }
8188 
8189 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8190 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8191     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8192     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8193     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8194     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8195     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8196     // set tasks and start
8197     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8198     hci_run();
8199     return ERROR_CODE_SUCCESS;
8200 }
8201 
8202 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8203     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8204     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8205     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8206     return ERROR_CODE_SUCCESS;
8207 }
8208 
8209 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8210     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8211     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8212     advertising_set->periodic_data = periodic_data;
8213     advertising_set->periodic_data_len = periodic_data_length;
8214     // set tasks and start
8215     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8216     hci_run();
8217     return ERROR_CODE_SUCCESS;
8218 }
8219 
8220 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
8221     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8222     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8223     // set tasks and start
8224     advertising_set->periodic_include_adi = include_adi;
8225     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8226     hci_run();
8227     return ERROR_CODE_SUCCESS;
8228 }
8229 
8230 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
8231     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8232     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8233     // set tasks and start
8234     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8235     hci_run();
8236     return ERROR_CODE_SUCCESS;
8237 }
8238 
8239 uint8_t gap_periodic_advertising_sync_transfer_set_default_parameters(uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type){
8240     hci_stack->le_past_mode = mode;
8241     hci_stack->le_past_skip = skip;
8242     hci_stack->le_past_sync_timeout = sync_timeout;
8243     hci_stack->le_past_cte_type = cte_type;
8244     hci_stack->le_past_set_default_params = true;
8245     hci_run();
8246     return ERROR_CODE_SUCCESS;
8247 }
8248 
8249 uint8_t gap_periodic_advertising_sync_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, hci_con_handle_t sync_handle){
8250     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8251     if (hci_connection == NULL){
8252         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8253     }
8254     hci_connection->le_past_sync_handle = sync_handle;
8255     hci_connection->le_past_service_data = service_data;
8256     hci_run();
8257     return ERROR_CODE_SUCCESS;
8258 }
8259 
8260 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
8261 
8262 #endif
8263 
8264 #endif
8265 
8266 void hci_le_set_own_address_type(uint8_t own_address_type){
8267     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
8268     if (own_address_type == hci_stack->le_own_addr_type) return;
8269     hci_stack->le_own_addr_type = own_address_type;
8270 
8271 #ifdef ENABLE_LE_PERIPHERAL
8272     // update advertisement parameters, too
8273     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8274     hci_run();
8275 #endif
8276 #ifdef ENABLE_LE_CENTRAL
8277     // note: we don't update scan parameters or modify ongoing connection attempts
8278 #endif
8279 }
8280 
8281 void hci_le_random_address_set(const bd_addr_t random_address){
8282     memcpy(hci_stack->le_random_address, random_address, 6);
8283     hci_stack->le_random_address_set = true;
8284     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8285     hci_run();
8286 }
8287 
8288 #endif
8289 
8290 uint8_t gap_disconnect(hci_con_handle_t handle){
8291     hci_connection_t * conn = hci_connection_for_handle(handle);
8292     if (!conn){
8293         hci_emit_disconnection_complete(handle, 0);
8294         return 0;
8295     }
8296     // ignore if already disconnected
8297     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
8298         return 0;
8299     }
8300     conn->state = SEND_DISCONNECT;
8301     hci_run();
8302     return 0;
8303 }
8304 
8305 int gap_read_rssi(hci_con_handle_t con_handle){
8306     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8307     if (hci_connection == NULL) return 0;
8308     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
8309     hci_run();
8310     return 1;
8311 }
8312 
8313 /**
8314  * @brief Get connection type
8315  * @param con_handle
8316  * @result connection_type
8317  */
8318 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
8319     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8320     if (!conn) return GAP_CONNECTION_INVALID;
8321     switch (conn->address_type){
8322         case BD_ADDR_TYPE_LE_PUBLIC:
8323         case BD_ADDR_TYPE_LE_RANDOM:
8324             return GAP_CONNECTION_LE;
8325         case BD_ADDR_TYPE_SCO:
8326             return GAP_CONNECTION_SCO;
8327         case BD_ADDR_TYPE_ACL:
8328             return GAP_CONNECTION_ACL;
8329         default:
8330             return GAP_CONNECTION_INVALID;
8331     }
8332 }
8333 
8334 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
8335     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8336     if (!conn) return HCI_ROLE_INVALID;
8337     return (hci_role_t) conn->role;
8338 }
8339 
8340 
8341 #ifdef ENABLE_CLASSIC
8342 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
8343     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8344     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8345     conn->request_role = role;
8346     hci_run();
8347     return ERROR_CODE_SUCCESS;
8348 }
8349 #endif
8350 
8351 #ifdef ENABLE_BLE
8352 
8353 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){
8354     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8355     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8356 
8357     conn->le_phy_update_all_phys    = all_phys;
8358     conn->le_phy_update_tx_phys     = tx_phys;
8359     conn->le_phy_update_rx_phys     = rx_phys;
8360     conn->le_phy_update_phy_options = phy_options;
8361 
8362     hci_run();
8363 
8364     return 0;
8365 }
8366 
8367 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8368     // check if already in list
8369     btstack_linked_list_iterator_t it;
8370     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8371     while (btstack_linked_list_iterator_has_next(&it)) {
8372         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
8373         if (entry->address_type != address_type) {
8374             continue;
8375         }
8376         if (memcmp(entry->address, address, 6) != 0) {
8377             continue;
8378         }
8379 		// disallow if already scheduled to add
8380 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
8381 			return ERROR_CODE_COMMAND_DISALLOWED;
8382 		}
8383 		// still on controller, but scheduled to remove -> re-add
8384 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
8385 		return ERROR_CODE_SUCCESS;
8386     }
8387     // alloc and add to list
8388     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
8389     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8390     entry->address_type = address_type;
8391     (void)memcpy(entry->address, address, 6);
8392     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
8393     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
8394     return ERROR_CODE_SUCCESS;
8395 }
8396 
8397 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8398     btstack_linked_list_iterator_t it;
8399     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8400     while (btstack_linked_list_iterator_has_next(&it)){
8401         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8402         if (entry->address_type != address_type) {
8403             continue;
8404         }
8405         if (memcmp(entry->address, address, 6) != 0) {
8406             continue;
8407         }
8408         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8409             // remove from controller if already present
8410             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8411         }  else {
8412             // directly remove entry from whitelist
8413             btstack_linked_list_iterator_remove(&it);
8414             btstack_memory_whitelist_entry_free(entry);
8415         }
8416         return ERROR_CODE_SUCCESS;
8417     }
8418     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8419 }
8420 
8421 static void hci_whitelist_clear(void){
8422     btstack_linked_list_iterator_t it;
8423     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8424     while (btstack_linked_list_iterator_has_next(&it)){
8425         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8426         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8427             // remove from controller if already present
8428             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8429             continue;
8430         }
8431         // directly remove entry from whitelist
8432         btstack_linked_list_iterator_remove(&it);
8433         btstack_memory_whitelist_entry_free(entry);
8434     }
8435 }
8436 
8437 /**
8438  * @brief Clear Whitelist
8439  * @return 0 if ok
8440  */
8441 uint8_t gap_whitelist_clear(void){
8442     hci_whitelist_clear();
8443     hci_run();
8444     return ERROR_CODE_SUCCESS;
8445 }
8446 
8447 /**
8448  * @brief Add Device to Whitelist
8449  * @param address_typ
8450  * @param address
8451  * @return 0 if ok
8452  */
8453 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8454     uint8_t status = hci_whitelist_add(address_type, address);
8455     if (status){
8456         return status;
8457     }
8458     hci_run();
8459     return ERROR_CODE_SUCCESS;
8460 }
8461 
8462 /**
8463  * @brief Remove Device from Whitelist
8464  * @param address_typ
8465  * @param address
8466  * @return 0 if ok
8467  */
8468 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8469     uint8_t status = hci_whitelist_remove(address_type, address);
8470     if (status){
8471         return status;
8472     }
8473     hci_run();
8474     return ERROR_CODE_SUCCESS;
8475 }
8476 
8477 #ifdef ENABLE_LE_CENTRAL
8478 /**
8479  * @brief Connect with Whitelist
8480  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
8481  * @return - if ok
8482  */
8483 uint8_t gap_connect_with_whitelist(void){
8484     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8485         return ERROR_CODE_COMMAND_DISALLOWED;
8486     }
8487     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8488     hci_run();
8489     return ERROR_CODE_SUCCESS;
8490 }
8491 
8492 /**
8493  * @brief Auto Connection Establishment - Start Connecting to device
8494  * @param address_typ
8495  * @param address
8496  * @return 0 if ok
8497  */
8498 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
8499     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8500         return ERROR_CODE_COMMAND_DISALLOWED;
8501     }
8502 
8503     uint8_t status = hci_whitelist_add(address_type, address);
8504     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
8505         return status;
8506     }
8507 
8508     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8509 
8510     hci_run();
8511     return ERROR_CODE_SUCCESS;
8512 }
8513 
8514 /**
8515  * @brief Auto Connection Establishment - Stop Connecting to device
8516  * @param address_typ
8517  * @param address
8518  * @return 0 if ok
8519  */
8520 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
8521     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8522         return ERROR_CODE_COMMAND_DISALLOWED;
8523     }
8524 
8525     hci_whitelist_remove(address_type, address);
8526     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
8527         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8528     }
8529     hci_run();
8530     return 0;
8531 }
8532 
8533 /**
8534  * @brief Auto Connection Establishment - Stop everything
8535  * @note  Convenience function to stop all active auto connection attempts
8536  */
8537 uint8_t gap_auto_connection_stop_all(void){
8538     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
8539         return ERROR_CODE_COMMAND_DISALLOWED;
8540     }
8541     hci_whitelist_clear();
8542     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8543     hci_run();
8544     return ERROR_CODE_SUCCESS;
8545 }
8546 
8547 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
8548     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8549     if (!conn) return 0;
8550     return conn->le_connection_interval;
8551 }
8552 #endif
8553 #endif
8554 
8555 #ifdef ENABLE_CLASSIC
8556 /**
8557  * @brief Set Extended Inquiry Response data
8558  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
8559  * @note has to be done before stack starts up
8560  */
8561 void gap_set_extended_inquiry_response(const uint8_t * data){
8562     hci_stack->eir_data = data;
8563     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
8564     hci_run();
8565 }
8566 
8567 /**
8568  * @brief Start GAP Classic Inquiry
8569  * @param duration in 1.28s units
8570  * @return 0 if ok
8571  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
8572  */
8573 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
8574     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
8575     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8576     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
8577         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8578     }
8579     hci_stack->inquiry_state = duration_in_1280ms_units;
8580     hci_stack->inquiry_max_period_length = 0;
8581     hci_stack->inquiry_min_period_length = 0;
8582     hci_run();
8583     return 0;
8584 }
8585 
8586 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
8587     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
8588     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
8589     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8590     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8591     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8592     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8593 
8594     hci_stack->inquiry_state = duration;
8595     hci_stack->inquiry_max_period_length = max_period_length;
8596     hci_stack->inquiry_min_period_length = min_period_length;
8597     hci_run();
8598     return 0;
8599 }
8600 
8601 /**
8602  * @brief Stop GAP Classic Inquiry
8603  * @return 0 if ok
8604  */
8605 int gap_inquiry_stop(void){
8606     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
8607         // emit inquiry complete event, before it even started
8608         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
8609         hci_emit_event(event, sizeof(event), 1);
8610         return 0;
8611     }
8612     switch (hci_stack->inquiry_state){
8613         case GAP_INQUIRY_STATE_ACTIVE:
8614             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
8615             hci_run();
8616             return ERROR_CODE_SUCCESS;
8617         case GAP_INQUIRY_STATE_PERIODIC:
8618             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
8619             hci_run();
8620             return ERROR_CODE_SUCCESS;
8621         default:
8622             return ERROR_CODE_COMMAND_DISALLOWED;
8623     }
8624 }
8625 
8626 void gap_inquiry_set_lap(uint32_t lap){
8627     hci_stack->inquiry_lap = lap;
8628 }
8629 
8630 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
8631     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
8632     hci_stack->inquiry_scan_window   = inquiry_scan_window;
8633     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
8634     hci_run();
8635 }
8636 
8637 
8638 /**
8639  * @brief Remote Name Request
8640  * @param addr
8641  * @param page_scan_repetition_mode
8642  * @param clock_offset only used when bit 15 is set
8643  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
8644  */
8645 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
8646     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8647     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
8648     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
8649     hci_stack->remote_name_clock_offset = clock_offset;
8650     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
8651     hci_run();
8652     return 0;
8653 }
8654 
8655 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
8656     hci_stack->gap_pairing_state = state;
8657     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
8658     hci_run();
8659     return 0;
8660 }
8661 
8662 /**
8663  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
8664  * @param addr
8665  * @param pin_data
8666  * @param pin_len
8667  * @return 0 if ok
8668  */
8669 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
8670     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8671     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
8672     hci_stack->gap_pairing_pin_len = pin_len;
8673     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
8674 }
8675 
8676 /**
8677  * @brief Legacy Pairing Pin Code Response
8678  * @param addr
8679  * @param pin
8680  * @return 0 if ok
8681  */
8682 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
8683     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
8684 }
8685 
8686 /**
8687  * @brief Abort Legacy Pairing
8688  * @param addr
8689  * @param pin
8690  * @return 0 if ok
8691  */
8692 int gap_pin_code_negative(bd_addr_t addr){
8693     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8694     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
8695 }
8696 
8697 /**
8698  * @brief SSP Passkey Response
8699  * @param addr
8700  * @param passkey
8701  * @return 0 if ok
8702  */
8703 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
8704     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8705     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
8706     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
8707 }
8708 
8709 /**
8710  * @brief Abort SSP Passkey Entry/Pairing
8711  * @param addr
8712  * @param pin
8713  * @return 0 if ok
8714  */
8715 int gap_ssp_passkey_negative(const bd_addr_t addr){
8716     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8717     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
8718 }
8719 
8720 /**
8721  * @brief Accept SSP Numeric Comparison
8722  * @param addr
8723  * @param passkey
8724  * @return 0 if ok
8725  */
8726 int gap_ssp_confirmation_response(const bd_addr_t addr){
8727     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8728     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
8729 }
8730 
8731 /**
8732  * @brief Abort SSP Numeric Comparison/Pairing
8733  * @param addr
8734  * @param pin
8735  * @return 0 if ok
8736  */
8737 int gap_ssp_confirmation_negative(const bd_addr_t addr){
8738     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8739     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
8740 }
8741 
8742 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
8743 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
8744     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8745     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8746     connectionSetAuthenticationFlags(conn, flag);
8747     hci_run();
8748     return ERROR_CODE_SUCCESS;
8749 }
8750 #endif
8751 
8752 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
8753 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
8754     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
8755 }
8756 
8757 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
8758     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
8759 }
8760 #endif
8761 
8762 #ifdef ENABLE_CLASSIC_PAIRING_OOB
8763 /**
8764  * @brief Report Remote OOB Data
8765  * @param bd_addr
8766  * @param c_192 Simple Pairing Hash C derived from P-192 public key
8767  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
8768  * @param c_256 Simple Pairing Hash C derived from P-256 public key
8769  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
8770  */
8771 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){
8772     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8773     if (connection == NULL) {
8774         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8775     }
8776     connection->classic_oob_c_192 = c_192;
8777     connection->classic_oob_r_192 = r_192;
8778 
8779     // ignore P-256 if not supported by us
8780     if (hci_stack->secure_connections_active){
8781         connection->classic_oob_c_256 = c_256;
8782         connection->classic_oob_r_256 = r_256;
8783     }
8784 
8785     return ERROR_CODE_SUCCESS;
8786 }
8787 /**
8788  * @brief Generate new OOB data
8789  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
8790  */
8791 void gap_ssp_generate_oob_data(void){
8792     hci_stack->classic_read_local_oob_data = true;
8793     hci_run();
8794 }
8795 
8796 #endif
8797 
8798 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
8799 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
8800     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8801     if (connection == NULL) {
8802         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8803     }
8804 
8805     memcpy(connection->link_key, link_key, sizeof(link_key_t));
8806     connection->link_key_type = type;
8807 
8808     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
8809 }
8810 
8811 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
8812 /**
8813  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
8814  * @param inquiry_mode see bluetooth_defines.h
8815  */
8816 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
8817     hci_stack->inquiry_mode = inquiry_mode;
8818 }
8819 
8820 /**
8821  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
8822  */
8823 void hci_set_sco_voice_setting(uint16_t voice_setting){
8824     hci_stack->sco_voice_setting = voice_setting;
8825 }
8826 
8827 /**
8828  * @brief Get SCO Voice Setting
8829  * @return current voice setting
8830  */
8831 uint16_t hci_get_sco_voice_setting(void){
8832     return hci_stack->sco_voice_setting;
8833 }
8834 
8835 static int hci_have_usb_transport(void){
8836     if (!hci_stack->hci_transport) return 0;
8837     const char * transport_name = hci_stack->hci_transport->name;
8838     if (!transport_name) return 0;
8839     return (transport_name[0] == 'H') && (transport_name[1] == '2');
8840 }
8841 
8842 /** @brief Get SCO packet length for current SCO Voice setting
8843  *  @note  Using SCO packets of the exact length is required for USB transfer
8844  *  @return Length of SCO packets in bytes (not audio frames)
8845  */
8846 uint16_t hci_get_sco_packet_length(void){
8847     uint16_t sco_packet_length = 0;
8848 
8849 #ifdef ENABLE_SCO_OVER_HCI
8850     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8851     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8852 
8853     if (hci_have_usb_transport()){
8854         // see Core Spec for H2 USB Transfer.
8855         // 3 byte SCO header + 24 bytes per connection
8856         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
8857         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
8858     } else {
8859         // 3 byte SCO header + SCO packet size over the air (60 bytes)
8860         sco_packet_length = 3 + 60 * multiplier;
8861         // assert that it still fits inside an SCO buffer
8862         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
8863             sco_packet_length = 3 + 60;
8864         }
8865     }
8866 #endif
8867 
8868 #ifdef HAVE_SCO_TRANSPORT
8869     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8870     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8871     sco_packet_length = 3 + 60 * multiplier;
8872 #endif
8873     return sco_packet_length;
8874 }
8875 
8876 /**
8877 * @brief Sets the master/slave policy
8878 * @param policy (0: attempt to become master, 1: let connecting device decide)
8879 */
8880 void hci_set_master_slave_policy(uint8_t policy){
8881     hci_stack->master_slave_policy = policy;
8882 }
8883 
8884 #endif
8885 
8886 HCI_STATE hci_get_state(void){
8887     return hci_stack->state;
8888 }
8889 
8890 #ifdef ENABLE_CLASSIC
8891 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
8892     hci_stack->gap_classic_accept_callback = accept_callback;
8893 }
8894 #endif
8895 
8896 /**
8897  * @brief Set callback for Bluetooth Hardware Error
8898  */
8899 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
8900     hci_stack->hardware_error_callback = fn;
8901 }
8902 
8903 void hci_disconnect_all(void){
8904     btstack_linked_list_iterator_t it;
8905     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
8906     while (btstack_linked_list_iterator_has_next(&it)){
8907         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
8908         if (con->state == SENT_DISCONNECT) continue;
8909         con->state = SEND_DISCONNECT;
8910     }
8911     hci_run();
8912 }
8913 
8914 uint16_t hci_get_manufacturer(void){
8915     return hci_stack->manufacturer;
8916 }
8917 
8918 #ifdef ENABLE_BLE
8919 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
8920     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
8921     if (!hci_con) return NULL;
8922     return &hci_con->sm_connection;
8923 }
8924 
8925 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
8926 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
8927 #endif
8928 
8929 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
8930     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8931     if (hci_connection == NULL) return 0;
8932     if (hci_is_le_connection(hci_connection)){
8933 #ifdef ENABLE_BLE
8934         sm_connection_t * sm_conn = &hci_connection->sm_connection;
8935         if (sm_conn->sm_connection_encrypted) {
8936             return sm_conn->sm_actual_encryption_key_size;
8937         }
8938 #endif
8939     } else {
8940 #ifdef ENABLE_CLASSIC
8941         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
8942             return hci_connection->encryption_key_size;
8943         }
8944 #endif
8945     }
8946     return 0;
8947 }
8948 
8949 bool gap_authenticated(hci_con_handle_t con_handle){
8950     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8951     if (hci_connection == NULL) return false;
8952 
8953     switch (hci_connection->address_type){
8954 #ifdef ENABLE_BLE
8955         case BD_ADDR_TYPE_LE_PUBLIC:
8956         case BD_ADDR_TYPE_LE_RANDOM:
8957             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
8958             return hci_connection->sm_connection.sm_connection_authenticated != 0;
8959 #endif
8960 #ifdef ENABLE_CLASSIC
8961         case BD_ADDR_TYPE_SCO:
8962         case BD_ADDR_TYPE_ACL:
8963             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
8964 #endif
8965         default:
8966             return false;
8967     }
8968 }
8969 
8970 bool gap_secure_connection(hci_con_handle_t con_handle){
8971     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8972     if (hci_connection == NULL) return 0;
8973 
8974     switch (hci_connection->address_type){
8975 #ifdef ENABLE_BLE
8976         case BD_ADDR_TYPE_LE_PUBLIC:
8977         case BD_ADDR_TYPE_LE_RANDOM:
8978             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
8979             return hci_connection->sm_connection.sm_connection_sc != 0;
8980 #endif
8981 #ifdef ENABLE_CLASSIC
8982         case BD_ADDR_TYPE_SCO:
8983         case BD_ADDR_TYPE_ACL:
8984             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
8985 #endif
8986         default:
8987             return false;
8988     }
8989 }
8990 
8991 bool gap_bonded(hci_con_handle_t con_handle){
8992 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8993 	if (hci_connection == NULL) return 0;
8994 
8995 #ifdef ENABLE_CLASSIC
8996 	link_key_t link_key;
8997 	link_key_type_t link_key_type;
8998 #endif
8999 	switch (hci_connection->address_type){
9000 #ifdef ENABLE_BLE
9001 		case BD_ADDR_TYPE_LE_PUBLIC:
9002 		case BD_ADDR_TYPE_LE_RANDOM:
9003 			return hci_connection->sm_connection.sm_le_db_index >= 0;
9004 #endif
9005 #ifdef ENABLE_CLASSIC
9006 		case BD_ADDR_TYPE_SCO:
9007 		case BD_ADDR_TYPE_ACL:
9008 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
9009 #endif
9010 		default:
9011 			return false;
9012 	}
9013 }
9014 
9015 #ifdef ENABLE_BLE
9016 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
9017     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
9018     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
9019     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
9020     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
9021     return sm_conn->sm_connection_authorization_state;
9022 }
9023 #endif
9024 
9025 #ifdef ENABLE_CLASSIC
9026 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){
9027     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9028     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9029     conn->sniff_min_interval = sniff_min_interval;
9030     conn->sniff_max_interval = sniff_max_interval;
9031     conn->sniff_attempt = sniff_attempt;
9032     conn->sniff_timeout = sniff_timeout;
9033     hci_run();
9034     return 0;
9035 }
9036 
9037 /**
9038  * @brief Exit Sniff mode
9039  * @param con_handle
9040  @ @return 0 if ok
9041  */
9042 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
9043     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9044     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9045     conn->sniff_min_interval = 0xffff;
9046     hci_run();
9047     return 0;
9048 }
9049 
9050 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){
9051     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9052     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9053     conn->sniff_subrating_max_latency = max_latency;
9054     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
9055     conn->sniff_subrating_min_local_timeout = min_local_timeout;
9056     hci_run();
9057     return ERROR_CODE_SUCCESS;
9058 }
9059 
9060 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){
9061     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9062     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9063     conn->qos_service_type = service_type;
9064     conn->qos_token_rate = token_rate;
9065     conn->qos_peak_bandwidth = peak_bandwidth;
9066     conn->qos_latency = latency;
9067     conn->qos_delay_variation = delay_variation;
9068     hci_run();
9069     return ERROR_CODE_SUCCESS;
9070 }
9071 
9072 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
9073     hci_stack->new_page_scan_interval = page_scan_interval;
9074     hci_stack->new_page_scan_window = page_scan_window;
9075     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
9076     hci_run();
9077 }
9078 
9079 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
9080     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
9081     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
9082     hci_run();
9083 }
9084 
9085 void gap_set_page_timeout(uint16_t page_timeout){
9086     hci_stack->page_timeout = page_timeout;
9087     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
9088     hci_run();
9089 }
9090 
9091 #endif
9092 
9093 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
9094 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
9095     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9096     if (le_device_db_index >= le_device_db_max_count()) return;
9097     uint8_t offset = le_device_db_index >> 3;
9098     uint8_t mask = 1 << (le_device_db_index & 7);
9099     hci_stack->le_resolving_list_add_entries[offset] |= mask;
9100     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9101     	// note: go back to remove entries, otherwise, a remove + add will skip the add
9102         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9103     }
9104 }
9105 
9106 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
9107 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9108 	if (le_device_db_index >= le_device_db_max_count()) return;
9109 	uint8_t offset = le_device_db_index >> 3;
9110 	uint8_t mask = 1 << (le_device_db_index & 7);
9111 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
9112 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9113 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9114 	}
9115 }
9116 
9117 uint8_t gap_load_resolving_list_from_le_device_db(void){
9118     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
9119 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
9120 	}
9121 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
9122 		// restart le resolving list update
9123 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
9124 	}
9125 	return ERROR_CODE_SUCCESS;
9126 }
9127 #endif
9128 
9129 #ifdef ENABLE_BLE
9130 #ifdef ENABLE_LE_CENTRAL
9131 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
9132 
9133 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9134     // check if already in list
9135     btstack_linked_list_iterator_t it;
9136     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9137     while (btstack_linked_list_iterator_has_next(&it)) {
9138         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
9139         if (entry->sid != advertising_sid) {
9140             continue;
9141         }
9142         if (entry->address_type != address_type) {
9143             continue;
9144         }
9145         if (memcmp(entry->address, address, 6) != 0) {
9146             continue;
9147         }
9148         // disallow if already scheduled to add
9149         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
9150             return ERROR_CODE_COMMAND_DISALLOWED;
9151         }
9152         // still on controller, but scheduled to remove -> re-add
9153         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9154         return ERROR_CODE_SUCCESS;
9155     }
9156     // alloc and add to list
9157     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
9158     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9159     entry->sid = advertising_sid;
9160     entry->address_type = address_type;
9161     (void)memcpy(entry->address, address, 6);
9162     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9163     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
9164     return ERROR_CODE_SUCCESS;
9165 }
9166 
9167 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9168     btstack_linked_list_iterator_t it;
9169     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9170     while (btstack_linked_list_iterator_has_next(&it)){
9171         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9172         if (entry->sid != advertising_sid) {
9173             continue;
9174         }
9175         if (entry->address_type != address_type) {
9176             continue;
9177         }
9178         if (memcmp(entry->address, address, 6) != 0) {
9179             continue;
9180         }
9181         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9182             // remove from controller if already present
9183             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9184         }  else {
9185             // directly remove entry from whitelist
9186             btstack_linked_list_iterator_remove(&it);
9187             btstack_memory_periodic_advertiser_list_entry_free(entry);
9188         }
9189         return ERROR_CODE_SUCCESS;
9190     }
9191     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9192 }
9193 
9194 static void hci_periodic_advertiser_list_clear(void){
9195     btstack_linked_list_iterator_t it;
9196     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9197     while (btstack_linked_list_iterator_has_next(&it)){
9198         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9199         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9200             // remove from controller if already present
9201             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9202             continue;
9203         }
9204         // directly remove entry from whitelist
9205         btstack_linked_list_iterator_remove(&it);
9206         btstack_memory_periodic_advertiser_list_entry_free(entry);
9207     }
9208 }
9209 
9210 uint8_t gap_periodic_advertiser_list_clear(void){
9211     hci_periodic_advertiser_list_clear();
9212     hci_run();
9213     return ERROR_CODE_SUCCESS;
9214 }
9215 
9216 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9217     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
9218     if (status){
9219         return status;
9220     }
9221     hci_run();
9222     return ERROR_CODE_SUCCESS;
9223 }
9224 
9225 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9226     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
9227     if (status){
9228         return status;
9229     }
9230     hci_run();
9231     return ERROR_CODE_SUCCESS;
9232 }
9233 
9234 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
9235                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
9236     // abort if already active
9237     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
9238         return ERROR_CODE_COMMAND_DISALLOWED;
9239     }
9240     // store request
9241     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
9242     hci_stack->le_periodic_sync_options = options;
9243     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
9244     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
9245     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
9246     hci_stack->le_periodic_sync_skip = skip;
9247     hci_stack->le_periodic_sync_timeout = sync_timeout;
9248     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
9249 
9250     hci_run();
9251     return ERROR_CODE_SUCCESS;
9252 }
9253 
9254 uint8_t gap_periodic_advertising_create_sync_cancel(void){
9255     // abort if not requested
9256     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
9257         return ERROR_CODE_COMMAND_DISALLOWED;
9258     }
9259     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
9260     hci_run();
9261     return ERROR_CODE_SUCCESS;
9262 }
9263 
9264 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
9265     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
9266         return ERROR_CODE_COMMAND_DISALLOWED;
9267     }
9268     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
9269     hci_run();
9270     return ERROR_CODE_SUCCESS;
9271 }
9272 
9273 #endif
9274 #endif
9275 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
9276 static uint8_t hci_iso_stream_create(hci_iso_type_t iso_type, hci_con_handle_t con_handle, uint8_t group_id,
9277                                      hci_iso_stream_state_t state) {
9278     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
9279     if (iso_stream == NULL){
9280         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
9281     } else {
9282         iso_stream->iso_type = iso_type;
9283         iso_stream->state = state;
9284         iso_stream->con_handle = con_handle;
9285         iso_stream->group_id = group_id;
9286         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
9287         return ERROR_CODE_SUCCESS;
9288     }
9289 }
9290 
9291 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
9292     btstack_linked_list_iterator_t it;
9293     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9294     while (btstack_linked_list_iterator_has_next(&it)){
9295         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9296         if (iso_stream->con_handle == con_handle ) {
9297             return iso_stream;
9298         }
9299     }
9300     return NULL;
9301 }
9302 
9303 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
9304     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->con_handle, iso_stream->group_id);
9305     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
9306     btstack_memory_hci_iso_stream_free(iso_stream);
9307 }
9308 
9309 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
9310     btstack_linked_list_iterator_t it;
9311     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9312     while (btstack_linked_list_iterator_has_next(&it)){
9313         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9314         if ((iso_stream->group_id == group_id) &&
9315             (iso_stream->iso_type == iso_type)){
9316             btstack_linked_list_iterator_remove(&it);
9317             btstack_memory_hci_iso_stream_free(iso_stream);
9318         }
9319     }
9320 }
9321 
9322 static void hci_iso_stream_requested_finalize(uint8_t group_id) {
9323     btstack_linked_list_iterator_t it;
9324     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9325     while (btstack_linked_list_iterator_has_next(&it)){
9326         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9327         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
9328             (iso_stream->group_id == group_id)){
9329             btstack_linked_list_iterator_remove(&it);
9330             btstack_memory_hci_iso_stream_free(iso_stream);
9331         }
9332     }
9333 }
9334 static void hci_iso_stream_requested_confirm(uint8_t big_handle){
9335     btstack_linked_list_iterator_t it;
9336     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9337     while (btstack_linked_list_iterator_has_next(&it)){
9338         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9339         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
9340             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
9341         }
9342     }
9343 }
9344 
9345 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
9346     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
9347     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
9348     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
9349     return (sdu_len_offset + 2 + sdu_len) == size;
9350 }
9351 
9352 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){
9353     if (hci_stack->iso_packet_handler == NULL) {
9354         return;
9355     }
9356     if (size < 4) {
9357         return;
9358     }
9359 
9360     // parse header
9361     uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0);
9362     uint16_t iso_data_len = little_endian_read_16(packet, 2);
9363     hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff);
9364     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
9365     uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3;
9366 
9367     // assert packet is complete
9368     if ((iso_data_len + 4u) != size){
9369         return;
9370     }
9371 
9372     if ((pb_flag & 0x01) == 0){
9373         if (pb_flag == 0x02){
9374             // The ISO_Data_Load field contains a header and a complete SDU.
9375             if (hci_iso_sdu_complete(packet, size)) {
9376                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
9377             }
9378         } else {
9379             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
9380             if (iso_stream == NULL){
9381                 return;
9382             }
9383             if (size > HCI_ISO_PAYLOAD_SIZE){
9384                 return;
9385             }
9386             memcpy(iso_stream->reassembly_buffer, packet, size);
9387             // fix pb_flag
9388             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
9389             iso_stream->reassembly_pos = size;
9390         }
9391     } else {
9392         // iso_data_load contains continuation or last fragment of an SDU
9393         uint8_t  ts_flag = (conn_handle_and_flags >> 14) & 1;
9394         if (ts_flag != 0){
9395            return;
9396         }
9397         // append fragment
9398         if (iso_stream == NULL){
9399             return;
9400         }
9401         if (iso_stream->reassembly_pos == 0){
9402             return;
9403         }
9404         if ((iso_stream->reassembly_pos + iso_data_len) > size){
9405             // reset reassembly buffer
9406             iso_stream->reassembly_pos = 0;
9407             return;
9408         }
9409         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len);
9410         iso_stream->reassembly_pos += iso_data_len;
9411 
9412         // deliver if last fragment and SDU complete
9413         if (pb_flag == 0x03){
9414             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
9415                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
9416             }
9417             iso_stream->reassembly_pos = 0;
9418         }
9419     }
9420 }
9421 
9422 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
9423     uint8_t event [6 + (MAX_NR_BIS * 2)];
9424     uint16_t pos = 0;
9425     event[pos++] = HCI_EVENT_META_GAP;
9426     event[pos++] = 4 + (2 * big->num_bis);
9427     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
9428     event[pos++] = status;
9429     event[pos++] = big->big_handle;
9430     event[pos++] = big->num_bis;
9431     uint8_t i;
9432     for (i=0;i<big->num_bis;i++){
9433         little_endian_store_16(event, pos, big->bis_con_handles[i]);
9434         pos += 2;
9435     }
9436     hci_emit_event(event, pos, 0);
9437 }
9438 
9439 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
9440     uint8_t event [6 + (MAX_NR_CIS * 2)];
9441     uint16_t pos = 0;
9442     event[pos++] = HCI_EVENT_META_GAP;
9443     event[pos++] = 4 + (2 * cig->num_cis);
9444     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
9445     event[pos++] = status;
9446     event[pos++] = cig->cig_id;
9447     event[pos++] = cig->num_cis;
9448     uint8_t i;
9449     for (i=0;i<cig->num_cis;i++){
9450         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
9451         pos += 2;
9452     }
9453     hci_emit_event(event, pos, 0);
9454 }
9455 
9456 static void
9457 hci_emit_cis_created(uint8_t cig_id, hci_con_handle_t cis_con_handle, uint8_t status) {
9458     uint8_t event [7];
9459     uint16_t pos = 0;
9460     event[pos++] = HCI_EVENT_META_GAP;
9461     event[pos++] = 5;
9462     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
9463     event[pos++] = status;
9464     event[pos++] = cig_id;
9465     little_endian_store_16(event, pos, cis_con_handle);
9466     pos += 2;
9467     hci_emit_event(event, pos, 0);
9468 }
9469 
9470 static void hci_emit_big_terminated(const le_audio_big_t * big){
9471     uint8_t event [4];
9472     uint16_t pos = 0;
9473     event[pos++] = HCI_EVENT_META_GAP;
9474     event[pos++] = 2;
9475     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
9476     event[pos++] = big->big_handle;
9477     hci_emit_event(event, pos, 0);
9478 }
9479 
9480 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
9481     uint8_t event [6 + (MAX_NR_BIS * 2)];
9482     uint16_t pos = 0;
9483     event[pos++] = HCI_EVENT_META_GAP;
9484     event[pos++] = 4;
9485     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
9486     event[pos++] = status;
9487     event[pos++] = big_sync->big_handle;
9488     event[pos++] = big_sync->num_bis;
9489     uint8_t i;
9490     for (i=0;i<big_sync->num_bis;i++){
9491         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
9492         pos += 2;
9493     }
9494     hci_emit_event(event, pos, 0);
9495 }
9496 
9497 static void hci_emit_big_sync_stopped(uint8_t big_handle){
9498     uint8_t event [4];
9499     uint16_t pos = 0;
9500     event[pos++] = HCI_EVENT_META_GAP;
9501     event[pos++] = 2;
9502     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
9503     event[pos++] = big_handle;
9504     hci_emit_event(event, pos, 0);
9505 }
9506 
9507 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
9508     uint8_t event[6];
9509     uint16_t pos = 0;
9510     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
9511     event[pos++] = sizeof(event) - 2;
9512     event[pos++] = big->big_handle;
9513     event[pos++] = bis_index;
9514     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
9515     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
9516 }
9517 
9518 static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) {
9519     uint8_t event[4];
9520     uint16_t pos = 0;
9521     event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW;
9522     event[pos++] = sizeof(event) - 2;
9523     little_endian_store_16(event, pos, cis_con_handle);
9524     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
9525 }
9526 
9527 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
9528     btstack_linked_list_iterator_t it;
9529     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9530     while (btstack_linked_list_iterator_has_next(&it)){
9531         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9532         if ( big->big_handle == big_handle ) {
9533             return big;
9534         }
9535     }
9536     return NULL;
9537 }
9538 
9539 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
9540     btstack_linked_list_iterator_t it;
9541     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
9542     while (btstack_linked_list_iterator_has_next(&it)){
9543         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
9544         if ( big_sync->big_handle == big_handle ) {
9545             return big_sync;
9546         }
9547     }
9548     return NULL;
9549 }
9550 
9551 void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
9552     hci_stack->iso_packets_to_queue = num_packets;
9553 }
9554 
9555 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
9556     btstack_linked_list_iterator_t it;
9557     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
9558     while (btstack_linked_list_iterator_has_next(&it)){
9559         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
9560         if ( cig->cig_id == cig_id ) {
9561             return cig;
9562         }
9563     }
9564     return NULL;
9565 }
9566 
9567 static void hci_iso_notify_can_send_now(void){
9568 
9569     // BIG
9570 
9571     btstack_linked_list_iterator_t it;
9572     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9573     while (btstack_linked_list_iterator_has_next(&it)){
9574         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9575         // track number completed packet timestamps
9576         if (big->num_completed_timestamp_current_valid){
9577             big->num_completed_timestamp_current_valid = false;
9578             if (big->num_completed_timestamp_previous_valid){
9579                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
9580                 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
9581                 int32_t  num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
9582                                                                                big->num_completed_timestamp_previous_ms);
9583                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
9584                     // to catch up, skip packet on all BIS
9585                     uint8_t i;
9586                     for (i=0;i<big->num_bis;i++){
9587                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9588                         if (iso_stream){
9589                             iso_stream->num_packets_to_skip++;
9590                         }
9591                     }
9592                 }
9593             }
9594             big->num_completed_timestamp_previous_valid = true;
9595             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
9596         }
9597 
9598         if (big->can_send_now_requested){
9599             // check if no outgoing iso packets pending and no can send now have to be emitted
9600             uint8_t i;
9601             bool can_send = true;
9602             uint8_t num_iso_queued_minimum = 0;
9603             for (i=0;i<big->num_bis;i++){
9604                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9605                 if (iso_stream == NULL) continue;
9606                 // handle case where individual ISO packet was sent too late:
9607                 // for each additionally queued packet, a new one needs to get skipped
9608                 if (i==0){
9609                     num_iso_queued_minimum = iso_stream->num_packets_sent;
9610                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
9611                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
9612                     iso_stream->num_packets_to_skip += num_packets_to_skip;
9613                     iso_stream->num_packets_sent    -= num_packets_to_skip;
9614                 }
9615                 // check if we can send now
9616                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
9617                     can_send = false;
9618                     break;
9619                 }
9620             }
9621             if (can_send){
9622                 // propagate can send now to individual streams
9623                 big->can_send_now_requested = false;
9624                 for (i=0;i<big->num_bis;i++){
9625                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9626                     iso_stream->emit_ready_to_send = true;
9627                 }
9628             }
9629         }
9630     }
9631 
9632     if (hci_stack->hci_packet_buffer_reserved) return;
9633 
9634     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9635     while (btstack_linked_list_iterator_has_next(&it)){
9636         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9637         // report bis ready
9638         uint8_t i;
9639         for (i=0;i<big->num_bis;i++){
9640             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9641             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
9642                 iso_stream->emit_ready_to_send = false;
9643                 hci_emit_bis_can_send_now(big, i);
9644                 break;
9645             }
9646         }
9647     }
9648 
9649     // CIS
9650     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9651     while (btstack_linked_list_iterator_has_next(&it)) {
9652         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9653         if ((iso_stream->can_send_now_requested) &&
9654             (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){
9655             iso_stream->can_send_now_requested = false;
9656             hci_emit_cis_can_send_now(iso_stream->con_handle);
9657         }
9658     }
9659 }
9660 
9661 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
9662     if (hci_big_for_handle(big_params->big_handle) != NULL){
9663         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9664     }
9665     if (big_params->num_bis == 0){
9666         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9667     }
9668     if (big_params->num_bis > MAX_NR_BIS){
9669         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9670     }
9671 
9672     // reserve ISO Streams
9673     uint8_t i;
9674     uint8_t status = ERROR_CODE_SUCCESS;
9675     for (i=0;i<big_params->num_bis;i++){
9676         status = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_CON_HANDLE_INVALID, big_params->big_handle,
9677                                        HCI_ISO_STREAM_STATE_REQUESTED);
9678         if (status != ERROR_CODE_SUCCESS) {
9679             break;
9680         }
9681     }
9682 
9683     // free structs on error
9684     if (status != ERROR_CODE_SUCCESS){
9685         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_params->big_handle);
9686         return status;
9687     }
9688 
9689     le_audio_big_t * big = storage;
9690     big->big_handle = big_params->big_handle;
9691     big->params = big_params;
9692     big->state = LE_AUDIO_BIG_STATE_CREATE;
9693     big->num_bis = big_params->num_bis;
9694     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9695 
9696     hci_run();
9697 
9698     return ERROR_CODE_SUCCESS;
9699 }
9700 
9701 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
9702     if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){
9703         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9704     }
9705     if (big_sync_params->num_bis == 0){
9706         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9707     }
9708     if (big_sync_params->num_bis > MAX_NR_BIS){
9709         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9710     }
9711 
9712     le_audio_big_sync_t * big_sync = storage;
9713     big_sync->big_handle = big_sync_params->big_handle;
9714     big_sync->params = big_sync_params;
9715     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
9716     big_sync->num_bis = big_sync_params->num_bis;
9717     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9718 
9719     hci_run();
9720 
9721     return ERROR_CODE_SUCCESS;
9722 }
9723 
9724 uint8_t gap_big_terminate(uint8_t big_handle){
9725     le_audio_big_t * big = hci_big_for_handle(big_handle);
9726     if (big == NULL){
9727         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9728     }
9729     switch (big->state){
9730         case LE_AUDIO_BIG_STATE_CREATE:
9731             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9732             hci_emit_big_terminated(big);
9733             break;
9734         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9735             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9736             break;
9737         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9738         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9739         case LE_AUDIO_BIG_STATE_ACTIVE:
9740             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
9741             hci_run();
9742             break;
9743         default:
9744             return ERROR_CODE_COMMAND_DISALLOWED;
9745     }
9746     return ERROR_CODE_SUCCESS;
9747 }
9748 
9749 uint8_t gap_big_sync_terminate(uint8_t big_handle){
9750     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
9751     if (big_sync == NULL){
9752         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9753     }
9754     switch (big_sync->state){
9755         case LE_AUDIO_BIG_STATE_CREATE:
9756             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9757             hci_emit_big_sync_stopped(big_handle);
9758             break;
9759         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9760             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9761             break;
9762         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9763         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9764         case LE_AUDIO_BIG_STATE_ACTIVE:
9765             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
9766             hci_run();
9767             break;
9768         default:
9769             return ERROR_CODE_COMMAND_DISALLOWED;
9770     }
9771     return ERROR_CODE_SUCCESS;
9772 }
9773 
9774 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
9775     le_audio_big_t * big = hci_big_for_handle(big_handle);
9776     if (big == NULL){
9777         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9778     }
9779     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
9780         return ERROR_CODE_COMMAND_DISALLOWED;
9781     }
9782     big->can_send_now_requested = true;
9783     hci_iso_notify_can_send_now();
9784     return ERROR_CODE_SUCCESS;
9785 }
9786 
9787 uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){
9788     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
9789     if (iso_stream == NULL){
9790         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9791     }
9792     if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) {
9793         return ERROR_CODE_COMMAND_DISALLOWED;
9794     }
9795     iso_stream->can_send_now_requested = true;
9796     hci_iso_notify_can_send_now();
9797     return ERROR_CODE_SUCCESS;
9798 }
9799 
9800 uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
9801     if (hci_cig_for_id(cig_params->cig_id) != NULL){
9802         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9803     }
9804     if (cig_params->num_cis == 0){
9805         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9806     }
9807     if (cig_params->num_cis > MAX_NR_BIS){
9808         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9809     }
9810 
9811     // reserve ISO Streams
9812     uint8_t i;
9813     uint8_t status = ERROR_CODE_SUCCESS;
9814     for (i=0;i<cig_params->num_cis;i++){
9815         status = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_CON_HANDLE_INVALID, cig_params->cig_id,
9816                                        HCI_ISO_STREAM_STATE_REQUESTED);
9817         if (status != ERROR_CODE_SUCCESS) {
9818             break;
9819         }
9820     }
9821 
9822     // free structs on error
9823     if (status != ERROR_CODE_SUCCESS){
9824         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
9825         return status;
9826     }
9827 
9828     le_audio_cig_t * cig = storage;
9829     cig->cig_id = cig_params->cig_id;
9830     cig->num_cis = cig_params->num_cis;
9831     cig->params = cig_params;
9832     cig->state = LE_AUDIO_CIG_STATE_CREATE;
9833     for (i=0;i<cig->num_cis;i++){
9834         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
9835         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
9836     }
9837     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
9838 
9839     hci_run();
9840 
9841     return ERROR_CODE_SUCCESS;
9842 }
9843 
9844 uint8_t gap_cis_create(uint8_t cig_handle, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
9845     le_audio_cig_t * cig = hci_cig_for_id(cig_handle);
9846     if (cig == NULL){
9847         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9848     }
9849 
9850     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
9851         return ERROR_CODE_COMMAND_DISALLOWED;
9852     }
9853 
9854     // store ACL Connection Handles
9855     uint8_t i;
9856     for (i=0;i<cig->num_cis;i++){
9857         // check that all con handles exit
9858         hci_con_handle_t cis_handle = cis_con_handles[i];
9859         uint8_t j;
9860         bool found = false;
9861         for (j=0;j<cig->num_cis;j++){
9862             if (cig->cis_con_handles[j] == cis_handle){
9863                 cig->acl_con_handles[j] = acl_con_handles[j];
9864                 found = true;
9865                 break;
9866             }
9867         }
9868         if (!found){
9869             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9870         }
9871     }
9872 
9873     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
9874     hci_run();
9875 
9876     return ERROR_CODE_SUCCESS;
9877 }
9878 
9879 static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_con_handle, hci_iso_stream_state_t state){
9880     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
9881     if (iso_stream != NULL){
9882         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9883     }
9884 
9885     uint8_t status = hci_iso_stream_create(HCI_ISO_TYPE_CIS, cis_con_handle,
9886                                            HCI_ISO_GROUP_ID_INVALID, state);
9887     if (status == ERROR_CODE_SUCCESS){
9888         return status;
9889     }
9890 
9891     hci_run();
9892     return ERROR_CODE_SUCCESS;
9893 }
9894 
9895 uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){
9896     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT);
9897 }
9898 
9899 uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){
9900     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT);
9901 }
9902 
9903 
9904 #endif
9905 #endif /* ENABLE_BLE */
9906 
9907 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
9908 void hci_setup_test_connections_fuzz(void){
9909     hci_connection_t * conn;
9910 
9911     // default address: 66:55:44:33:00:01
9912     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
9913 
9914     // setup Controller info
9915     hci_stack->num_cmd_packets = 255;
9916     hci_stack->acl_packets_total_num = 255;
9917 
9918     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
9919     addr[5] = 0x01;
9920     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9921     conn->con_handle = addr[5];
9922     conn->role  = HCI_ROLE_SLAVE;
9923     conn->state = RECEIVED_CONNECTION_REQUEST;
9924     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9925 
9926     // setup incoming Classic SCO connection with con handle 0x0002
9927     addr[5] = 0x02;
9928     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9929     conn->con_handle = addr[5];
9930     conn->role  = HCI_ROLE_SLAVE;
9931     conn->state = RECEIVED_CONNECTION_REQUEST;
9932     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9933 
9934     // setup ready Classic ACL connection with con handle 0x0003
9935     addr[5] = 0x03;
9936     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9937     conn->con_handle = addr[5];
9938     conn->role  = HCI_ROLE_SLAVE;
9939     conn->state = OPEN;
9940     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9941 
9942     // setup ready Classic SCO connection with con handle 0x0004
9943     addr[5] = 0x04;
9944     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9945     conn->con_handle = addr[5];
9946     conn->role  = HCI_ROLE_SLAVE;
9947     conn->state = OPEN;
9948     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9949 
9950     // setup ready LE ACL connection with con handle 0x005 and public address
9951     addr[5] = 0x05;
9952     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
9953     conn->con_handle = addr[5];
9954     conn->role  = HCI_ROLE_SLAVE;
9955     conn->state = OPEN;
9956     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9957     conn->sm_connection.sm_connection_encrypted = 1;
9958 }
9959 
9960 void hci_free_connections_fuzz(void){
9961     btstack_linked_list_iterator_t it;
9962     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9963     while (btstack_linked_list_iterator_has_next(&it)){
9964         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9965         btstack_linked_list_iterator_remove(&it);
9966         btstack_memory_hci_connection_free(con);
9967     }
9968 }
9969 void hci_simulate_working_fuzz(void){
9970     hci_stack->le_scanning_param_update = false;
9971     hci_init_done();
9972     hci_stack->num_cmd_packets = 255;
9973 }
9974 #endif
9975