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