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