xref: /btstack/src/hci.c (revision 42c5c5581b83a00e2c1de42e4fe687a30b9efa5a)
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 #endif
5588 
5589 #ifdef ENABLE_LE_PERIPHERAL
5590 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5591 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
5592     uint8_t  operation = 0;
5593     if (pos == 0){
5594         // first fragment or complete data
5595         operation |= 1;
5596     }
5597     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
5598         // last fragment or complete data
5599         operation |= 2;
5600     }
5601     return operation;
5602 }
5603 #endif
5604 #endif
5605 
5606 static bool hci_run_general_gap_le(void){
5607 
5608     btstack_linked_list_iterator_t lit;
5609 
5610     // Phase 1: collect what to stop
5611 
5612 #ifdef ENABLE_LE_CENTRAL
5613     bool scanning_stop = false;
5614     bool connecting_stop = false;
5615 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5616 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5617     bool periodic_sync_stop = false;
5618 #endif
5619 #endif
5620 #endif
5621 
5622 #ifdef ENABLE_LE_PERIPHERAL
5623     bool advertising_stop = false;
5624 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5625     le_advertising_set_t * advertising_stop_set = NULL;
5626 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5627     bool periodic_advertising_stop = false;
5628 #endif
5629 #endif
5630 #endif
5631 
5632     // check if own address changes
5633     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5634 
5635     // check if whitelist needs modification
5636     bool whitelist_modification_pending = false;
5637     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5638     while (btstack_linked_list_iterator_has_next(&lit)){
5639         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5640         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
5641             whitelist_modification_pending = true;
5642             break;
5643         }
5644     }
5645 
5646     // check if resolving list needs modification
5647     bool resolving_list_modification_pending = false;
5648 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5649     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
5650 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
5651         resolving_list_modification_pending = true;
5652     }
5653 #endif
5654 
5655 #ifdef ENABLE_LE_CENTRAL
5656 
5657 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5658     // check if periodic advertiser list needs modification
5659     bool periodic_list_modification_pending = false;
5660     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5661     while (btstack_linked_list_iterator_has_next(&lit)){
5662         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5663         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
5664             periodic_list_modification_pending = true;
5665             break;
5666         }
5667     }
5668 #endif
5669 
5670     // scanning control
5671     if (hci_stack->le_scanning_active) {
5672         // stop if:
5673         // - parameter change required
5674         // - it's disabled
5675         // - whitelist change required but used for scanning
5676         // - resolving list modified
5677         // - own address changes
5678         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
5679         if ((hci_stack->le_scanning_param_update) ||
5680             !hci_stack->le_scanning_enabled ||
5681             (scanning_uses_whitelist && whitelist_modification_pending) ||
5682             resolving_list_modification_pending ||
5683             random_address_change){
5684 
5685             scanning_stop = true;
5686         }
5687     }
5688 
5689     // connecting control
5690     bool connecting_with_whitelist;
5691     switch (hci_stack->le_connecting_state){
5692         case LE_CONNECTING_DIRECT:
5693         case LE_CONNECTING_WHITELIST:
5694             // stop connecting if:
5695             // - connecting uses white and whitelist modification pending
5696             // - if it got disabled
5697             // - resolving list modified
5698             // - own address changes
5699             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
5700             if ((connecting_with_whitelist && whitelist_modification_pending) ||
5701                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
5702                 resolving_list_modification_pending ||
5703                 random_address_change) {
5704 
5705                 connecting_stop = true;
5706             }
5707             break;
5708         default:
5709             break;
5710     }
5711 
5712 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5713 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5714     // periodic sync control
5715     bool sync_with_advertiser_list;
5716     switch(hci_stack->le_periodic_sync_state){
5717         case LE_CONNECTING_DIRECT:
5718         case LE_CONNECTING_WHITELIST:
5719             // stop sync if:
5720             // - sync with advertiser list and advertiser list modification pending
5721             // - if it got disabled
5722             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
5723             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
5724                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
5725                 periodic_sync_stop = true;
5726             }
5727             break;
5728         default:
5729             break;
5730     }
5731 #endif
5732 #endif
5733 
5734 #endif /* ENABLE_LE_CENTRAL */
5735 
5736 #ifdef ENABLE_LE_PERIPHERAL
5737     // le advertisement control
5738     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
5739         // stop if:
5740         // - parameter change required
5741         // - random address used in advertising and changes
5742         // - it's disabled
5743         // - whitelist change required but used for advertisement filter policy
5744         // - resolving list modified
5745         // - own address changes
5746         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
5747         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
5748         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
5749         if (advertising_change ||
5750             (advertising_uses_random_address && random_address_change) ||
5751             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
5752             (advertising_uses_whitelist && whitelist_modification_pending) ||
5753             resolving_list_modification_pending ||
5754             random_address_change) {
5755 
5756             advertising_stop = true;
5757         }
5758     }
5759 
5760 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5761     if (hci_extended_advertising_supported() && (advertising_stop == false)){
5762         btstack_linked_list_iterator_t it;
5763         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5764         while (btstack_linked_list_iterator_has_next(&it)){
5765             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5766             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5767                 // stop if:
5768                 // - parameter change required
5769                 // - random address used in connectable advertising and changes
5770                 // - it's disabled
5771                 // - whitelist change required but used for advertisement filter policy
5772                 // - resolving list modified
5773                 // - own address changes
5774                 // - advertisement set will be removed
5775                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
5776                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
5777                 bool advertising_uses_random_address =
5778                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
5779                         advertising_connectable;
5780                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
5781                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
5782                 bool advertising_set_random_address_change =
5783                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5784                 bool advertising_set_will_be_removed =
5785                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
5786                 if (advertising_parameter_change ||
5787                     (advertising_uses_random_address && advertising_set_random_address_change) ||
5788                     (advertising_enabled == false) ||
5789                     (advertising_uses_whitelist && whitelist_modification_pending) ||
5790                     resolving_list_modification_pending ||
5791                     advertising_set_will_be_removed) {
5792 
5793                     advertising_stop = true;
5794                     advertising_stop_set = advertising_set;
5795                     break;
5796                 }
5797             }
5798 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5799             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5800                 // stop if:
5801                 // - it's disabled
5802                 // - parameter change required
5803                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
5804                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
5805                 if ((periodic_enabled == false) || periodic_parameter_change){
5806                     periodic_advertising_stop = true;
5807                     advertising_stop_set = advertising_set;
5808                 }
5809             }
5810 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5811         }
5812     }
5813 #endif
5814 
5815 #endif
5816 
5817 
5818     // Phase 2: stop everything that should be off during modifications
5819 
5820 
5821     // 2.1 Outgoing connection
5822 #ifdef ENABLE_LE_CENTRAL
5823     if (connecting_stop){
5824         hci_send_cmd(&hci_le_create_connection_cancel);
5825         return true;
5826     }
5827 #endif
5828 
5829     // 2.2 Scanning
5830 #ifdef ENABLE_LE_CENTRAL
5831     if (scanning_stop){
5832         hci_stack->le_scanning_active = false;
5833         hci_le_scan_stop();
5834         return true;
5835     }
5836 
5837     // 2.3 Periodic Sync
5838 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5839     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
5840         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
5841         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
5842         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
5843         return true;
5844     }
5845 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5846     if (periodic_sync_stop){
5847         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
5848         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
5849         return true;
5850     }
5851 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5852 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5853 #endif /* ENABLE_LE_CENTRAL */
5854 
5855     // 2.4 Advertising: legacy, extended, periodic
5856 #ifdef ENABLE_LE_PERIPHERAL
5857     if (advertising_stop){
5858 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5859         if (hci_extended_advertising_supported()) {
5860             uint8_t advertising_stop_handle;
5861             if (advertising_stop_set != NULL){
5862                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5863                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5864             } else {
5865                 advertising_stop_handle = 0;
5866                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5867             }
5868             const uint8_t advertising_handles[] = { advertising_stop_handle };
5869             const uint16_t durations[] = { 0 };
5870             const uint16_t max_events[] = { 0 };
5871             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5872         } else
5873 #endif
5874         {
5875             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5876             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5877         }
5878         return true;
5879     }
5880 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5881 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5882     if (periodic_advertising_stop){
5883         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5884         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
5885         return true;
5886     }
5887 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5888 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5889 #endif /* ENABLE_LE_PERIPHERAL */
5890 
5891 
5892     // Phase 3: modify
5893 
5894     if (random_address_change){
5895         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5896 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5897         if (hci_extended_advertising_supported()) {
5898             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5899         }
5900 #endif
5901         {
5902             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5903         }
5904         return true;
5905     }
5906 
5907 #ifdef ENABLE_LE_CENTRAL
5908     if (hci_stack->le_scanning_param_update){
5909         hci_stack->le_scanning_param_update = false;
5910 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5911         if (hci_extended_advertising_supported()){
5912             // prepare arrays for all PHYs
5913             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
5914             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
5915             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
5916             uint8_t  scanning_phys     = 1;  // LE 1M PHY
5917             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
5918                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
5919         } else
5920 #endif
5921         {
5922             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5923                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
5924         }
5925         return true;
5926     }
5927 #endif
5928 
5929 #ifdef ENABLE_LE_PERIPHERAL
5930     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
5931         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5932         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5933 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5934         if (hci_extended_advertising_supported()){
5935             // map advertisment type to advertising event properties
5936             uint16_t adv_event_properties = 0;
5937             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5938             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5939                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5940             }
5941             hci_stack->le_advertising_set_in_current_command = 0;
5942             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5943                          0,
5944                          adv_event_properties,
5945                          hci_stack->le_advertisements_interval_min,
5946                          hci_stack->le_advertisements_interval_max,
5947                          hci_stack->le_advertisements_channel_map,
5948                          hci_stack->le_advertisements_own_addr_type,
5949                          hci_stack->le_advertisements_direct_address_type,
5950                          hci_stack->le_advertisements_direct_address,
5951                          hci_stack->le_advertisements_filter_policy,
5952                          0x7f,  // tx power: no preference
5953                          0x01,  // primary adv phy: LE 1M
5954                          0,     // secondary adv max skip
5955                          0,     // secondary adv phy
5956                          0,     // adv sid
5957                          0      // scan request notification
5958                          );
5959         }
5960 #endif
5961         {
5962             hci_send_cmd(&hci_le_set_advertising_parameters,
5963                          hci_stack->le_advertisements_interval_min,
5964                          hci_stack->le_advertisements_interval_max,
5965                          hci_stack->le_advertisements_type,
5966                          hci_stack->le_advertisements_own_addr_type,
5967                          hci_stack->le_advertisements_direct_address_type,
5968                          hci_stack->le_advertisements_direct_address,
5969                          hci_stack->le_advertisements_channel_map,
5970                          hci_stack->le_advertisements_filter_policy);
5971         }
5972         return true;
5973     }
5974 
5975     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
5976         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5977         uint8_t adv_data_clean[31];
5978         memset(adv_data_clean, 0, sizeof(adv_data_clean));
5979         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
5980                      hci_stack->le_advertisements_data_len);
5981         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
5982 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5983         if (hci_extended_advertising_supported()){
5984             hci_stack->le_advertising_set_in_current_command = 0;
5985             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
5986         } else
5987 #endif
5988         {
5989             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
5990         }
5991         return true;
5992     }
5993 
5994     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
5995         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5996         uint8_t scan_data_clean[31];
5997         memset(scan_data_clean, 0, sizeof(scan_data_clean));
5998         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
5999                      hci_stack->le_scan_response_data_len);
6000         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6001 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6002         if (hci_extended_advertising_supported()){
6003             hci_stack->le_advertising_set_in_current_command = 0;
6004             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6005         } else
6006 #endif
6007         {
6008             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6009         }
6010         return true;
6011     }
6012 
6013 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6014     if (hci_extended_advertising_supported()) {
6015         btstack_linked_list_iterator_t it;
6016         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6017         while (btstack_linked_list_iterator_has_next(&it)){
6018             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6019             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6020                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6021                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6022                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6023                 return true;
6024             }
6025             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
6026                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6027                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
6028                 return true;
6029             }
6030             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6031                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6032                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6033                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6034                              advertising_set->advertising_handle,
6035                              advertising_set->extended_params.advertising_event_properties,
6036                              advertising_set->extended_params.primary_advertising_interval_min,
6037                              advertising_set->extended_params.primary_advertising_interval_max,
6038                              advertising_set->extended_params.primary_advertising_channel_map,
6039                              advertising_set->extended_params.own_address_type,
6040                              advertising_set->extended_params.peer_address_type,
6041                              advertising_set->extended_params.peer_address,
6042                              advertising_set->extended_params.advertising_filter_policy,
6043                              advertising_set->extended_params.advertising_tx_power,
6044                              advertising_set->extended_params.primary_advertising_phy,
6045                              advertising_set->extended_params.secondary_advertising_max_skip,
6046                              advertising_set->extended_params.secondary_advertising_phy,
6047                              advertising_set->extended_params.advertising_sid,
6048                              advertising_set->extended_params.scan_request_notification_enable
6049                 );
6050                 return true;
6051             }
6052             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6053                 uint16_t pos = advertising_set->adv_data_pos;
6054                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6055                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6056                 if ((operation & 0x02) != 0){
6057                     // last fragment or complete data
6058                     operation |= 2;
6059                     advertising_set->adv_data_pos = 0;
6060                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6061                 } else {
6062                     advertising_set->adv_data_pos += data_to_upload;
6063                 }
6064                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6065                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6066                 return true;
6067             }
6068             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6069                 uint16_t pos = advertising_set->scan_data_pos;
6070                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6071                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6072                 if ((operation & 0x02) != 0){
6073                     advertising_set->scan_data_pos = 0;
6074                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6075                 } else {
6076                     advertising_set->scan_data_pos += data_to_upload;
6077                 }
6078                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6079                 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]);
6080                 return true;
6081             }
6082 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6083             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
6084                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
6085                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6086                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
6087                              advertising_set->advertising_handle,
6088                              advertising_set->periodic_params.periodic_advertising_interval_min,
6089                              advertising_set->periodic_params.periodic_advertising_interval_max,
6090                              advertising_set->periodic_params.periodic_advertising_properties);
6091                 return true;
6092             }
6093             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
6094                 uint16_t pos = advertising_set->periodic_data_pos;
6095                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
6096                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6097                 if ((operation & 0x02) != 0){
6098                     // last fragment or complete data
6099                     operation |= 2;
6100                     advertising_set->periodic_data_pos = 0;
6101                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
6102                 } else {
6103                     advertising_set->periodic_data_pos += data_to_upload;
6104                 }
6105                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6106                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
6107                 return true;
6108             }
6109 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6110         }
6111     }
6112 #endif
6113 
6114 #endif
6115 
6116 #ifdef ENABLE_LE_CENTRAL
6117     // if connect with whitelist was active and is not cancelled yet, wait until next time
6118     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
6119 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6120     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
6121     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
6122 #endif
6123 #endif
6124 
6125     // LE Whitelist Management
6126     if (whitelist_modification_pending){
6127         // add/remove entries
6128         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6129         while (btstack_linked_list_iterator_has_next(&lit)){
6130             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6131 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
6132 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6133 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
6134 				return true;
6135 			}
6136             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
6137 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
6138                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
6139                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
6140                 return true;
6141             }
6142             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
6143 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6144 				btstack_memory_whitelist_entry_free(entry);
6145             }
6146         }
6147     }
6148 
6149 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6150     // LE Resolving List Management
6151     if (resolving_list_supported) {
6152 		uint16_t i;
6153 		switch (hci_stack->le_resolving_list_state) {
6154 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
6155 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6156 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
6157 				return true;
6158 			case LE_RESOLVING_LIST_READ_SIZE:
6159 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
6160 				hci_send_cmd(&hci_le_read_resolving_list_size);
6161 				return true;
6162 			case LE_RESOLVING_LIST_SEND_CLEAR:
6163 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
6164 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6165 							  sizeof(hci_stack->le_resolving_list_add_entries));
6166 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6167 							  sizeof(hci_stack->le_resolving_list_remove_entries));
6168 				hci_send_cmd(&hci_le_clear_resolving_list);
6169 				return true;
6170 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
6171                 // first remove old entries
6172 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6173 					uint8_t offset = i >> 3;
6174 					uint8_t mask = 1 << (i & 7);
6175 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
6176 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
6177 					bd_addr_t peer_identity_addreses;
6178 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6179 					sm_key_t peer_irk;
6180 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6181 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6182 
6183 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6184 					// trigger whitelist entry 'update' (work around for controller bug)
6185 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6186 					while (btstack_linked_list_iterator_has_next(&lit)) {
6187 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6188 						if (entry->address_type != peer_identity_addr_type) continue;
6189 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6190 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6191 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6192 					}
6193 #endif
6194 
6195 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6196 								 peer_identity_addreses);
6197 					return true;
6198 				}
6199 
6200                 // then add new entries
6201 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6202 					uint8_t offset = i >> 3;
6203 					uint8_t mask = 1 << (i & 7);
6204 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
6205 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
6206 					bd_addr_t peer_identity_addreses;
6207 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6208 					sm_key_t peer_irk;
6209 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6210 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6211                     if (btstack_is_null(peer_irk, 16)) continue;
6212 					const uint8_t *local_irk = gap_get_persistent_irk();
6213 					// command uses format specifier 'P' that stores 16-byte value without flip
6214 					uint8_t local_irk_flipped[16];
6215 					uint8_t peer_irk_flipped[16];
6216 					reverse_128(local_irk, local_irk_flipped);
6217 					reverse_128(peer_irk, peer_irk_flipped);
6218 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6219 								 peer_irk_flipped, local_irk_flipped);
6220 					return true;
6221 				}
6222 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6223 				break;
6224 
6225 			default:
6226 				break;
6227 		}
6228 	}
6229     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6230 #endif
6231 
6232 #ifdef ENABLE_LE_CENTRAL
6233 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6234     // LE Whitelist Management
6235     if (periodic_list_modification_pending){
6236         // add/remove entries
6237         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6238         while (btstack_linked_list_iterator_has_next(&lit)){
6239             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6240             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6241                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6242                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
6243                 return true;
6244             }
6245             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6246                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6247                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
6248                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6249                 return true;
6250             }
6251             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6252                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6253                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6254             }
6255         }
6256     }
6257 #endif
6258 #endif
6259 
6260 #ifdef ENABLE_LE_CENTRAL
6261 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6262 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6263     if (hci_stack->le_past_set_default_params){
6264         hci_stack->le_past_set_default_params = false;
6265         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
6266                      hci_stack->le_past_mode,
6267                      hci_stack->le_past_skip,
6268                      hci_stack->le_past_sync_timeout,
6269                      hci_stack->le_past_cte_type);
6270         return true;
6271     }
6272 #endif
6273 #endif
6274 #endif
6275 
6276     // post-pone all actions until stack is fully working
6277     if (hci_stack->state != HCI_STATE_WORKING) return false;
6278 
6279     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6280     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6281 
6282     // Phase 4: restore state
6283 
6284 #ifdef ENABLE_LE_CENTRAL
6285     // re-start scanning
6286     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6287         hci_stack->le_scanning_active = true;
6288 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6289         if (hci_extended_advertising_supported()){
6290             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
6291         } else
6292 #endif
6293         {
6294             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
6295         }
6296         return true;
6297     }
6298 #endif
6299 
6300 #ifdef ENABLE_LE_CENTRAL
6301     // re-start connecting
6302     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6303         bd_addr_t null_addr;
6304         memset(null_addr, 0, 6);
6305         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6306         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6307         hci_send_cmd(&hci_le_create_connection,
6308                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
6309                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
6310                      1,         // use whitelist
6311                      0,         // peer address type
6312                      null_addr, // peer bd addr
6313                      hci_stack->le_connection_own_addr_type,   // our addr type:
6314                      hci_stack->le_connection_interval_min,    // conn interval min
6315                      hci_stack->le_connection_interval_max,    // conn interval max
6316                      hci_stack->le_connection_latency,         // conn latency
6317                      hci_stack->le_supervision_timeout,        // conn latency
6318                      hci_stack->le_minimum_ce_length,          // min ce length
6319                      hci_stack->le_maximum_ce_length           // max ce length
6320         );
6321         return true;
6322     }
6323 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6324     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6325         switch(hci_stack->le_periodic_sync_request){
6326             case LE_CONNECTING_DIRECT:
6327             case LE_CONNECTING_WHITELIST:
6328                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6329                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6330                              hci_stack->le_periodic_sync_options,
6331                              hci_stack->le_periodic_sync_advertising_sid,
6332                              hci_stack->le_periodic_sync_advertiser_address_type,
6333                              hci_stack->le_periodic_sync_advertiser_address,
6334                              hci_stack->le_periodic_sync_skip,
6335                              hci_stack->le_periodic_sync_timeout,
6336                              hci_stack->le_periodic_sync_cte_type);
6337                 return true;
6338             default:
6339                 break;
6340         }
6341     }
6342 #endif
6343 #endif
6344 
6345 #ifdef ENABLE_LE_PERIPHERAL
6346     // re-start advertising
6347     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6348         // check if advertisements should be enabled given
6349         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6350         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6351 
6352 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6353         if (hci_extended_advertising_supported()){
6354             const uint8_t advertising_handles[] = { 0 };
6355             const uint16_t durations[] = { 0 };
6356             const uint16_t max_events[] = { 0 };
6357             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6358         } else
6359 #endif
6360         {
6361             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6362         }
6363         return true;
6364     }
6365 
6366 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6367     if (hci_extended_advertising_supported()) {
6368         btstack_linked_list_iterator_t it;
6369         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6370         while (btstack_linked_list_iterator_has_next(&it)) {
6371             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6372             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6373                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6374                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6375                 const uint16_t durations[] = { advertising_set->enable_timeout };
6376                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6377                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6378                 return true;
6379             }
6380 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6381             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6382                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6383                 uint8_t enable = 1;
6384                 if (advertising_set->periodic_include_adi){
6385                     enable |= 2;
6386                 }
6387                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6388                 return true;
6389             }
6390 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6391         }
6392     }
6393 #endif
6394 #endif
6395 
6396     return false;
6397 }
6398 
6399 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6400 static bool hci_run_iso_tasks(void){
6401     btstack_linked_list_iterator_t it;
6402 
6403     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
6404         return false;
6405     }
6406 
6407     // BIG
6408     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6409     while (btstack_linked_list_iterator_has_next(&it)){
6410         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6411         switch (big->state){
6412             case LE_AUDIO_BIG_STATE_CREATE:
6413                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
6414                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6415                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6416                 hci_send_cmd(&hci_le_create_big,
6417                              big->params->big_handle,
6418                              big->params->advertising_handle,
6419                              big->params->num_bis,
6420                              big->params->sdu_interval_us,
6421                              big->params->max_sdu,
6422                              big->params->max_transport_latency_ms,
6423                              big->params->rtn,
6424                              big->params->phy,
6425                              big->params->packing,
6426                              big->params->framing,
6427                              big->params->encryption,
6428                              big->params->broadcast_code);
6429                 return true;
6430             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6431                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6432                 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);
6433                 return true;
6434             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6435                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6436                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6437                 return true;
6438             case LE_AUDIO_BIG_STATE_TERMINATE:
6439                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6440                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6441                 return true;
6442             default:
6443                 break;
6444         }
6445     }
6446 
6447     // BIG Sync
6448     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6449     while (btstack_linked_list_iterator_has_next(&it)){
6450         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6451         switch (big_sync->state){
6452             case LE_AUDIO_BIG_STATE_CREATE:
6453                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
6454                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6455                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6456                 hci_send_cmd(&hci_le_big_create_sync,
6457                              big_sync->params->big_handle,
6458                              big_sync->params->sync_handle,
6459                              big_sync->params->encryption,
6460                              big_sync->params->broadcast_code,
6461                              big_sync->params->mse,
6462                              big_sync->params->big_sync_timeout_10ms,
6463                              big_sync->params->num_bis,
6464                              big_sync->params->bis_indices);
6465                 return true;
6466             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6467                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6468                 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);
6469                 return true;
6470             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6471                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6472                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6473                 return true;
6474             case LE_AUDIO_BIG_STATE_TERMINATE:
6475                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6476                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6477                 return true;
6478             default:
6479                 break;
6480         }
6481     }
6482 
6483     // CIG
6484     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
6485     while (btstack_linked_list_iterator_has_next(&it)) {
6486         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
6487         uint8_t i;
6488         // Set CIG Parameters
6489         uint8_t cis_id[MAX_NR_CIS];
6490         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
6491         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
6492         uint8_t phy_c_to_p[MAX_NR_CIS];
6493         uint8_t phy_p_to_c[MAX_NR_CIS];
6494         uint8_t rtn_c_to_p[MAX_NR_CIS];
6495         uint8_t rtn_p_to_c[MAX_NR_CIS];
6496         switch (cig->state) {
6497             case LE_AUDIO_CIG_STATE_CREATE:
6498                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6499                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6500                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
6501                 le_audio_cig_params_t * params = cig->params;
6502                 for (i = 0; i < params->num_cis; i++) {
6503                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
6504                     cis_id[i]         = cis_params->cis_id;
6505                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
6506                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
6507                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
6508                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
6509                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
6510                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
6511                 }
6512                 hci_send_cmd(&hci_le_set_cig_parameters,
6513                              cig->cig_id,
6514                              params->sdu_interval_c_to_p,
6515                              params->sdu_interval_p_to_c,
6516                              params->worst_case_sca,
6517                              params->packing,
6518                              params->framing,
6519                              params->max_transport_latency_c_to_p,
6520                              params->max_transport_latency_p_to_c,
6521                              params->num_cis,
6522                              cis_id,
6523                              max_sdu_c_to_p,
6524                              max_sdu_p_to_c,
6525                              phy_c_to_p,
6526                              phy_p_to_c,
6527                              rtn_c_to_p,
6528                              rtn_p_to_c
6529                 );
6530                 return true;
6531             case LE_AUDIO_CIG_STATE_CREATE_CIS:
6532                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6533                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6534                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
6535                 for (i=0;i<cig->num_cis;i++){
6536                     cig->cis_setup_active[i] = true;
6537                 }
6538                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
6539                 return true;
6540             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
6541                 while (cig->state_vars.next_cis < (cig->num_cis * 2)){
6542                     // find next path to setup
6543                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
6544                     if (cig->cis_established[cis_index] == false) {
6545                         continue;
6546                     }
6547                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
6548                     bool setup = true;
6549                     if (cis_direction == 0){
6550                         // 0 - input - host to controller
6551                         // we are central => central to peripheral
6552                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
6553                     } else {
6554                         // 1 - output - controller to host
6555                         // we are central => peripheral to central
6556                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
6557                     }
6558                     if (setup){
6559                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6560                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6561                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
6562                         hci_send_cmd(&hci_le_setup_iso_data_path, cig->cis_con_handles[cis_index], cis_direction, 0, 0, 0, 0, 0, 0, NULL);
6563                         return true;
6564                     }
6565                     cig->state_vars.next_cis++;
6566                 }
6567                 // emit done
6568                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
6569             default:
6570                 break;
6571         }
6572     }
6573 
6574     // CIS Accept/Reject
6575     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
6576     while (btstack_linked_list_iterator_has_next(&it)) {
6577         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
6578         hci_con_handle_t con_handle;
6579         switch (iso_stream->state){
6580             case HCI_ISO_STREAM_W2_ACCEPT:
6581                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
6582                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6583                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6584                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->con_handle);
6585                 return true;
6586             case HCI_ISO_STREAM_W2_REJECT:
6587                 con_handle = iso_stream->con_handle;
6588                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6589                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6590                 hci_iso_stream_finalize(iso_stream);
6591                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
6592                 return true;
6593             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
6594                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6595                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6596                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
6597                 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->con_handle, 0, 0, 0, 0, 0, 0, 0, NULL);
6598                 break;
6599             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
6600                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6601                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6602                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT;
6603                 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->con_handle, 1, 0, 0, 0, 0, 0, 0, NULL);
6604                 break;
6605             default:
6606                 break;
6607         }
6608     }
6609 
6610     return false;
6611 }
6612 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6613 #endif
6614 
6615 static bool hci_run_general_pending_commands(void){
6616     btstack_linked_item_t * it;
6617     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6618         hci_connection_t * connection = (hci_connection_t *) it;
6619 
6620         switch(connection->state){
6621             case SEND_CREATE_CONNECTION:
6622                 switch(connection->address_type){
6623 #ifdef ENABLE_CLASSIC
6624                     case BD_ADDR_TYPE_ACL:
6625                         log_info("sending hci_create_connection");
6626                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
6627                         break;
6628 #endif
6629                     default:
6630 #ifdef ENABLE_BLE
6631 #ifdef ENABLE_LE_CENTRAL
6632                         log_info("sending hci_le_create_connection");
6633                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6634                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6635 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6636                         if (hci_extended_advertising_supported()) {
6637                             uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval };
6638                             uint16_t le_connection_scan_window[1]   = { hci_stack->le_connection_scan_window };
6639                             uint16_t le_connection_interval_min[1]  = { hci_stack->le_connection_interval_min };
6640                             uint16_t le_connection_interval_max[1]  = { hci_stack->le_connection_interval_max };
6641                             uint16_t le_connection_latency[1]       = { hci_stack->le_connection_latency };
6642                             uint16_t le_supervision_timeout[1]      = { hci_stack->le_supervision_timeout };
6643                             uint16_t le_minimum_ce_length[1]        = { hci_stack->le_minimum_ce_length };
6644                             uint16_t le_maximum_ce_length[1]        = { hci_stack->le_maximum_ce_length };
6645                             hci_send_cmd(&hci_le_extended_create_connection,
6646                                          0,         // don't use whitelist
6647                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6648                                          connection->address_type,      // peer address type
6649                                          connection->address,           // peer bd addr
6650                                          1,                             // initiating PHY - 1M
6651                                          le_connection_scan_interval,   // conn scan interval
6652                                          le_connection_scan_window,     // conn scan windows
6653                                          le_connection_interval_min,    // conn interval min
6654                                          le_connection_interval_max,    // conn interval max
6655                                          le_connection_latency,         // conn latency
6656                                          le_supervision_timeout,        // conn latency
6657                                          le_minimum_ce_length,          // min ce length
6658                                          le_maximum_ce_length           // max ce length
6659                             );                        }
6660                         else
6661 #endif
6662                         {
6663                             hci_send_cmd(&hci_le_create_connection,
6664                                          hci_stack->le_connection_scan_interval,    // conn scan interval
6665                                          hci_stack->le_connection_scan_window,      // conn scan windows
6666                                          0,         // don't use whitelist
6667                                          connection->address_type, // peer address type
6668                                          connection->address,      // peer bd addr
6669                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6670                                          hci_stack->le_connection_interval_min,    // conn interval min
6671                                          hci_stack->le_connection_interval_max,    // conn interval max
6672                                          hci_stack->le_connection_latency,         // conn latency
6673                                          hci_stack->le_supervision_timeout,        // conn latency
6674                                          hci_stack->le_minimum_ce_length,          // min ce length
6675                                          hci_stack->le_maximum_ce_length          // max ce length
6676                             );
6677                         }
6678                         connection->state = SENT_CREATE_CONNECTION;
6679 #endif
6680 #endif
6681                         break;
6682                 }
6683                 return true;
6684 
6685 #ifdef ENABLE_CLASSIC
6686             case RECEIVED_CONNECTION_REQUEST:
6687                 connection->role  = HCI_ROLE_SLAVE;
6688                 if (connection->address_type == BD_ADDR_TYPE_ACL){
6689                     log_info("sending hci_accept_connection_request");
6690                     connection->state = ACCEPTED_CONNECTION_REQUEST;
6691                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
6692                     return true;
6693                 }
6694                 break;
6695 #endif
6696             case SEND_DISCONNECT:
6697                 connection->state = SENT_DISCONNECT;
6698                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6699                 return true;
6700 
6701             default:
6702                 break;
6703         }
6704 
6705         // no further commands if connection is about to get shut down
6706         if (connection->state == SENT_DISCONNECT) continue;
6707 
6708 #ifdef ENABLE_CLASSIC
6709 
6710         // Handling link key request requires remote supported features
6711         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
6712             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
6713             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
6714 
6715             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
6716             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
6717             if (have_link_key && security_level_sufficient){
6718                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
6719             } else {
6720                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
6721             }
6722             return true;
6723         }
6724 
6725         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
6726             log_info("denying to pin request");
6727             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
6728             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
6729             return true;
6730         }
6731 
6732         // security assessment requires remote features
6733         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
6734             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
6735             hci_ssp_assess_security_on_io_cap_request(connection);
6736             // 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
6737         }
6738 
6739         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
6740             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6741             // set authentication requirements:
6742             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
6743             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
6744             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
6745             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
6746                 authreq |= 1;
6747             }
6748             bool bonding = hci_stack->bondable;
6749             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
6750                 // if we have received IO Cap Response, we're in responder role
6751                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6752                 if (bonding && !remote_bonding){
6753                     log_info("Remote not bonding, dropping local flag");
6754                     bonding = false;
6755                 }
6756             }
6757             if (bonding){
6758                 if (connection->bonding_flags & BONDING_DEDICATED){
6759                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6760                 } else {
6761                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
6762                 }
6763             }
6764             uint8_t have_oob_data = 0;
6765 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6766             if (connection->classic_oob_c_192 != NULL){
6767                     have_oob_data |= 1;
6768             }
6769             if (connection->classic_oob_c_256 != NULL){
6770                 have_oob_data |= 2;
6771             }
6772 #endif
6773             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
6774             return true;
6775         }
6776 
6777         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
6778             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6779             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
6780             return true;
6781         }
6782 
6783 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6784         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
6785             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
6786             const uint8_t zero[16] = { 0 };
6787             const uint8_t * r_192 = zero;
6788             const uint8_t * c_192 = zero;
6789             const uint8_t * r_256 = zero;
6790             const uint8_t * c_256 = zero;
6791             // verify P-256 OOB
6792             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
6793                 c_256 = connection->classic_oob_c_256;
6794                 if (connection->classic_oob_r_256 != NULL) {
6795                     r_256 = connection->classic_oob_r_256;
6796                 }
6797             }
6798             // verify P-192 OOB
6799             if ((connection->classic_oob_c_192 != NULL)) {
6800                 c_192 = connection->classic_oob_c_192;
6801                 if (connection->classic_oob_r_192 != NULL) {
6802                     r_192 = connection->classic_oob_r_192;
6803                 }
6804             }
6805 
6806             // assess security
6807             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
6808             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
6809             if (need_level_4 && !can_reach_level_4){
6810                 log_info("Level 4 required, but not possible -> abort");
6811                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
6812                 // send oob negative reply
6813                 c_256 = NULL;
6814                 c_192 = NULL;
6815             }
6816 
6817             // Reply
6818             if (c_256 != zero) {
6819                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
6820             } else if (c_192 != zero){
6821                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
6822             } else {
6823                 hci_stack->classic_oob_con_handle = connection->con_handle;
6824                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
6825             }
6826             return true;
6827         }
6828 #endif
6829 
6830         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
6831             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
6832             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
6833             return true;
6834         }
6835 
6836         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
6837             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
6838             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
6839             return true;
6840         }
6841 
6842         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
6843             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
6844             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
6845             return true;
6846         }
6847 
6848         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
6849             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
6850             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
6851             connection->state = SENT_DISCONNECT;
6852             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6853             return true;
6854         }
6855 
6856         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
6857             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
6858             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
6859             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
6860             return true;
6861         }
6862 
6863         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
6864             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
6865             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
6866             return true;
6867         }
6868 
6869         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
6870             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
6871             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
6872             return true;
6873         }
6874 
6875         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
6876             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6877             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
6878             return true;
6879         }
6880 
6881         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
6882             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
6883             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
6884             return true;
6885         }
6886 
6887         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
6888             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
6889             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
6890             return true;
6891         }
6892 #endif
6893 
6894         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
6895             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
6896 #ifdef ENABLE_CLASSIC
6897             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
6898 #endif
6899             if (connection->state != SENT_DISCONNECT){
6900                 connection->state = SENT_DISCONNECT;
6901                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
6902                 return true;
6903             }
6904         }
6905 
6906 #ifdef ENABLE_CLASSIC
6907         uint16_t sniff_min_interval;
6908         switch (connection->sniff_min_interval){
6909             case 0:
6910                 break;
6911             case 0xffff:
6912                 connection->sniff_min_interval = 0;
6913                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
6914                 return true;
6915             default:
6916                 sniff_min_interval = connection->sniff_min_interval;
6917                 connection->sniff_min_interval = 0;
6918                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
6919                 return true;
6920         }
6921 
6922         if (connection->sniff_subrating_max_latency != 0xffff){
6923             uint16_t max_latency = connection->sniff_subrating_max_latency;
6924             connection->sniff_subrating_max_latency = 0;
6925             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
6926             return true;
6927         }
6928 
6929         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
6930             uint8_t service_type = (uint8_t) connection->qos_service_type;
6931             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
6932             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);
6933             return true;
6934         }
6935 
6936         if (connection->request_role != HCI_ROLE_INVALID){
6937             hci_role_t role = connection->request_role;
6938             connection->request_role = HCI_ROLE_INVALID;
6939             hci_send_cmd(&hci_switch_role_command, connection->address, role);
6940             return true;
6941         }
6942 #endif
6943 
6944         if (connection->gap_connection_tasks != 0){
6945 #ifdef ENABLE_CLASSIC
6946             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
6947                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
6948                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
6949                 return true;
6950             }
6951             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
6952                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
6953                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
6954                 return true;
6955             }
6956 #endif
6957             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
6958                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
6959                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
6960                 return true;
6961             }
6962 #ifdef ENABLE_BLE
6963             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
6964                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
6965                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
6966                 return true;
6967             }
6968 #endif
6969         }
6970 
6971 #ifdef ENABLE_BLE
6972         switch (connection->le_con_parameter_update_state){
6973             // response to L2CAP CON PARAMETER UPDATE REQUEST
6974             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
6975                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6976                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
6977                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6978                              0x0000, 0xffff);
6979                 return true;
6980             case CON_PARAMETER_UPDATE_REPLY:
6981                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6982                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
6983                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6984                              0x0000, 0xffff);
6985                 return true;
6986             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
6987                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6988                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
6989                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
6990                 return true;
6991             default:
6992                 break;
6993         }
6994         if (connection->le_phy_update_all_phys != 0xffu){
6995             uint8_t all_phys = connection->le_phy_update_all_phys;
6996             connection->le_phy_update_all_phys = 0xff;
6997             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);
6998             return true;
6999         }
7000 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7001         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
7002             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
7003             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
7004             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
7005             return true;
7006         }
7007 #endif
7008 #endif
7009     }
7010     return false;
7011 }
7012 
7013 static void hci_run(void){
7014 
7015     // stack state sub statemachines
7016     switch (hci_stack->state) {
7017         case HCI_STATE_INITIALIZING:
7018             hci_initializing_run();
7019             break;
7020         case HCI_STATE_HALTING:
7021             hci_halting_run();
7022             break;
7023         case HCI_STATE_FALLING_ASLEEP:
7024             hci_falling_asleep_run();
7025             break;
7026         default:
7027             break;
7028     }
7029 
7030     // allow to run after initialization to working transition
7031     if (hci_stack->state != HCI_STATE_WORKING){
7032         return;
7033     }
7034 
7035     bool done;
7036 
7037     // send continuation fragments first, as they block the prepared packet buffer
7038     done = hci_run_acl_fragments();
7039     if (done) return;
7040 
7041 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7042     done = hci_run_iso_fragments();
7043     if (done) return;
7044 #endif
7045 
7046 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7047     // send host num completed packets next as they don't require num_cmd_packets > 0
7048     if (!hci_can_send_comand_packet_transport()) return;
7049     if (hci_stack->host_completed_packets){
7050         hci_host_num_completed_packets();
7051         return;
7052     }
7053 #endif
7054 
7055     if (!hci_can_send_command_packet_now()) return;
7056 
7057     // global/non-connection oriented commands
7058 
7059 
7060 #ifdef ENABLE_CLASSIC
7061     // general gap classic
7062     done = hci_run_general_gap_classic();
7063     if (done) return;
7064 #endif
7065 
7066 #ifdef ENABLE_BLE
7067     // general gap le
7068     done = hci_run_general_gap_le();
7069     if (done) return;
7070 
7071 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7072     // ISO related tasks, e.g. BIG create/terminate/sync
7073     done = hci_run_iso_tasks();
7074     if (done) return;
7075 #endif
7076 #endif
7077 
7078     // send pending HCI commands
7079     hci_run_general_pending_commands();
7080 }
7081 
7082 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
7083     // house-keeping
7084 
7085 #ifdef ENABLE_CLASSIC
7086     bd_addr_t addr;
7087     hci_connection_t * conn;
7088 #endif
7089 #ifdef ENABLE_LE_CENTRAL
7090     uint8_t initiator_filter_policy;
7091 #endif
7092 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7093     uint8_t i;
7094     uint8_t num_cis;
7095     hci_con_handle_t cis_handle;
7096     uint8_t status;
7097 #endif
7098 
7099     uint16_t opcode = little_endian_read_16(packet, 0);
7100     switch (opcode) {
7101         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
7102             hci_stack->loopback_mode = packet[3];
7103             break;
7104 
7105 #ifdef ENABLE_CLASSIC
7106         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7107             reverse_bd_addr(&packet[3], addr);
7108             log_info("Create_connection to %s", bd_addr_to_str(addr));
7109 
7110             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
7111             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
7112                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
7113                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
7114             }
7115 
7116             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7117             if (!conn) {
7118                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7119                 if (!conn) {
7120                     // notify client that alloc failed
7121                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7122                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
7123                 }
7124                 conn->state = SEND_CREATE_CONNECTION;
7125                 conn->role  = HCI_ROLE_MASTER;
7126             }
7127 
7128             log_info("conn state %u", conn->state);
7129             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7130             switch (conn->state) {
7131                 // if connection active exists
7132                 case OPEN:
7133                     // and OPEN, emit connection complete command
7134                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
7135                     // packet not sent to controller
7136                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7137                 case RECEIVED_DISCONNECTION_COMPLETE:
7138                     // create connection triggered in disconnect complete event, let's do it now
7139                     break;
7140                 case SEND_CREATE_CONNECTION:
7141 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
7142                     if (hci_classic_operation_active()){
7143                         return ERROR_CODE_SUCCESS;
7144                     }
7145 #endif
7146                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7147                     break;
7148                 default:
7149                     // otherwise, just ignore as it is already in the open process
7150                     // packet not sent to controller
7151                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7152             }
7153             conn->state = SENT_CREATE_CONNECTION;
7154 
7155             // track outgoing connection
7156             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
7157             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7158             break;
7159 
7160 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
7161         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
7162             // setup_synchronous_connection? Voice setting at offset 22
7163             // TODO: compare to current setting if sco connection already active
7164             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7165             break;
7166         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
7167             // accept_synchronous_connection? Voice setting at offset 18
7168             // TODO: compare to current setting if sco connection already active
7169             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7170             // track outgoing connection
7171             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7172             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
7173             break;
7174 #endif
7175 #endif
7176 
7177 #ifdef ENABLE_BLE
7178 #ifdef ENABLE_LE_CENTRAL
7179         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7180             // white list used?
7181             initiator_filter_policy = packet[7];
7182             switch (initiator_filter_policy) {
7183                 case 0:
7184                     // whitelist not used
7185                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7186                     break;
7187                 case 1:
7188                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7189                     break;
7190                 default:
7191                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7192                     break;
7193             }
7194             // track outgoing connection
7195             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
7196             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
7197             break;
7198         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
7199             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
7200             break;
7201 #endif
7202 #endif /* ENABLE_BLE */
7203         default:
7204             break;
7205     }
7206 
7207     hci_stack->num_cmd_packets--;
7208 
7209     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
7210     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7211     if (err != 0){
7212         return ERROR_CODE_HARDWARE_FAILURE;
7213     }
7214     return ERROR_CODE_SUCCESS;
7215 }
7216 
7217 // disconnect because of security block
7218 void hci_disconnect_security_block(hci_con_handle_t con_handle){
7219     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7220     if (!connection) return;
7221     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
7222 }
7223 
7224 
7225 // Configure Secure Simple Pairing
7226 
7227 #ifdef ENABLE_CLASSIC
7228 
7229 // enable will enable SSP during init
7230 void gap_ssp_set_enable(int enable){
7231     hci_stack->ssp_enable = enable;
7232 }
7233 
7234 static int hci_local_ssp_activated(void){
7235     return gap_ssp_supported() && hci_stack->ssp_enable;
7236 }
7237 
7238 // if set, BTstack will respond to io capability request using authentication requirement
7239 void gap_ssp_set_io_capability(int io_capability){
7240     hci_stack->ssp_io_capability = io_capability;
7241 }
7242 void gap_ssp_set_authentication_requirement(int authentication_requirement){
7243     hci_stack->ssp_authentication_requirement = authentication_requirement;
7244 }
7245 
7246 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
7247 void gap_ssp_set_auto_accept(int auto_accept){
7248     hci_stack->ssp_auto_accept = auto_accept;
7249 }
7250 
7251 void gap_secure_connections_enable(bool enable){
7252     hci_stack->secure_connections_enable = enable;
7253 }
7254 bool gap_secure_connections_active(void){
7255     return hci_stack->secure_connections_active;
7256 }
7257 
7258 #endif
7259 
7260 // va_list part of hci_send_cmd
7261 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
7262     if (!hci_can_send_command_packet_now()){
7263         log_error("hci_send_cmd called but cannot send packet now");
7264         return ERROR_CODE_COMMAND_DISALLOWED;
7265     }
7266 
7267     // for HCI INITIALIZATION
7268     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
7269     hci_stack->last_cmd_opcode = cmd->opcode;
7270 
7271     hci_reserve_packet_buffer();
7272     uint8_t * packet = hci_stack->hci_packet_buffer;
7273     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
7274     uint8_t status = hci_send_cmd_packet(packet, size);
7275 
7276     // release packet buffer on error or for synchronous transport implementations
7277     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7278         hci_release_packet_buffer();
7279         hci_emit_transport_packet_sent();
7280     }
7281 
7282     return status;
7283 }
7284 
7285 /**
7286  * pre: numcmds >= 0 - it's allowed to send a command to the controller
7287  */
7288 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
7289     va_list argptr;
7290     va_start(argptr, cmd);
7291     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
7292     va_end(argptr);
7293     return status;
7294 }
7295 
7296 // Create various non-HCI events.
7297 // TODO: generalize, use table similar to hci_create_command
7298 
7299 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
7300     // dump packet
7301     if (dump) {
7302         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
7303     }
7304 
7305     // dispatch to all event handlers
7306     btstack_linked_list_iterator_t it;
7307     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
7308     while (btstack_linked_list_iterator_has_next(&it)){
7309         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
7310         entry->callback(HCI_EVENT_PACKET, 0, event, size);
7311     }
7312 }
7313 
7314 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
7315     if (!hci_stack->acl_packet_handler) return;
7316     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
7317 }
7318 
7319 #ifdef ENABLE_CLASSIC
7320 static void hci_notify_if_sco_can_send_now(void){
7321     // notify SCO sender if waiting
7322     if (!hci_stack->sco_waiting_for_can_send_now) return;
7323     if (hci_can_send_sco_packet_now()){
7324         hci_stack->sco_waiting_for_can_send_now = 0;
7325         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
7326         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
7327         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
7328     }
7329 }
7330 
7331 // parsing end emitting has been merged to reduce code size
7332 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
7333     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
7334 
7335     uint8_t * eir_data;
7336     ad_context_t context;
7337     const uint8_t * name;
7338     uint8_t         name_len;
7339 
7340     if (size < 3) return;
7341 
7342     int event_type = hci_event_packet_get_type(packet);
7343     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
7344     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
7345 
7346     switch (event_type){
7347         case HCI_EVENT_INQUIRY_RESULT:
7348         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7349             if (size != (3 + (num_responses * 14))) return;
7350             break;
7351         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7352             if (size != 257) return;
7353             if (num_responses != 1) return;
7354             break;
7355         default:
7356             return;
7357     }
7358 
7359     // event[1] is set at the end
7360     int i;
7361     for (i=0; i<num_responses;i++){
7362         memset(event, 0, sizeof(event));
7363         event[0] = GAP_EVENT_INQUIRY_RESULT;
7364         uint8_t event_size = 27;    // if name is not set by EIR
7365 
7366         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
7367         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
7368         (void)memcpy(&event[9],
7369                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
7370                      3); // class of device
7371         (void)memcpy(&event[12],
7372                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
7373                      2); // clock offset
7374 
7375         switch (event_type){
7376             case HCI_EVENT_INQUIRY_RESULT:
7377                 // 14,15,16,17 = 0, size 18
7378                 break;
7379             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7380                 event[14] = 1;
7381                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7382                 // 16,17 = 0, size 18
7383                 break;
7384             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7385                 event[14] = 1;
7386                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7387                 // EIR packets only contain a single inquiry response
7388                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
7389                 name = NULL;
7390                 // Iterate over EIR data
7391                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
7392                     uint8_t data_type    = ad_iterator_get_data_type(&context);
7393                     uint8_t data_size    = ad_iterator_get_data_len(&context);
7394                     const uint8_t * data = ad_iterator_get_data(&context);
7395                     // Prefer Complete Local Name over Shortened Local Name
7396                     switch (data_type){
7397                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
7398                             if (name) continue;
7399                             /* fall through */
7400                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
7401                             name = data;
7402                             name_len = data_size;
7403                             break;
7404                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
7405                             if (data_size != 8) break;
7406                             event[16] = 1;
7407                             memcpy(&event[17], data, 8);
7408                             break;
7409                         default:
7410                             break;
7411                     }
7412                 }
7413                 if (name){
7414                     event[25] = 1;
7415                     // truncate name if needed
7416                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
7417                     event[26] = len;
7418                     (void)memcpy(&event[27], name, len);
7419                     event_size += len;
7420                 }
7421                 break;
7422             default:
7423                 return;
7424         }
7425         event[1] = event_size - 2;
7426         hci_emit_event(event, event_size, 1);
7427     }
7428 }
7429 #endif
7430 
7431 void hci_emit_state(void){
7432     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
7433     uint8_t event[3];
7434     event[0] = BTSTACK_EVENT_STATE;
7435     event[1] = sizeof(event) - 2u;
7436     event[2] = hci_stack->state;
7437     hci_emit_event(event, sizeof(event), 1);
7438 }
7439 
7440 #ifdef ENABLE_CLASSIC
7441 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
7442     uint8_t event[13];
7443     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
7444     event[1] = sizeof(event) - 2;
7445     event[2] = status;
7446     little_endian_store_16(event, 3, con_handle);
7447     reverse_bd_addr(address, &event[5]);
7448     event[11] = 1; // ACL connection
7449     event[12] = 0; // encryption disabled
7450     hci_emit_event(event, sizeof(event), 1);
7451 }
7452 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
7453     if (disable_l2cap_timeouts) return;
7454     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
7455     uint8_t event[4];
7456     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
7457     event[1] = sizeof(event) - 2;
7458     little_endian_store_16(event, 2, conn->con_handle);
7459     hci_emit_event(event, sizeof(event), 1);
7460 }
7461 #endif
7462 
7463 #ifdef ENABLE_BLE
7464 #ifdef ENABLE_LE_CENTRAL
7465 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){
7466     uint8_t event[21];
7467     event[0] = HCI_EVENT_LE_META;
7468     event[1] = sizeof(event) - 2u;
7469     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
7470     event[3] = status;
7471     little_endian_store_16(event, 4, con_handle);
7472     event[6] = 0; // TODO: role
7473     event[7] = address_type;
7474     reverse_bd_addr(address, &event[8]);
7475     little_endian_store_16(event, 14, 0); // interval
7476     little_endian_store_16(event, 16, 0); // latency
7477     little_endian_store_16(event, 18, 0); // supervision timeout
7478     event[20] = 0; // master clock accuracy
7479     hci_emit_event(event, sizeof(event), 1);
7480 }
7481 #endif
7482 #endif
7483 
7484 static void hci_emit_transport_packet_sent(void){
7485     // notify upper stack that it might be possible to send again
7486     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
7487     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
7488 }
7489 
7490 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
7491     uint8_t event[6];
7492     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
7493     event[1] = sizeof(event) - 2u;
7494     event[2] = 0; // status = OK
7495     little_endian_store_16(event, 3, con_handle);
7496     event[5] = reason;
7497     hci_emit_event(event, sizeof(event), 1);
7498 }
7499 
7500 static void hci_emit_nr_connections_changed(void){
7501     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
7502     uint8_t event[3];
7503     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
7504     event[1] = sizeof(event) - 2u;
7505     event[2] = nr_hci_connections();
7506     hci_emit_event(event, sizeof(event), 1);
7507 }
7508 
7509 static void hci_emit_hci_open_failed(void){
7510     log_info("BTSTACK_EVENT_POWERON_FAILED");
7511     uint8_t event[2];
7512     event[0] = BTSTACK_EVENT_POWERON_FAILED;
7513     event[1] = sizeof(event) - 2u;
7514     hci_emit_event(event, sizeof(event), 1);
7515 }
7516 
7517 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
7518     log_info("hci_emit_dedicated_bonding_result %u ", status);
7519     uint8_t event[9];
7520     int pos = 0;
7521     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
7522     event[pos++] = sizeof(event) - 2u;
7523     event[pos++] = status;
7524     reverse_bd_addr(address, &event[pos]);
7525     hci_emit_event(event, sizeof(event), 1);
7526 }
7527 
7528 
7529 #ifdef ENABLE_CLASSIC
7530 
7531 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
7532     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
7533     uint8_t event[5];
7534     int pos = 0;
7535     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
7536     event[pos++] = sizeof(event) - 2;
7537     little_endian_store_16(event, 2, con_handle);
7538     pos += 2;
7539     event[pos++] = level;
7540     hci_emit_event(event, sizeof(event), 1);
7541 }
7542 
7543 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
7544     if (!connection) return LEVEL_0;
7545     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
7546     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
7547     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
7548     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
7549     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
7550     // LEVEL 4 always requires 128 bit encrytion key size
7551     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
7552         security_level = LEVEL_3;
7553     }
7554     return security_level;
7555 }
7556 
7557 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
7558     uint8_t event[4];
7559     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
7560     event[1] = sizeof(event) - 2;
7561     event[2] = discoverable;
7562     event[3] = connectable;
7563     hci_emit_event(event, sizeof(event), 1);
7564 }
7565 
7566 // query if remote side supports eSCO
7567 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
7568     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7569     if (!connection) return false;
7570     return (connection->remote_supported_features[0] & 1) != 0;
7571 }
7572 
7573 static bool hci_ssp_supported(hci_connection_t * connection){
7574     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
7575     return (connection->bonding_flags & mask) == mask;
7576 }
7577 
7578 // query if remote side supports SSP
7579 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
7580     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7581     if (!connection) return false;
7582     return hci_ssp_supported(connection) ? 1 : 0;
7583 }
7584 
7585 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
7586     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
7587 }
7588 
7589 /**
7590  * Check if remote supported features query has completed
7591  */
7592 bool hci_remote_features_available(hci_con_handle_t handle){
7593     hci_connection_t * connection = hci_connection_for_handle(handle);
7594     if (!connection) return false;
7595     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
7596 }
7597 
7598 /**
7599  * Trigger remote supported features query
7600  */
7601 
7602 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
7603     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
7604         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7605     }
7606 }
7607 
7608 void hci_remote_features_query(hci_con_handle_t con_handle){
7609     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7610     if (!connection) return;
7611     hci_trigger_remote_features_for_connection(connection);
7612     hci_run();
7613 }
7614 
7615 // GAP API
7616 /**
7617  * @bbrief enable/disable bonding. default is enabled
7618  * @praram enabled
7619  */
7620 void gap_set_bondable_mode(int enable){
7621     hci_stack->bondable = enable ? 1 : 0;
7622 }
7623 /**
7624  * @brief Get bondable mode.
7625  * @return 1 if bondable
7626  */
7627 int gap_get_bondable_mode(void){
7628     return hci_stack->bondable;
7629 }
7630 
7631 /**
7632  * @brief map link keys to security levels
7633  */
7634 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
7635     switch (link_key_type){
7636         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7637             return LEVEL_4;
7638         case COMBINATION_KEY:
7639         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7640             return LEVEL_3;
7641         default:
7642             return LEVEL_2;
7643     }
7644 }
7645 
7646 /**
7647  * @brief map link keys to secure connection yes/no
7648  */
7649 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
7650     switch (link_key_type){
7651         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7652         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7653             return true;
7654         default:
7655             return false;
7656     }
7657 }
7658 
7659 /**
7660  * @brief map link keys to authenticated
7661  */
7662 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
7663     switch (link_key_type){
7664         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7665         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7666             return true;
7667         default:
7668             return false;
7669     }
7670 }
7671 
7672 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
7673     log_info("gap_mitm_protection_required_for_security_level %u", level);
7674     return level > LEVEL_2;
7675 }
7676 
7677 /**
7678  * @brief get current security level
7679  */
7680 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
7681     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7682     if (!connection) return LEVEL_0;
7683     return gap_security_level_for_connection(connection);
7684 }
7685 
7686 /**
7687  * @brief request connection to device to
7688  * @result GAP_AUTHENTICATION_RESULT
7689  */
7690 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
7691     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7692     if (!connection){
7693         hci_emit_security_level(con_handle, LEVEL_0);
7694         return;
7695     }
7696 
7697     btstack_assert(hci_is_le_connection(connection) == false);
7698 
7699     // 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)
7700     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
7701     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
7702         requested_level = LEVEL_4;
7703     }
7704 
7705     gap_security_level_t current_level = gap_security_level(con_handle);
7706     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
7707         requested_level, connection->requested_security_level, current_level);
7708 
7709     // authentication active if authentication request was sent or planned level > 0
7710     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
7711     if (authentication_active){
7712         // authentication already active
7713         if (connection->requested_security_level < requested_level){
7714             // increase requested level as new level is higher
7715             // TODO: handle re-authentication when done
7716             connection->requested_security_level = requested_level;
7717         }
7718     } else {
7719         // no request active, notify if security sufficient
7720         if (requested_level <= current_level){
7721             hci_emit_security_level(con_handle, current_level);
7722             return;
7723         }
7724 
7725         // store request
7726         connection->requested_security_level = requested_level;
7727 
7728         // start to authenticate connection
7729         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
7730 
7731         // request remote features if not already active, also trigger hci_run
7732         hci_remote_features_query(con_handle);
7733     }
7734 }
7735 
7736 /**
7737  * @brief start dedicated bonding with device. disconnect after bonding
7738  * @param device
7739  * @param request MITM protection
7740  * @result GAP_DEDICATED_BONDING_COMPLETE
7741  */
7742 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
7743 
7744     // create connection state machine
7745     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
7746 
7747     if (!connection){
7748         return BTSTACK_MEMORY_ALLOC_FAILED;
7749     }
7750 
7751     // delete linkn key
7752     gap_drop_link_key_for_bd_addr(device);
7753 
7754     // configure LEVEL_2/3, dedicated bonding
7755     connection->state = SEND_CREATE_CONNECTION;
7756     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
7757     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
7758     connection->bonding_flags = BONDING_DEDICATED;
7759 
7760     // wait for GAP Security Result and send GAP Dedicated Bonding complete
7761 
7762     // handle: connnection failure (connection complete != ok)
7763     // handle: authentication failure
7764     // handle: disconnect on done
7765 
7766     hci_run();
7767 
7768     return 0;
7769 }
7770 
7771 void gap_set_local_name(const char * local_name){
7772     hci_stack->local_name = local_name;
7773     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
7774     // also update EIR if not set by user
7775     if (hci_stack->eir_data == NULL){
7776         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7777     }
7778     hci_run();
7779 }
7780 #endif
7781 
7782 
7783 #ifdef ENABLE_BLE
7784 
7785 #ifdef ENABLE_LE_CENTRAL
7786 void gap_start_scan(void){
7787     hci_stack->le_scanning_enabled = true;
7788     hci_run();
7789 }
7790 
7791 void gap_stop_scan(void){
7792     hci_stack->le_scanning_enabled = false;
7793     hci_run();
7794 }
7795 
7796 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
7797     hci_stack->le_scan_type          = scan_type;
7798     hci_stack->le_scan_filter_policy = scanning_filter_policy;
7799     hci_stack->le_scan_interval      = scan_interval;
7800     hci_stack->le_scan_window        = scan_window;
7801     hci_stack->le_scanning_param_update = true;
7802     hci_run();
7803 }
7804 
7805 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
7806     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
7807 }
7808 
7809 void gap_set_scan_duplicate_filter(bool enabled){
7810     hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0;
7811 }
7812 
7813 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
7814     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
7815     if (!conn){
7816         // disallow if le connection is already outgoing
7817         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7818             log_error("le connection already active");
7819             return ERROR_CODE_COMMAND_DISALLOWED;
7820         }
7821 
7822         log_info("gap_connect: no connection exists yet, creating context");
7823         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
7824         if (!conn){
7825             // notify client that alloc failed
7826             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7827             log_info("gap_connect: failed to alloc hci_connection_t");
7828             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
7829         }
7830 
7831         // set le connecting state
7832         if (hci_is_le_connection_type(addr_type)){
7833             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
7834         }
7835 
7836         conn->state = SEND_CREATE_CONNECTION;
7837         log_info("gap_connect: send create connection next");
7838         hci_run();
7839         return ERROR_CODE_SUCCESS;
7840     }
7841 
7842     if (!hci_is_le_connection(conn) ||
7843         (conn->state == SEND_CREATE_CONNECTION) ||
7844         (conn->state == SENT_CREATE_CONNECTION)) {
7845         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
7846         log_error("gap_connect: classic connection or connect is already being created");
7847         return GATT_CLIENT_IN_WRONG_STATE;
7848     }
7849 
7850     // check if connection was just disconnected
7851     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7852         log_info("gap_connect: send create connection (again)");
7853         conn->state = SEND_CREATE_CONNECTION;
7854         hci_run();
7855         return ERROR_CODE_SUCCESS;
7856     }
7857 
7858     log_info("gap_connect: context exists with state %u", conn->state);
7859     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
7860     hci_run();
7861     return ERROR_CODE_SUCCESS;
7862 }
7863 
7864 // @assumption: only a single outgoing LE Connection exists
7865 static hci_connection_t * gap_get_outgoing_connection(void){
7866     btstack_linked_item_t *it;
7867     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7868         hci_connection_t * conn = (hci_connection_t *) it;
7869         if (!hci_is_le_connection(conn)) continue;
7870         switch (conn->state){
7871             case SEND_CREATE_CONNECTION:
7872             case SENT_CREATE_CONNECTION:
7873                 return conn;
7874             default:
7875                 break;
7876         };
7877     }
7878     return NULL;
7879 }
7880 
7881 uint8_t gap_connect_cancel(void){
7882     hci_connection_t * conn;
7883     switch (hci_stack->le_connecting_request){
7884         case LE_CONNECTING_IDLE:
7885             break;
7886         case LE_CONNECTING_WHITELIST:
7887             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7888             hci_run();
7889             break;
7890         case LE_CONNECTING_DIRECT:
7891             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7892             conn = gap_get_outgoing_connection();
7893             if (conn == NULL){
7894                 hci_run();
7895             } else {
7896                 switch (conn->state){
7897                     case SEND_CREATE_CONNECTION:
7898                         // skip sending create connection and emit event instead
7899                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
7900                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
7901                         btstack_memory_hci_connection_free( conn );
7902                         break;
7903                     case SENT_CREATE_CONNECTION:
7904                         // let hci_run_general_gap_le cancel outgoing connection
7905                         hci_run();
7906                         break;
7907                     default:
7908                         break;
7909                 }
7910             }
7911             break;
7912         default:
7913             btstack_unreachable();
7914             break;
7915     }
7916     return ERROR_CODE_SUCCESS;
7917 }
7918 
7919 /**
7920  * @brief Set connection parameters for outgoing connections
7921  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
7922  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
7923  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
7924  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
7925  * @param conn_latency, default: 4
7926  * @param supervision_timeout (unit: 10ms), default: 720 ms
7927  * @param min_ce_length (unit: 0.625ms), default: 10 ms
7928  * @param max_ce_length (unit: 0.625ms), default: 30 ms
7929  */
7930 
7931 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
7932     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
7933     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
7934     hci_stack->le_connection_scan_interval = conn_scan_interval;
7935     hci_stack->le_connection_scan_window = conn_scan_window;
7936     hci_stack->le_connection_interval_min = conn_interval_min;
7937     hci_stack->le_connection_interval_max = conn_interval_max;
7938     hci_stack->le_connection_latency = conn_latency;
7939     hci_stack->le_supervision_timeout = supervision_timeout;
7940     hci_stack->le_minimum_ce_length = min_ce_length;
7941     hci_stack->le_maximum_ce_length = max_ce_length;
7942 }
7943 #endif
7944 
7945 /**
7946  * @brief Updates the connection parameters for a given LE connection
7947  * @param handle
7948  * @param conn_interval_min (unit: 1.25ms)
7949  * @param conn_interval_max (unit: 1.25ms)
7950  * @param conn_latency
7951  * @param supervision_timeout (unit: 10ms)
7952  * @return 0 if ok
7953  */
7954 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7955     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7956     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7957     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7958     connection->le_conn_interval_min = conn_interval_min;
7959     connection->le_conn_interval_max = conn_interval_max;
7960     connection->le_conn_latency = conn_latency;
7961     connection->le_supervision_timeout = supervision_timeout;
7962     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
7963     hci_run();
7964     return 0;
7965 }
7966 
7967 /**
7968  * @brief Request an update of the connection parameter for a given LE connection
7969  * @param handle
7970  * @param conn_interval_min (unit: 1.25ms)
7971  * @param conn_interval_max (unit: 1.25ms)
7972  * @param conn_latency
7973  * @param supervision_timeout (unit: 10ms)
7974  * @return 0 if ok
7975  */
7976 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7977     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7978     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7979     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7980     connection->le_conn_interval_min = conn_interval_min;
7981     connection->le_conn_interval_max = conn_interval_max;
7982     connection->le_conn_latency = conn_latency;
7983     connection->le_supervision_timeout = supervision_timeout;
7984     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
7985     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
7986     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
7987     return 0;
7988 }
7989 
7990 #ifdef ENABLE_LE_PERIPHERAL
7991 
7992 /**
7993  * @brief Set Advertisement Data
7994  * @param advertising_data_length
7995  * @param advertising_data (max 31 octets)
7996  * @note data is not copied, pointer has to stay valid
7997  */
7998 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
7999     hci_stack->le_advertisements_data_len = advertising_data_length;
8000     hci_stack->le_advertisements_data = advertising_data;
8001     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8002     hci_run();
8003 }
8004 
8005 /**
8006  * @brief Set Scan Response Data
8007  * @param advertising_data_length
8008  * @param advertising_data (max 31 octets)
8009  * @note data is not copied, pointer has to stay valid
8010  */
8011 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
8012     hci_stack->le_scan_response_data_len = scan_response_data_length;
8013     hci_stack->le_scan_response_data = scan_response_data;
8014     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8015     hci_run();
8016 }
8017 
8018 /**
8019  * @brief Set Advertisement Parameters
8020  * @param adv_int_min
8021  * @param adv_int_max
8022  * @param adv_type
8023  * @param direct_address_type
8024  * @param direct_address
8025  * @param channel_map
8026  * @param filter_policy
8027  *
8028  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
8029  */
8030  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
8031     uint8_t direct_address_typ, bd_addr_t direct_address,
8032     uint8_t channel_map, uint8_t filter_policy) {
8033 
8034     hci_stack->le_advertisements_interval_min = adv_int_min;
8035     hci_stack->le_advertisements_interval_max = adv_int_max;
8036     hci_stack->le_advertisements_type = adv_type;
8037     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
8038     hci_stack->le_advertisements_channel_map = channel_map;
8039     hci_stack->le_advertisements_filter_policy = filter_policy;
8040     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
8041                  6);
8042 
8043     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8044     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
8045     hci_run();
8046  }
8047 
8048 /**
8049  * @brief Enable/Disable Advertisements
8050  * @param enabled
8051  */
8052 void gap_advertisements_enable(int enabled){
8053     if (enabled == 0){
8054         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8055     } else {
8056         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
8057     }
8058     hci_update_advertisements_enabled_for_current_roles();
8059     hci_run();
8060 }
8061 
8062 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8063 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
8064     btstack_linked_list_iterator_t it;
8065     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
8066     while (btstack_linked_list_iterator_has_next(&it)){
8067         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
8068         if ( item->advertising_handle == advertising_handle ) {
8069             return item;
8070         }
8071     }
8072     return NULL;
8073 }
8074 
8075 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
8076     // find free advertisement handle
8077     uint8_t advertisement_handle;
8078     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
8079         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
8080     }
8081     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8082     // clear
8083     memset(storage, 0, sizeof(le_advertising_set_t));
8084     // copy params
8085     storage->advertising_handle = advertisement_handle;
8086     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8087     // add to list
8088     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
8089     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
8090     *out_advertising_handle = advertisement_handle;
8091     // set tasks and start
8092     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8093     hci_run();
8094     return ERROR_CODE_SUCCESS;
8095 }
8096 
8097 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
8098     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8099     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8100     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8101     // set tasks and start
8102     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8103     hci_run();
8104     return ERROR_CODE_SUCCESS;
8105 }
8106 
8107 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
8108     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8109     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8110     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
8111     return ERROR_CODE_SUCCESS;
8112 }
8113 
8114 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
8115     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8116     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8117     memcpy(advertising_set->random_address, random_address, 6);
8118     // set tasks and start
8119     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8120     hci_run();
8121     return ERROR_CODE_SUCCESS;
8122 }
8123 
8124 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
8125     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8126     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8127     advertising_set->adv_data = advertising_data;
8128     advertising_set->adv_data_len = advertising_data_length;
8129     // set tasks and start
8130     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8131     hci_run();
8132     return ERROR_CODE_SUCCESS;
8133 }
8134 
8135 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){
8136     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8137     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8138     advertising_set->scan_data = scan_response_data;
8139     advertising_set->scan_data_len = scan_response_data_length;
8140     // set tasks and start
8141     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8142     hci_run();
8143     return ERROR_CODE_SUCCESS;
8144 }
8145 
8146 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
8147     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8148     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8149     advertising_set->enable_timeout = timeout;
8150     advertising_set->enable_max_scan_events = num_extended_advertising_events;
8151     // set tasks and start
8152     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
8153     hci_run();
8154     return ERROR_CODE_SUCCESS;
8155 }
8156 
8157 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
8158     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8159     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8160     // set tasks and start
8161     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8162     hci_run();
8163     return ERROR_CODE_SUCCESS;
8164 }
8165 
8166 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8167     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8168     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8169     // set tasks and start
8170     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8171     hci_run();
8172     return ERROR_CODE_SUCCESS;
8173 }
8174 
8175 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8176 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8177     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8178     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8179     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8180     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8181     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8182     // set tasks and start
8183     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8184     hci_run();
8185     return ERROR_CODE_SUCCESS;
8186 }
8187 
8188 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8189     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8190     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8191     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8192     return ERROR_CODE_SUCCESS;
8193 }
8194 
8195 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8196     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8197     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8198     advertising_set->periodic_data = periodic_data;
8199     advertising_set->periodic_data_len = periodic_data_length;
8200     // set tasks and start
8201     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8202     hci_run();
8203     return ERROR_CODE_SUCCESS;
8204 }
8205 
8206 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
8207     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8208     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8209     // set tasks and start
8210     advertising_set->periodic_include_adi = include_adi;
8211     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8212     hci_run();
8213     return ERROR_CODE_SUCCESS;
8214 }
8215 
8216 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
8217     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8218     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8219     // set tasks and start
8220     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8221     hci_run();
8222     return ERROR_CODE_SUCCESS;
8223 }
8224 
8225 uint8_t gap_periodic_advertising_sync_transfer_set_default_parameters(uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type){
8226     hci_stack->le_past_mode = mode;
8227     hci_stack->le_past_skip = skip;
8228     hci_stack->le_past_sync_timeout = sync_timeout;
8229     hci_stack->le_past_cte_type = cte_type;
8230     hci_stack->le_past_set_default_params = true;
8231     hci_run();
8232     return ERROR_CODE_SUCCESS;
8233 }
8234 
8235 uint8_t gap_periodic_advertising_sync_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, hci_con_handle_t sync_handle){
8236     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8237     if (hci_connection == NULL){
8238         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8239     }
8240     hci_connection->le_past_sync_handle = sync_handle;
8241     hci_connection->le_past_service_data = service_data;
8242     hci_run();
8243     return ERROR_CODE_SUCCESS;
8244 }
8245 
8246 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
8247 
8248 #endif
8249 
8250 #endif
8251 
8252 void hci_le_set_own_address_type(uint8_t own_address_type){
8253     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
8254     if (own_address_type == hci_stack->le_own_addr_type) return;
8255     hci_stack->le_own_addr_type = own_address_type;
8256 
8257 #ifdef ENABLE_LE_PERIPHERAL
8258     // update advertisement parameters, too
8259     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8260     hci_run();
8261 #endif
8262 #ifdef ENABLE_LE_CENTRAL
8263     // note: we don't update scan parameters or modify ongoing connection attempts
8264 #endif
8265 }
8266 
8267 void hci_le_random_address_set(const bd_addr_t random_address){
8268     memcpy(hci_stack->le_random_address, random_address, 6);
8269     hci_stack->le_random_address_set = true;
8270     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8271     hci_run();
8272 }
8273 
8274 #endif
8275 
8276 uint8_t gap_disconnect(hci_con_handle_t handle){
8277     hci_connection_t * conn = hci_connection_for_handle(handle);
8278     if (!conn){
8279         hci_emit_disconnection_complete(handle, 0);
8280         return 0;
8281     }
8282     // ignore if already disconnected
8283     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
8284         return 0;
8285     }
8286     conn->state = SEND_DISCONNECT;
8287     hci_run();
8288     return 0;
8289 }
8290 
8291 int gap_read_rssi(hci_con_handle_t con_handle){
8292     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8293     if (hci_connection == NULL) return 0;
8294     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
8295     hci_run();
8296     return 1;
8297 }
8298 
8299 /**
8300  * @brief Get connection type
8301  * @param con_handle
8302  * @result connection_type
8303  */
8304 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
8305     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8306     if (!conn) return GAP_CONNECTION_INVALID;
8307     switch (conn->address_type){
8308         case BD_ADDR_TYPE_LE_PUBLIC:
8309         case BD_ADDR_TYPE_LE_RANDOM:
8310             return GAP_CONNECTION_LE;
8311         case BD_ADDR_TYPE_SCO:
8312             return GAP_CONNECTION_SCO;
8313         case BD_ADDR_TYPE_ACL:
8314             return GAP_CONNECTION_ACL;
8315         default:
8316             return GAP_CONNECTION_INVALID;
8317     }
8318 }
8319 
8320 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
8321     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8322     if (!conn) return HCI_ROLE_INVALID;
8323     return (hci_role_t) conn->role;
8324 }
8325 
8326 
8327 #ifdef ENABLE_CLASSIC
8328 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
8329     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8330     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8331     conn->request_role = role;
8332     hci_run();
8333     return ERROR_CODE_SUCCESS;
8334 }
8335 #endif
8336 
8337 #ifdef ENABLE_BLE
8338 
8339 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){
8340     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8341     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8342 
8343     conn->le_phy_update_all_phys    = all_phys;
8344     conn->le_phy_update_tx_phys     = tx_phys;
8345     conn->le_phy_update_rx_phys     = rx_phys;
8346     conn->le_phy_update_phy_options = phy_options;
8347 
8348     hci_run();
8349 
8350     return 0;
8351 }
8352 
8353 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8354     // check if already in list
8355     btstack_linked_list_iterator_t it;
8356     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8357     while (btstack_linked_list_iterator_has_next(&it)) {
8358         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
8359         if (entry->address_type != address_type) {
8360             continue;
8361         }
8362         if (memcmp(entry->address, address, 6) != 0) {
8363             continue;
8364         }
8365 		// disallow if already scheduled to add
8366 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
8367 			return ERROR_CODE_COMMAND_DISALLOWED;
8368 		}
8369 		// still on controller, but scheduled to remove -> re-add
8370 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
8371 		return ERROR_CODE_SUCCESS;
8372     }
8373     // alloc and add to list
8374     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
8375     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8376     entry->address_type = address_type;
8377     (void)memcpy(entry->address, address, 6);
8378     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
8379     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
8380     return ERROR_CODE_SUCCESS;
8381 }
8382 
8383 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8384     btstack_linked_list_iterator_t it;
8385     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8386     while (btstack_linked_list_iterator_has_next(&it)){
8387         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8388         if (entry->address_type != address_type) {
8389             continue;
8390         }
8391         if (memcmp(entry->address, address, 6) != 0) {
8392             continue;
8393         }
8394         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8395             // remove from controller if already present
8396             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8397         }  else {
8398             // directly remove entry from whitelist
8399             btstack_linked_list_iterator_remove(&it);
8400             btstack_memory_whitelist_entry_free(entry);
8401         }
8402         return ERROR_CODE_SUCCESS;
8403     }
8404     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8405 }
8406 
8407 static void hci_whitelist_clear(void){
8408     btstack_linked_list_iterator_t it;
8409     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8410     while (btstack_linked_list_iterator_has_next(&it)){
8411         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8412         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8413             // remove from controller if already present
8414             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8415             continue;
8416         }
8417         // directly remove entry from whitelist
8418         btstack_linked_list_iterator_remove(&it);
8419         btstack_memory_whitelist_entry_free(entry);
8420     }
8421 }
8422 
8423 /**
8424  * @brief Clear Whitelist
8425  * @return 0 if ok
8426  */
8427 uint8_t gap_whitelist_clear(void){
8428     hci_whitelist_clear();
8429     hci_run();
8430     return ERROR_CODE_SUCCESS;
8431 }
8432 
8433 /**
8434  * @brief Add Device to Whitelist
8435  * @param address_typ
8436  * @param address
8437  * @return 0 if ok
8438  */
8439 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8440     uint8_t status = hci_whitelist_add(address_type, address);
8441     if (status){
8442         return status;
8443     }
8444     hci_run();
8445     return ERROR_CODE_SUCCESS;
8446 }
8447 
8448 /**
8449  * @brief Remove Device from Whitelist
8450  * @param address_typ
8451  * @param address
8452  * @return 0 if ok
8453  */
8454 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8455     uint8_t status = hci_whitelist_remove(address_type, address);
8456     if (status){
8457         return status;
8458     }
8459     hci_run();
8460     return ERROR_CODE_SUCCESS;
8461 }
8462 
8463 #ifdef ENABLE_LE_CENTRAL
8464 /**
8465  * @brief Connect with Whitelist
8466  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
8467  * @return - if ok
8468  */
8469 uint8_t gap_connect_with_whitelist(void){
8470     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8471         return ERROR_CODE_COMMAND_DISALLOWED;
8472     }
8473     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8474     hci_run();
8475     return ERROR_CODE_SUCCESS;
8476 }
8477 
8478 /**
8479  * @brief Auto Connection Establishment - Start Connecting to device
8480  * @param address_typ
8481  * @param address
8482  * @return 0 if ok
8483  */
8484 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
8485     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8486         return ERROR_CODE_COMMAND_DISALLOWED;
8487     }
8488 
8489     uint8_t status = hci_whitelist_add(address_type, address);
8490     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
8491         return status;
8492     }
8493 
8494     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8495 
8496     hci_run();
8497     return ERROR_CODE_SUCCESS;
8498 }
8499 
8500 /**
8501  * @brief Auto Connection Establishment - Stop Connecting to device
8502  * @param address_typ
8503  * @param address
8504  * @return 0 if ok
8505  */
8506 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
8507     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8508         return ERROR_CODE_COMMAND_DISALLOWED;
8509     }
8510 
8511     hci_whitelist_remove(address_type, address);
8512     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
8513         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8514     }
8515     hci_run();
8516     return 0;
8517 }
8518 
8519 /**
8520  * @brief Auto Connection Establishment - Stop everything
8521  * @note  Convenience function to stop all active auto connection attempts
8522  */
8523 uint8_t gap_auto_connection_stop_all(void){
8524     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
8525         return ERROR_CODE_COMMAND_DISALLOWED;
8526     }
8527     hci_whitelist_clear();
8528     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8529     hci_run();
8530     return ERROR_CODE_SUCCESS;
8531 }
8532 
8533 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
8534     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8535     if (!conn) return 0;
8536     return conn->le_connection_interval;
8537 }
8538 #endif
8539 #endif
8540 
8541 #ifdef ENABLE_CLASSIC
8542 /**
8543  * @brief Set Extended Inquiry Response data
8544  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
8545  * @note has to be done before stack starts up
8546  */
8547 void gap_set_extended_inquiry_response(const uint8_t * data){
8548     hci_stack->eir_data = data;
8549     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
8550     hci_run();
8551 }
8552 
8553 /**
8554  * @brief Start GAP Classic Inquiry
8555  * @param duration in 1.28s units
8556  * @return 0 if ok
8557  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
8558  */
8559 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
8560     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
8561     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8562     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
8563         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8564     }
8565     hci_stack->inquiry_state = duration_in_1280ms_units;
8566     hci_stack->inquiry_max_period_length = 0;
8567     hci_stack->inquiry_min_period_length = 0;
8568     hci_run();
8569     return 0;
8570 }
8571 
8572 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
8573     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
8574     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
8575     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8576     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8577     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8578     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8579 
8580     hci_stack->inquiry_state = duration;
8581     hci_stack->inquiry_max_period_length = max_period_length;
8582     hci_stack->inquiry_min_period_length = min_period_length;
8583     hci_run();
8584     return 0;
8585 }
8586 
8587 /**
8588  * @brief Stop GAP Classic Inquiry
8589  * @return 0 if ok
8590  */
8591 int gap_inquiry_stop(void){
8592     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
8593         // emit inquiry complete event, before it even started
8594         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
8595         hci_emit_event(event, sizeof(event), 1);
8596         return 0;
8597     }
8598     switch (hci_stack->inquiry_state){
8599         case GAP_INQUIRY_STATE_ACTIVE:
8600             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
8601             hci_run();
8602             return ERROR_CODE_SUCCESS;
8603         case GAP_INQUIRY_STATE_PERIODIC:
8604             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
8605             hci_run();
8606             return ERROR_CODE_SUCCESS;
8607         default:
8608             return ERROR_CODE_COMMAND_DISALLOWED;
8609     }
8610 }
8611 
8612 void gap_inquiry_set_lap(uint32_t lap){
8613     hci_stack->inquiry_lap = lap;
8614 }
8615 
8616 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
8617     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
8618     hci_stack->inquiry_scan_window   = inquiry_scan_window;
8619     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
8620     hci_run();
8621 }
8622 
8623 
8624 /**
8625  * @brief Remote Name Request
8626  * @param addr
8627  * @param page_scan_repetition_mode
8628  * @param clock_offset only used when bit 15 is set
8629  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
8630  */
8631 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
8632     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8633     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
8634     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
8635     hci_stack->remote_name_clock_offset = clock_offset;
8636     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
8637     hci_run();
8638     return 0;
8639 }
8640 
8641 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
8642     hci_stack->gap_pairing_state = state;
8643     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
8644     hci_run();
8645     return 0;
8646 }
8647 
8648 /**
8649  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
8650  * @param addr
8651  * @param pin_data
8652  * @param pin_len
8653  * @return 0 if ok
8654  */
8655 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
8656     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8657     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
8658     hci_stack->gap_pairing_pin_len = pin_len;
8659     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
8660 }
8661 
8662 /**
8663  * @brief Legacy Pairing Pin Code Response
8664  * @param addr
8665  * @param pin
8666  * @return 0 if ok
8667  */
8668 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
8669     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
8670 }
8671 
8672 /**
8673  * @brief Abort Legacy Pairing
8674  * @param addr
8675  * @param pin
8676  * @return 0 if ok
8677  */
8678 int gap_pin_code_negative(bd_addr_t addr){
8679     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8680     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
8681 }
8682 
8683 /**
8684  * @brief SSP Passkey Response
8685  * @param addr
8686  * @param passkey
8687  * @return 0 if ok
8688  */
8689 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
8690     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8691     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
8692     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
8693 }
8694 
8695 /**
8696  * @brief Abort SSP Passkey Entry/Pairing
8697  * @param addr
8698  * @param pin
8699  * @return 0 if ok
8700  */
8701 int gap_ssp_passkey_negative(const bd_addr_t addr){
8702     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8703     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
8704 }
8705 
8706 /**
8707  * @brief Accept SSP Numeric Comparison
8708  * @param addr
8709  * @param passkey
8710  * @return 0 if ok
8711  */
8712 int gap_ssp_confirmation_response(const bd_addr_t addr){
8713     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8714     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
8715 }
8716 
8717 /**
8718  * @brief Abort SSP Numeric Comparison/Pairing
8719  * @param addr
8720  * @param pin
8721  * @return 0 if ok
8722  */
8723 int gap_ssp_confirmation_negative(const bd_addr_t addr){
8724     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8725     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
8726 }
8727 
8728 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
8729 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
8730     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8731     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8732     connectionSetAuthenticationFlags(conn, flag);
8733     hci_run();
8734     return ERROR_CODE_SUCCESS;
8735 }
8736 #endif
8737 
8738 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
8739 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
8740     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
8741 }
8742 
8743 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
8744     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
8745 }
8746 #endif
8747 
8748 #ifdef ENABLE_CLASSIC_PAIRING_OOB
8749 /**
8750  * @brief Report Remote OOB Data
8751  * @param bd_addr
8752  * @param c_192 Simple Pairing Hash C derived from P-192 public key
8753  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
8754  * @param c_256 Simple Pairing Hash C derived from P-256 public key
8755  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
8756  */
8757 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){
8758     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8759     if (connection == NULL) {
8760         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8761     }
8762     connection->classic_oob_c_192 = c_192;
8763     connection->classic_oob_r_192 = r_192;
8764 
8765     // ignore P-256 if not supported by us
8766     if (hci_stack->secure_connections_active){
8767         connection->classic_oob_c_256 = c_256;
8768         connection->classic_oob_r_256 = r_256;
8769     }
8770 
8771     return ERROR_CODE_SUCCESS;
8772 }
8773 /**
8774  * @brief Generate new OOB data
8775  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
8776  */
8777 void gap_ssp_generate_oob_data(void){
8778     hci_stack->classic_read_local_oob_data = true;
8779     hci_run();
8780 }
8781 
8782 #endif
8783 
8784 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
8785 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
8786     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8787     if (connection == NULL) {
8788         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8789     }
8790 
8791     memcpy(connection->link_key, link_key, sizeof(link_key_t));
8792     connection->link_key_type = type;
8793 
8794     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
8795 }
8796 
8797 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
8798 /**
8799  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
8800  * @param inquiry_mode see bluetooth_defines.h
8801  */
8802 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
8803     hci_stack->inquiry_mode = inquiry_mode;
8804 }
8805 
8806 /**
8807  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
8808  */
8809 void hci_set_sco_voice_setting(uint16_t voice_setting){
8810     hci_stack->sco_voice_setting = voice_setting;
8811 }
8812 
8813 /**
8814  * @brief Get SCO Voice Setting
8815  * @return current voice setting
8816  */
8817 uint16_t hci_get_sco_voice_setting(void){
8818     return hci_stack->sco_voice_setting;
8819 }
8820 
8821 static int hci_have_usb_transport(void){
8822     if (!hci_stack->hci_transport) return 0;
8823     const char * transport_name = hci_stack->hci_transport->name;
8824     if (!transport_name) return 0;
8825     return (transport_name[0] == 'H') && (transport_name[1] == '2');
8826 }
8827 
8828 /** @brief Get SCO packet length for current SCO Voice setting
8829  *  @note  Using SCO packets of the exact length is required for USB transfer
8830  *  @return Length of SCO packets in bytes (not audio frames)
8831  */
8832 uint16_t hci_get_sco_packet_length(void){
8833     uint16_t sco_packet_length = 0;
8834 
8835 #ifdef ENABLE_SCO_OVER_HCI
8836     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8837     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8838 
8839     if (hci_have_usb_transport()){
8840         // see Core Spec for H2 USB Transfer.
8841         // 3 byte SCO header + 24 bytes per connection
8842         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
8843         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
8844     } else {
8845         // 3 byte SCO header + SCO packet size over the air (60 bytes)
8846         sco_packet_length = 3 + 60 * multiplier;
8847         // assert that it still fits inside an SCO buffer
8848         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
8849             sco_packet_length = 3 + 60;
8850         }
8851     }
8852 #endif
8853 
8854 #ifdef HAVE_SCO_TRANSPORT
8855     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8856     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8857     sco_packet_length = 3 + 60 * multiplier;
8858 #endif
8859     return sco_packet_length;
8860 }
8861 
8862 /**
8863 * @brief Sets the master/slave policy
8864 * @param policy (0: attempt to become master, 1: let connecting device decide)
8865 */
8866 void hci_set_master_slave_policy(uint8_t policy){
8867     hci_stack->master_slave_policy = policy;
8868 }
8869 
8870 #endif
8871 
8872 HCI_STATE hci_get_state(void){
8873     return hci_stack->state;
8874 }
8875 
8876 #ifdef ENABLE_CLASSIC
8877 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
8878     hci_stack->gap_classic_accept_callback = accept_callback;
8879 }
8880 #endif
8881 
8882 /**
8883  * @brief Set callback for Bluetooth Hardware Error
8884  */
8885 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
8886     hci_stack->hardware_error_callback = fn;
8887 }
8888 
8889 void hci_disconnect_all(void){
8890     btstack_linked_list_iterator_t it;
8891     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
8892     while (btstack_linked_list_iterator_has_next(&it)){
8893         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
8894         if (con->state == SENT_DISCONNECT) continue;
8895         con->state = SEND_DISCONNECT;
8896     }
8897     hci_run();
8898 }
8899 
8900 uint16_t hci_get_manufacturer(void){
8901     return hci_stack->manufacturer;
8902 }
8903 
8904 #ifdef ENABLE_BLE
8905 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
8906     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
8907     if (!hci_con) return NULL;
8908     return &hci_con->sm_connection;
8909 }
8910 
8911 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
8912 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
8913 #endif
8914 
8915 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
8916     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8917     if (hci_connection == NULL) return 0;
8918     if (hci_is_le_connection(hci_connection)){
8919 #ifdef ENABLE_BLE
8920         sm_connection_t * sm_conn = &hci_connection->sm_connection;
8921         if (sm_conn->sm_connection_encrypted) {
8922             return sm_conn->sm_actual_encryption_key_size;
8923         }
8924 #endif
8925     } else {
8926 #ifdef ENABLE_CLASSIC
8927         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
8928             return hci_connection->encryption_key_size;
8929         }
8930 #endif
8931     }
8932     return 0;
8933 }
8934 
8935 bool gap_authenticated(hci_con_handle_t con_handle){
8936     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8937     if (hci_connection == NULL) return false;
8938 
8939     switch (hci_connection->address_type){
8940 #ifdef ENABLE_BLE
8941         case BD_ADDR_TYPE_LE_PUBLIC:
8942         case BD_ADDR_TYPE_LE_RANDOM:
8943             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
8944             return hci_connection->sm_connection.sm_connection_authenticated != 0;
8945 #endif
8946 #ifdef ENABLE_CLASSIC
8947         case BD_ADDR_TYPE_SCO:
8948         case BD_ADDR_TYPE_ACL:
8949             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
8950 #endif
8951         default:
8952             return false;
8953     }
8954 }
8955 
8956 bool gap_secure_connection(hci_con_handle_t con_handle){
8957     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8958     if (hci_connection == NULL) return 0;
8959 
8960     switch (hci_connection->address_type){
8961 #ifdef ENABLE_BLE
8962         case BD_ADDR_TYPE_LE_PUBLIC:
8963         case BD_ADDR_TYPE_LE_RANDOM:
8964             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
8965             return hci_connection->sm_connection.sm_connection_sc != 0;
8966 #endif
8967 #ifdef ENABLE_CLASSIC
8968         case BD_ADDR_TYPE_SCO:
8969         case BD_ADDR_TYPE_ACL:
8970             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
8971 #endif
8972         default:
8973             return false;
8974     }
8975 }
8976 
8977 bool gap_bonded(hci_con_handle_t con_handle){
8978 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8979 	if (hci_connection == NULL) return 0;
8980 
8981 #ifdef ENABLE_CLASSIC
8982 	link_key_t link_key;
8983 	link_key_type_t link_key_type;
8984 #endif
8985 	switch (hci_connection->address_type){
8986 #ifdef ENABLE_BLE
8987 		case BD_ADDR_TYPE_LE_PUBLIC:
8988 		case BD_ADDR_TYPE_LE_RANDOM:
8989 			return hci_connection->sm_connection.sm_le_db_index >= 0;
8990 #endif
8991 #ifdef ENABLE_CLASSIC
8992 		case BD_ADDR_TYPE_SCO:
8993 		case BD_ADDR_TYPE_ACL:
8994 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
8995 #endif
8996 		default:
8997 			return false;
8998 	}
8999 }
9000 
9001 #ifdef ENABLE_BLE
9002 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
9003     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
9004     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
9005     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
9006     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
9007     return sm_conn->sm_connection_authorization_state;
9008 }
9009 #endif
9010 
9011 #ifdef ENABLE_CLASSIC
9012 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){
9013     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9014     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9015     conn->sniff_min_interval = sniff_min_interval;
9016     conn->sniff_max_interval = sniff_max_interval;
9017     conn->sniff_attempt = sniff_attempt;
9018     conn->sniff_timeout = sniff_timeout;
9019     hci_run();
9020     return 0;
9021 }
9022 
9023 /**
9024  * @brief Exit Sniff mode
9025  * @param con_handle
9026  @ @return 0 if ok
9027  */
9028 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
9029     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9030     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9031     conn->sniff_min_interval = 0xffff;
9032     hci_run();
9033     return 0;
9034 }
9035 
9036 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){
9037     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9038     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9039     conn->sniff_subrating_max_latency = max_latency;
9040     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
9041     conn->sniff_subrating_min_local_timeout = min_local_timeout;
9042     hci_run();
9043     return ERROR_CODE_SUCCESS;
9044 }
9045 
9046 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){
9047     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9048     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9049     conn->qos_service_type = service_type;
9050     conn->qos_token_rate = token_rate;
9051     conn->qos_peak_bandwidth = peak_bandwidth;
9052     conn->qos_latency = latency;
9053     conn->qos_delay_variation = delay_variation;
9054     hci_run();
9055     return ERROR_CODE_SUCCESS;
9056 }
9057 
9058 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
9059     hci_stack->new_page_scan_interval = page_scan_interval;
9060     hci_stack->new_page_scan_window = page_scan_window;
9061     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
9062     hci_run();
9063 }
9064 
9065 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
9066     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
9067     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
9068     hci_run();
9069 }
9070 
9071 void gap_set_page_timeout(uint16_t page_timeout){
9072     hci_stack->page_timeout = page_timeout;
9073     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
9074     hci_run();
9075 }
9076 
9077 #endif
9078 
9079 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
9080 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
9081     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9082     if (le_device_db_index >= le_device_db_max_count()) return;
9083     uint8_t offset = le_device_db_index >> 3;
9084     uint8_t mask = 1 << (le_device_db_index & 7);
9085     hci_stack->le_resolving_list_add_entries[offset] |= mask;
9086     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9087     	// note: go back to remove entries, otherwise, a remove + add will skip the add
9088         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9089     }
9090 }
9091 
9092 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
9093 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9094 	if (le_device_db_index >= le_device_db_max_count()) return;
9095 	uint8_t offset = le_device_db_index >> 3;
9096 	uint8_t mask = 1 << (le_device_db_index & 7);
9097 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
9098 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9099 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9100 	}
9101 }
9102 
9103 uint8_t gap_load_resolving_list_from_le_device_db(void){
9104     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
9105 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
9106 	}
9107 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
9108 		// restart le resolving list update
9109 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
9110 	}
9111 	return ERROR_CODE_SUCCESS;
9112 }
9113 #endif
9114 
9115 #ifdef ENABLE_BLE
9116 #ifdef ENABLE_LE_CENTRAL
9117 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
9118 
9119 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9120     // check if already in list
9121     btstack_linked_list_iterator_t it;
9122     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9123     while (btstack_linked_list_iterator_has_next(&it)) {
9124         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
9125         if (entry->sid != advertising_sid) {
9126             continue;
9127         }
9128         if (entry->address_type != address_type) {
9129             continue;
9130         }
9131         if (memcmp(entry->address, address, 6) != 0) {
9132             continue;
9133         }
9134         // disallow if already scheduled to add
9135         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
9136             return ERROR_CODE_COMMAND_DISALLOWED;
9137         }
9138         // still on controller, but scheduled to remove -> re-add
9139         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9140         return ERROR_CODE_SUCCESS;
9141     }
9142     // alloc and add to list
9143     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
9144     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9145     entry->sid = advertising_sid;
9146     entry->address_type = address_type;
9147     (void)memcpy(entry->address, address, 6);
9148     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9149     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
9150     return ERROR_CODE_SUCCESS;
9151 }
9152 
9153 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9154     btstack_linked_list_iterator_t it;
9155     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9156     while (btstack_linked_list_iterator_has_next(&it)){
9157         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9158         if (entry->sid != advertising_sid) {
9159             continue;
9160         }
9161         if (entry->address_type != address_type) {
9162             continue;
9163         }
9164         if (memcmp(entry->address, address, 6) != 0) {
9165             continue;
9166         }
9167         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9168             // remove from controller if already present
9169             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9170         }  else {
9171             // directly remove entry from whitelist
9172             btstack_linked_list_iterator_remove(&it);
9173             btstack_memory_periodic_advertiser_list_entry_free(entry);
9174         }
9175         return ERROR_CODE_SUCCESS;
9176     }
9177     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9178 }
9179 
9180 static void hci_periodic_advertiser_list_clear(void){
9181     btstack_linked_list_iterator_t it;
9182     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9183     while (btstack_linked_list_iterator_has_next(&it)){
9184         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9185         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9186             // remove from controller if already present
9187             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9188             continue;
9189         }
9190         // directly remove entry from whitelist
9191         btstack_linked_list_iterator_remove(&it);
9192         btstack_memory_periodic_advertiser_list_entry_free(entry);
9193     }
9194 }
9195 
9196 uint8_t gap_periodic_advertiser_list_clear(void){
9197     hci_periodic_advertiser_list_clear();
9198     hci_run();
9199     return ERROR_CODE_SUCCESS;
9200 }
9201 
9202 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9203     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
9204     if (status){
9205         return status;
9206     }
9207     hci_run();
9208     return ERROR_CODE_SUCCESS;
9209 }
9210 
9211 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9212     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
9213     if (status){
9214         return status;
9215     }
9216     hci_run();
9217     return ERROR_CODE_SUCCESS;
9218 }
9219 
9220 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
9221                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
9222     // abort if already active
9223     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
9224         return ERROR_CODE_COMMAND_DISALLOWED;
9225     }
9226     // store request
9227     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
9228     hci_stack->le_periodic_sync_options = options;
9229     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
9230     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
9231     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
9232     hci_stack->le_periodic_sync_skip = skip;
9233     hci_stack->le_periodic_sync_timeout = sync_timeout;
9234     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
9235 
9236     hci_run();
9237     return ERROR_CODE_SUCCESS;
9238 }
9239 
9240 uint8_t gap_periodic_advertising_create_sync_cancel(void){
9241     // abort if not requested
9242     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
9243         return ERROR_CODE_COMMAND_DISALLOWED;
9244     }
9245     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
9246     hci_run();
9247     return ERROR_CODE_SUCCESS;
9248 }
9249 
9250 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
9251     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
9252         return ERROR_CODE_COMMAND_DISALLOWED;
9253     }
9254     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
9255     hci_run();
9256     return ERROR_CODE_SUCCESS;
9257 }
9258 
9259 #endif
9260 #endif
9261 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
9262 static uint8_t hci_iso_stream_create(hci_iso_type_t iso_type, hci_con_handle_t con_handle, uint8_t group_id,
9263                                      hci_iso_stream_state_t state) {
9264     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
9265     if (iso_stream == NULL){
9266         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
9267     } else {
9268         iso_stream->iso_type = iso_type;
9269         iso_stream->state = state;
9270         iso_stream->con_handle = con_handle;
9271         iso_stream->group_id = group_id;
9272         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
9273         return ERROR_CODE_SUCCESS;
9274     }
9275 }
9276 
9277 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
9278     btstack_linked_list_iterator_t it;
9279     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9280     while (btstack_linked_list_iterator_has_next(&it)){
9281         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9282         if (iso_stream->con_handle == con_handle ) {
9283             return iso_stream;
9284         }
9285     }
9286     return NULL;
9287 }
9288 
9289 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
9290     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->con_handle, iso_stream->group_id);
9291     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
9292     btstack_memory_hci_iso_stream_free(iso_stream);
9293 }
9294 
9295 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
9296     btstack_linked_list_iterator_t it;
9297     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9298     while (btstack_linked_list_iterator_has_next(&it)){
9299         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9300         if ((iso_stream->group_id == group_id) &&
9301             (iso_stream->iso_type == iso_type)){
9302             btstack_linked_list_iterator_remove(&it);
9303             btstack_memory_hci_iso_stream_free(iso_stream);
9304         }
9305     }
9306 }
9307 
9308 static void hci_iso_stream_requested_finalize(uint8_t group_id) {
9309     btstack_linked_list_iterator_t it;
9310     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9311     while (btstack_linked_list_iterator_has_next(&it)){
9312         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9313         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
9314             (iso_stream->group_id == group_id)){
9315             btstack_linked_list_iterator_remove(&it);
9316             btstack_memory_hci_iso_stream_free(iso_stream);
9317         }
9318     }
9319 }
9320 static void hci_iso_stream_requested_confirm(uint8_t big_handle){
9321     btstack_linked_list_iterator_t it;
9322     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9323     while (btstack_linked_list_iterator_has_next(&it)){
9324         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9325         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
9326             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
9327         }
9328     }
9329 }
9330 
9331 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
9332     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
9333     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
9334     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
9335     return (sdu_len_offset + 2 + sdu_len) == size;
9336 }
9337 
9338 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){
9339     if (hci_stack->iso_packet_handler == NULL) {
9340         return;
9341     }
9342     if (size < 4) {
9343         return;
9344     }
9345 
9346     // parse header
9347     uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0);
9348     uint16_t iso_data_len = little_endian_read_16(packet, 2);
9349     hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff);
9350     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
9351     uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3;
9352 
9353     // assert packet is complete
9354     if ((iso_data_len + 4u) != size){
9355         return;
9356     }
9357 
9358     if ((pb_flag & 0x01) == 0){
9359         if (pb_flag == 0x02){
9360             // The ISO_Data_Load field contains a header and a complete SDU.
9361             if (hci_iso_sdu_complete(packet, size)) {
9362                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
9363             }
9364         } else {
9365             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
9366             if (iso_stream == NULL){
9367                 return;
9368             }
9369             if (size > HCI_ISO_PAYLOAD_SIZE){
9370                 return;
9371             }
9372             memcpy(iso_stream->reassembly_buffer, packet, size);
9373             // fix pb_flag
9374             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
9375             iso_stream->reassembly_pos = size;
9376         }
9377     } else {
9378         // iso_data_load contains continuation or last fragment of an SDU
9379         uint8_t  ts_flag = (conn_handle_and_flags >> 14) & 1;
9380         if (ts_flag != 0){
9381            return;
9382         }
9383         // append fragment
9384         if (iso_stream == NULL){
9385             return;
9386         }
9387         if (iso_stream->reassembly_pos == 0){
9388             return;
9389         }
9390         if ((iso_stream->reassembly_pos + iso_data_len) > size){
9391             // reset reassembly buffer
9392             iso_stream->reassembly_pos = 0;
9393             return;
9394         }
9395         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len);
9396         iso_stream->reassembly_pos += iso_data_len;
9397 
9398         // deliver if last fragment and SDU complete
9399         if (pb_flag == 0x03){
9400             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
9401                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
9402             }
9403             iso_stream->reassembly_pos = 0;
9404         }
9405     }
9406 }
9407 
9408 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
9409     uint8_t event [6 + (MAX_NR_BIS * 2)];
9410     uint16_t pos = 0;
9411     event[pos++] = HCI_EVENT_META_GAP;
9412     event[pos++] = 4 + (2 * big->num_bis);
9413     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
9414     event[pos++] = status;
9415     event[pos++] = big->big_handle;
9416     event[pos++] = big->num_bis;
9417     uint8_t i;
9418     for (i=0;i<big->num_bis;i++){
9419         little_endian_store_16(event, pos, big->bis_con_handles[i]);
9420         pos += 2;
9421     }
9422     hci_emit_event(event, pos, 0);
9423 }
9424 
9425 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
9426     uint8_t event [6 + (MAX_NR_CIS * 2)];
9427     uint16_t pos = 0;
9428     event[pos++] = HCI_EVENT_META_GAP;
9429     event[pos++] = 4 + (2 * cig->num_cis);
9430     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
9431     event[pos++] = status;
9432     event[pos++] = cig->cig_id;
9433     event[pos++] = cig->num_cis;
9434     uint8_t i;
9435     for (i=0;i<cig->num_cis;i++){
9436         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
9437         pos += 2;
9438     }
9439     hci_emit_event(event, pos, 0);
9440 }
9441 
9442 static void
9443 hci_emit_cis_created(uint8_t cig_id, hci_con_handle_t cis_con_handle, uint8_t status) {
9444     uint8_t event [7];
9445     uint16_t pos = 0;
9446     event[pos++] = HCI_EVENT_META_GAP;
9447     event[pos++] = 5;
9448     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
9449     event[pos++] = status;
9450     event[pos++] = cig_id;
9451     little_endian_store_16(event, pos, cis_con_handle);
9452     pos += 2;
9453     hci_emit_event(event, pos, 0);
9454 }
9455 
9456 static void hci_emit_big_terminated(const le_audio_big_t * big){
9457     uint8_t event [4];
9458     uint16_t pos = 0;
9459     event[pos++] = HCI_EVENT_META_GAP;
9460     event[pos++] = 2;
9461     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
9462     event[pos++] = big->big_handle;
9463     hci_emit_event(event, pos, 0);
9464 }
9465 
9466 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
9467     uint8_t event [6 + (MAX_NR_BIS * 2)];
9468     uint16_t pos = 0;
9469     event[pos++] = HCI_EVENT_META_GAP;
9470     event[pos++] = 4;
9471     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
9472     event[pos++] = status;
9473     event[pos++] = big_sync->big_handle;
9474     event[pos++] = big_sync->num_bis;
9475     uint8_t i;
9476     for (i=0;i<big_sync->num_bis;i++){
9477         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
9478         pos += 2;
9479     }
9480     hci_emit_event(event, pos, 0);
9481 }
9482 
9483 static void hci_emit_big_sync_stopped(uint8_t big_handle){
9484     uint8_t event [4];
9485     uint16_t pos = 0;
9486     event[pos++] = HCI_EVENT_META_GAP;
9487     event[pos++] = 2;
9488     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
9489     event[pos++] = big_handle;
9490     hci_emit_event(event, pos, 0);
9491 }
9492 
9493 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
9494     uint8_t event[6];
9495     uint16_t pos = 0;
9496     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
9497     event[pos++] = sizeof(event) - 2;
9498     event[pos++] = big->big_handle;
9499     event[pos++] = bis_index;
9500     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
9501     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
9502 }
9503 
9504 static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) {
9505     uint8_t event[4];
9506     uint16_t pos = 0;
9507     event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW;
9508     event[pos++] = sizeof(event) - 2;
9509     little_endian_store_16(event, pos, cis_con_handle);
9510     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
9511 }
9512 
9513 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
9514     btstack_linked_list_iterator_t it;
9515     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9516     while (btstack_linked_list_iterator_has_next(&it)){
9517         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9518         if ( big->big_handle == big_handle ) {
9519             return big;
9520         }
9521     }
9522     return NULL;
9523 }
9524 
9525 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
9526     btstack_linked_list_iterator_t it;
9527     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
9528     while (btstack_linked_list_iterator_has_next(&it)){
9529         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
9530         if ( big_sync->big_handle == big_handle ) {
9531             return big_sync;
9532         }
9533     }
9534     return NULL;
9535 }
9536 
9537 void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
9538     hci_stack->iso_packets_to_queue = num_packets;
9539 }
9540 
9541 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
9542     btstack_linked_list_iterator_t it;
9543     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
9544     while (btstack_linked_list_iterator_has_next(&it)){
9545         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
9546         if ( cig->cig_id == cig_id ) {
9547             return cig;
9548         }
9549     }
9550     return NULL;
9551 }
9552 
9553 static void hci_iso_notify_can_send_now(void){
9554 
9555     // BIG
9556 
9557     btstack_linked_list_iterator_t it;
9558     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9559     while (btstack_linked_list_iterator_has_next(&it)){
9560         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9561         // track number completed packet timestamps
9562         if (big->num_completed_timestamp_current_valid){
9563             big->num_completed_timestamp_current_valid = false;
9564             if (big->num_completed_timestamp_previous_valid){
9565                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
9566                 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
9567                 int32_t  num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
9568                                                                                big->num_completed_timestamp_previous_ms);
9569                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
9570                     // to catch up, skip packet on all BIS
9571                     uint8_t i;
9572                     for (i=0;i<big->num_bis;i++){
9573                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9574                         if (iso_stream){
9575                             iso_stream->num_packets_to_skip++;
9576                         }
9577                     }
9578                 }
9579             }
9580             big->num_completed_timestamp_previous_valid = true;
9581             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
9582         }
9583 
9584         if (big->can_send_now_requested){
9585             // check if no outgoing iso packets pending and no can send now have to be emitted
9586             uint8_t i;
9587             bool can_send = true;
9588             uint8_t num_iso_queued_minimum = 0;
9589             for (i=0;i<big->num_bis;i++){
9590                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9591                 if (iso_stream == NULL) continue;
9592                 // handle case where individual ISO packet was sent too late:
9593                 // for each additionally queued packet, a new one needs to get skipped
9594                 if (i==0){
9595                     num_iso_queued_minimum = iso_stream->num_packets_sent;
9596                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
9597                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
9598                     iso_stream->num_packets_to_skip += num_packets_to_skip;
9599                     iso_stream->num_packets_sent    -= num_packets_to_skip;
9600                 }
9601                 // check if we can send now
9602                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
9603                     can_send = false;
9604                     break;
9605                 }
9606             }
9607             if (can_send){
9608                 // propagate can send now to individual streams
9609                 big->can_send_now_requested = false;
9610                 for (i=0;i<big->num_bis;i++){
9611                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9612                     iso_stream->emit_ready_to_send = true;
9613                 }
9614             }
9615         }
9616     }
9617 
9618     if (hci_stack->hci_packet_buffer_reserved) return;
9619 
9620     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9621     while (btstack_linked_list_iterator_has_next(&it)){
9622         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9623         // report bis ready
9624         uint8_t i;
9625         for (i=0;i<big->num_bis;i++){
9626             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9627             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
9628                 iso_stream->emit_ready_to_send = false;
9629                 hci_emit_bis_can_send_now(big, i);
9630                 break;
9631             }
9632         }
9633     }
9634 
9635     // CIS
9636     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9637     while (btstack_linked_list_iterator_has_next(&it)) {
9638         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9639         if ((iso_stream->can_send_now_requested) &&
9640             (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){
9641             iso_stream->can_send_now_requested = false;
9642             hci_emit_cis_can_send_now(iso_stream->con_handle);
9643         }
9644     }
9645 }
9646 
9647 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
9648     if (hci_big_for_handle(big_params->big_handle) != NULL){
9649         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9650     }
9651     if (big_params->num_bis == 0){
9652         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9653     }
9654     if (big_params->num_bis > MAX_NR_BIS){
9655         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9656     }
9657 
9658     // reserve ISO Streams
9659     uint8_t i;
9660     uint8_t status = ERROR_CODE_SUCCESS;
9661     for (i=0;i<big_params->num_bis;i++){
9662         status = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_CON_HANDLE_INVALID, big_params->big_handle,
9663                                        HCI_ISO_STREAM_STATE_REQUESTED);
9664         if (status != ERROR_CODE_SUCCESS) {
9665             break;
9666         }
9667     }
9668 
9669     // free structs on error
9670     if (status != ERROR_CODE_SUCCESS){
9671         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_params->big_handle);
9672         return status;
9673     }
9674 
9675     le_audio_big_t * big = storage;
9676     big->big_handle = big_params->big_handle;
9677     big->params = big_params;
9678     big->state = LE_AUDIO_BIG_STATE_CREATE;
9679     big->num_bis = big_params->num_bis;
9680     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9681 
9682     hci_run();
9683 
9684     return ERROR_CODE_SUCCESS;
9685 }
9686 
9687 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
9688     if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){
9689         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9690     }
9691     if (big_sync_params->num_bis == 0){
9692         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9693     }
9694     if (big_sync_params->num_bis > MAX_NR_BIS){
9695         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9696     }
9697 
9698     le_audio_big_sync_t * big_sync = storage;
9699     big_sync->big_handle = big_sync_params->big_handle;
9700     big_sync->params = big_sync_params;
9701     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
9702     big_sync->num_bis = big_sync_params->num_bis;
9703     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9704 
9705     hci_run();
9706 
9707     return ERROR_CODE_SUCCESS;
9708 }
9709 
9710 uint8_t gap_big_terminate(uint8_t big_handle){
9711     le_audio_big_t * big = hci_big_for_handle(big_handle);
9712     if (big == NULL){
9713         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9714     }
9715     switch (big->state){
9716         case LE_AUDIO_BIG_STATE_CREATE:
9717             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9718             hci_emit_big_terminated(big);
9719             break;
9720         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9721             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9722             break;
9723         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9724         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9725         case LE_AUDIO_BIG_STATE_ACTIVE:
9726             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
9727             hci_run();
9728             break;
9729         default:
9730             return ERROR_CODE_COMMAND_DISALLOWED;
9731     }
9732     return ERROR_CODE_SUCCESS;
9733 }
9734 
9735 uint8_t gap_big_sync_terminate(uint8_t big_handle){
9736     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
9737     if (big_sync == NULL){
9738         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9739     }
9740     switch (big_sync->state){
9741         case LE_AUDIO_BIG_STATE_CREATE:
9742             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9743             hci_emit_big_sync_stopped(big_handle);
9744             break;
9745         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9746             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9747             break;
9748         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9749         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9750         case LE_AUDIO_BIG_STATE_ACTIVE:
9751             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
9752             hci_run();
9753             break;
9754         default:
9755             return ERROR_CODE_COMMAND_DISALLOWED;
9756     }
9757     return ERROR_CODE_SUCCESS;
9758 }
9759 
9760 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
9761     le_audio_big_t * big = hci_big_for_handle(big_handle);
9762     if (big == NULL){
9763         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9764     }
9765     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
9766         return ERROR_CODE_COMMAND_DISALLOWED;
9767     }
9768     big->can_send_now_requested = true;
9769     hci_iso_notify_can_send_now();
9770     return ERROR_CODE_SUCCESS;
9771 }
9772 
9773 uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){
9774     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
9775     if (iso_stream == NULL){
9776         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9777     }
9778     if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) {
9779         return ERROR_CODE_COMMAND_DISALLOWED;
9780     }
9781     iso_stream->can_send_now_requested = true;
9782     hci_iso_notify_can_send_now();
9783     return ERROR_CODE_SUCCESS;
9784 }
9785 
9786 uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
9787     if (hci_cig_for_id(cig_params->cig_id) != NULL){
9788         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9789     }
9790     if (cig_params->num_cis == 0){
9791         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9792     }
9793     if (cig_params->num_cis > MAX_NR_BIS){
9794         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9795     }
9796 
9797     // reserve ISO Streams
9798     uint8_t i;
9799     uint8_t status = ERROR_CODE_SUCCESS;
9800     for (i=0;i<cig_params->num_cis;i++){
9801         status = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_CON_HANDLE_INVALID, cig_params->cig_id,
9802                                        HCI_ISO_STREAM_STATE_REQUESTED);
9803         if (status != ERROR_CODE_SUCCESS) {
9804             break;
9805         }
9806     }
9807 
9808     // free structs on error
9809     if (status != ERROR_CODE_SUCCESS){
9810         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
9811         return status;
9812     }
9813 
9814     le_audio_cig_t * cig = storage;
9815     cig->cig_id = cig_params->cig_id;
9816     cig->num_cis = cig_params->num_cis;
9817     cig->params = cig_params;
9818     cig->state = LE_AUDIO_CIG_STATE_CREATE;
9819     for (i=0;i<cig->num_cis;i++){
9820         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
9821         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
9822     }
9823     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
9824 
9825     hci_run();
9826 
9827     return ERROR_CODE_SUCCESS;
9828 }
9829 
9830 uint8_t gap_cis_create(uint8_t cig_handle, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
9831     le_audio_cig_t * cig = hci_cig_for_id(cig_handle);
9832     if (cig == NULL){
9833         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9834     }
9835 
9836     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
9837         return ERROR_CODE_COMMAND_DISALLOWED;
9838     }
9839 
9840     // store ACL Connection Handles
9841     uint8_t i;
9842     for (i=0;i<cig->num_cis;i++){
9843         // check that all con handles exit
9844         hci_con_handle_t cis_handle = cis_con_handles[i];
9845         uint8_t j;
9846         bool found = false;
9847         for (j=0;j<cig->num_cis;j++){
9848             if (cig->cis_con_handles[j] == cis_handle){
9849                 cig->acl_con_handles[j] = acl_con_handles[j];
9850                 found = true;
9851                 break;
9852             }
9853         }
9854         if (!found){
9855             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9856         }
9857     }
9858 
9859     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
9860     hci_run();
9861 
9862     return ERROR_CODE_SUCCESS;
9863 }
9864 
9865 static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_con_handle, hci_iso_stream_state_t state){
9866     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
9867     if (iso_stream != NULL){
9868         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9869     }
9870 
9871     uint8_t status = hci_iso_stream_create(HCI_ISO_TYPE_CIS, cis_con_handle,
9872                                            HCI_ISO_GROUP_ID_INVALID, state);
9873     if (status == ERROR_CODE_SUCCESS){
9874         return status;
9875     }
9876 
9877     hci_run();
9878     return ERROR_CODE_SUCCESS;
9879 }
9880 
9881 uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){
9882     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT);
9883 }
9884 
9885 uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){
9886     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT);
9887 }
9888 
9889 
9890 #endif
9891 #endif /* ENABLE_BLE */
9892 
9893 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
9894 void hci_setup_test_connections_fuzz(void){
9895     hci_connection_t * conn;
9896 
9897     // default address: 66:55:44:33:00:01
9898     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
9899 
9900     // setup Controller info
9901     hci_stack->num_cmd_packets = 255;
9902     hci_stack->acl_packets_total_num = 255;
9903 
9904     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
9905     addr[5] = 0x01;
9906     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9907     conn->con_handle = addr[5];
9908     conn->role  = HCI_ROLE_SLAVE;
9909     conn->state = RECEIVED_CONNECTION_REQUEST;
9910     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9911 
9912     // setup incoming Classic SCO connection with con handle 0x0002
9913     addr[5] = 0x02;
9914     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9915     conn->con_handle = addr[5];
9916     conn->role  = HCI_ROLE_SLAVE;
9917     conn->state = RECEIVED_CONNECTION_REQUEST;
9918     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9919 
9920     // setup ready Classic ACL connection with con handle 0x0003
9921     addr[5] = 0x03;
9922     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9923     conn->con_handle = addr[5];
9924     conn->role  = HCI_ROLE_SLAVE;
9925     conn->state = OPEN;
9926     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9927 
9928     // setup ready Classic SCO connection with con handle 0x0004
9929     addr[5] = 0x04;
9930     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9931     conn->con_handle = addr[5];
9932     conn->role  = HCI_ROLE_SLAVE;
9933     conn->state = OPEN;
9934     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9935 
9936     // setup ready LE ACL connection with con handle 0x005 and public address
9937     addr[5] = 0x05;
9938     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
9939     conn->con_handle = addr[5];
9940     conn->role  = HCI_ROLE_SLAVE;
9941     conn->state = OPEN;
9942     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9943     conn->sm_connection.sm_connection_encrypted = 1;
9944 }
9945 
9946 void hci_free_connections_fuzz(void){
9947     btstack_linked_list_iterator_t it;
9948     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9949     while (btstack_linked_list_iterator_has_next(&it)){
9950         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9951         btstack_linked_list_iterator_remove(&it);
9952         btstack_memory_hci_connection_free(con);
9953     }
9954 }
9955 void hci_simulate_working_fuzz(void){
9956     hci_stack->le_scanning_param_update = false;
9957     hci_init_done();
9958     hci_stack->num_cmd_packets = 255;
9959 }
9960 #endif
9961