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