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