xref: /btstack/src/hci.c (revision f9306a1a53df338d08a2fcac69d20a498da9aeda)
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             // Lookup CIS via active group operation
2916             if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
2917                 cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
2918                 if (cig != NULL) {
2919                     // emit cis created if all ISO Paths have been created
2920                     // assume we are central
2921                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
2922                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
2923                     bool outgoing_needed = cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
2924                     // if outgoing has been setup, or incoming was setup but outgoing not required
2925                     if ((cis_direction == 1) || (outgoing_needed == false)){
2926                         hci_emit_cis_created(cig->cig_id, cig->cis_con_handles[cis_index], status);
2927                     }
2928                     // next state
2929                     cig->state_vars.next_cis++;
2930                     cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
2931                 }
2932             }
2933             break;
2934         }
2935         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
2936             // lookup BIG by state
2937             btstack_linked_list_iterator_t it;
2938             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
2939             while (btstack_linked_list_iterator_has_next(&it)) {
2940                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
2941                 uint8_t big_handle = big_sync->big_handle;
2942                 switch (big_sync->state){
2943                     case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
2944                         btstack_linked_list_iterator_remove(&it);
2945                         hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
2946                         return;
2947                     default:
2948                         btstack_linked_list_iterator_remove(&it);
2949                         hci_emit_big_sync_stopped(big_handle);
2950                         return;
2951                 }
2952             }
2953             break;
2954         }
2955 #endif
2956 #endif
2957         default:
2958             break;
2959     }
2960 }
2961 
2962 static void handle_command_status_event(uint8_t * packet, uint16_t size) {
2963     UNUSED(size);
2964 
2965     // get num cmd packets - limit to 1 to reduce complexity
2966     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2967 
2968     // get opcode and command status
2969     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
2970 
2971 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
2972     uint8_t status = hci_event_command_status_get_status(packet);
2973 #endif
2974 
2975 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
2976     bd_addr_type_t addr_type;
2977 #endif
2978 
2979     switch (opcode){
2980 #ifdef ENABLE_CLASSIC
2981         case HCI_OPCODE_HCI_CREATE_CONNECTION:
2982         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
2983 #endif
2984 #ifdef ENABLE_LE_CENTRAL
2985         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
2986 #endif
2987 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
2988             addr_type = hci_stack->outgoing_addr_type;
2989 
2990             // reset outgoing address info
2991             memset(hci_stack->outgoing_addr, 0, 6);
2992             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2993 
2994             // on error
2995             if (status != ERROR_CODE_SUCCESS){
2996 #ifdef ENABLE_LE_CENTRAL
2997                 if (hci_is_le_connection_type(addr_type)){
2998                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2999                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3000                 }
3001 #endif
3002                 // error => outgoing connection failed
3003                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
3004                 if (conn != NULL){
3005                     hci_handle_connection_failed(conn, status);
3006                 }
3007             }
3008             break;
3009 #endif
3010 #ifdef ENABLE_CLASSIC
3011         case HCI_OPCODE_HCI_INQUIRY:
3012             if (status == ERROR_CODE_SUCCESS) {
3013                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3014             } else {
3015                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3016             }
3017             break;
3018 #endif
3019 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3020         case HCI_OPCODE_HCI_LE_CREATE_CIS:
3021         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
3022             if (status == ERROR_CODE_SUCCESS){
3023                 hci_iso_stream_requested_confirm(0xff);
3024             } else {
3025                 hci_iso_stream_requested_finalize(0xff);
3026             }
3027             break;
3028 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
3029         default:
3030             break;
3031     }
3032 }
3033 
3034 #ifdef ENABLE_BLE
3035 static void event_handle_le_connection_complete(const uint8_t * packet){
3036 	bd_addr_t addr;
3037 	bd_addr_type_t addr_type;
3038 	hci_connection_t * conn;
3039 
3040 	// Connection management
3041 	reverse_bd_addr(&packet[8], addr);
3042 	addr_type = (bd_addr_type_t)packet[7];
3043 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
3044 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3045 
3046 #ifdef ENABLE_LE_CENTRAL
3047 	// handle error: error is reported only to the initiator -> outgoing connection
3048 	if (packet[3]){
3049 
3050 		// handle cancelled outgoing connection
3051 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
3052 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
3053 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
3054 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
3055 		    // reset state
3056             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
3057             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3058 			// get outgoing connection conn struct for direct connect
3059 			conn = gap_get_outgoing_connection();
3060 		}
3061 
3062 		// outgoing le connection establishment is done
3063 		if (conn){
3064 			// remove entry
3065 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3066 			btstack_memory_hci_connection_free( conn );
3067 		}
3068 		return;
3069 	}
3070 #endif
3071 
3072 	// on success, both hosts receive connection complete event
3073 	if (packet[6] == HCI_ROLE_MASTER){
3074 #ifdef ENABLE_LE_CENTRAL
3075 		// if we're master on an le connection, it was an outgoing connection and we're done with it
3076 		// note: no hci_connection_t object exists yet for connect with whitelist
3077 		if (hci_is_le_connection_type(addr_type)){
3078 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
3079 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3080 		}
3081 #endif
3082 	} else {
3083 #ifdef ENABLE_LE_PERIPHERAL
3084 		// if we're slave, it was an incoming connection, advertisements have stopped
3085         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
3086 #endif
3087 	}
3088 
3089 	// LE connections are auto-accepted, so just create a connection if there isn't one already
3090 	if (!conn){
3091 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3092 	}
3093 
3094 	// no memory, sorry.
3095 	if (!conn){
3096 		return;
3097 	}
3098 
3099 	conn->state = OPEN;
3100 	conn->role  = packet[6];
3101 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
3102 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
3103 
3104 #ifdef ENABLE_LE_PERIPHERAL
3105 	if (packet[6] == HCI_ROLE_SLAVE){
3106 		hci_update_advertisements_enabled_for_current_roles();
3107 	}
3108 #endif
3109 
3110     // init unenhanced att bearer mtu
3111     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3112     conn->att_connection.mtu_exchanged = false;
3113 
3114     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
3115 
3116 	// restart timer
3117 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3118 	// btstack_run_loop_add_timer(&conn->timeout);
3119 
3120 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3121 
3122 	hci_emit_nr_connections_changed();
3123 }
3124 #endif
3125 
3126 #ifdef ENABLE_CLASSIC
3127 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){
3128     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
3129     // LEVEL_4 is tested by l2cap
3130     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
3131     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
3132     if (level >= LEVEL_3){
3133         // MITM not possible without keyboard or display
3134         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3135         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3136 
3137         // MITM possible if one side has keyboard and the other has keyboard or display
3138         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3139         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3140 
3141         // MITM not possible if one side has only display and other side has no keyboard
3142         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3143         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3144     }
3145     // LEVEL 2 requires SSP, which is a given
3146     return true;
3147 }
3148 
3149 static bool btstack_is_null(uint8_t * data, uint16_t size){
3150     uint16_t i;
3151     for (i=0; i < size ; i++){
3152         if (data[i] != 0) {
3153             return false;
3154         }
3155     }
3156     return true;
3157 }
3158 
3159 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
3160     // get requested security level
3161     gap_security_level_t requested_security_level = conn->requested_security_level;
3162     if (hci_stack->gap_secure_connections_only_mode){
3163         requested_security_level = LEVEL_4;
3164     }
3165 
3166     // assess security: LEVEL 4 requires SC
3167     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
3168     if ((requested_security_level == LEVEL_4) &&
3169         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
3170         !hci_remote_sc_enabled(conn)){
3171         log_info("Level 4 required, but SC not supported -> abort");
3172         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3173         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3174         return;
3175     }
3176 
3177     // assess security based on io capabilities
3178     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3179         // responder: fully validate io caps of both sides as well as OOB data
3180         bool security_possible = false;
3181         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3182 
3183 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3184         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3185         // so we merge the OOB data availability
3186         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3187         if (conn->classic_oob_c_192 != NULL){
3188             have_oob_data |= 1;
3189         }
3190         if (conn->classic_oob_c_256 != NULL){
3191             have_oob_data |= 2;
3192         }
3193         // for up to Level 3, either P-192 as well as P-256 will do
3194         // 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
3195         // if remote does not SC, we should not receive P-256 data either
3196         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3197             security_possible = true;
3198         }
3199         // for Level 4, P-256 is needed
3200         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3201             security_possible = true;
3202         }
3203 #endif
3204 
3205         if (security_possible == false){
3206             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3207             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3208             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3209             return;
3210         }
3211     } else {
3212         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
3213 #ifndef ENABLE_CLASSIC_PAIRING_OOB
3214 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3215         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3216             log_info("Level 3+ required, but no input/output -> abort");
3217             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3218             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3219             return;
3220         }
3221 #endif
3222 #endif
3223     }
3224 
3225 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3226     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3227         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3228     } else {
3229         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3230     }
3231 #endif
3232 }
3233 
3234 #endif
3235 
3236 static void event_handler(uint8_t *packet, uint16_t size){
3237 
3238     uint16_t event_length = packet[1];
3239 
3240     // assert packet is complete
3241     if (size != (event_length + 2u)){
3242         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
3243         return;
3244     }
3245 
3246     hci_con_handle_t handle;
3247     hci_connection_t * conn;
3248     int i;
3249 
3250 #ifdef ENABLE_CLASSIC
3251     hci_link_type_t link_type;
3252     bd_addr_t addr;
3253     bd_addr_type_t addr_type;
3254 #endif
3255 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3256     hci_iso_stream_t * iso_stream;
3257     le_audio_big_t   * big;
3258     le_audio_big_sync_t * big_sync;
3259 #endif
3260 
3261     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
3262 
3263     switch (hci_event_packet_get_type(packet)) {
3264 
3265         case HCI_EVENT_COMMAND_COMPLETE:
3266             handle_command_complete_event(packet, size);
3267             break;
3268 
3269         case HCI_EVENT_COMMAND_STATUS:
3270             handle_command_status_event(packet, size);
3271             break;
3272 
3273         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
3274             if (size < 3) return;
3275             uint16_t num_handles = packet[2];
3276             if (size != (3u + num_handles * 4u)) return;
3277 #ifdef ENABLE_CLASSIC
3278             bool notify_sco = false;
3279 #endif
3280 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3281             bool notify_iso = false;
3282 #endif
3283             uint16_t offset = 3;
3284             for (i=0; i<num_handles;i++){
3285                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
3286                 offset += 2u;
3287                 uint16_t num_packets = little_endian_read_16(packet, offset);
3288                 offset += 2u;
3289 
3290                 conn = hci_connection_for_handle(handle);
3291                 if (conn != NULL) {
3292 
3293                     if (conn->num_packets_sent >= num_packets) {
3294                         conn->num_packets_sent -= num_packets;
3295                     } else {
3296                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3297                         conn->num_packets_sent = 0;
3298                     }
3299                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3300 #ifdef ENABLE_CLASSIC
3301                     if (conn->address_type == BD_ADDR_TYPE_SCO){
3302                         notify_sco = true;
3303                     }
3304 #endif
3305                 }
3306 
3307 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
3308                 hci_controller_dump_packets();
3309 #endif
3310 
3311 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3312                 if (conn == NULL){
3313                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle);
3314                     if (iso_stream != NULL){
3315                         if (iso_stream->num_packets_sent >= num_packets) {
3316                             iso_stream->num_packets_sent -= num_packets;
3317                         } else {
3318                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3319                             iso_stream->num_packets_sent = 0;
3320                         }
3321                         if (iso_stream->iso_type == HCI_ISO_TYPE_BIS){
3322                             le_audio_big_t * big = hci_big_for_handle(iso_stream->group_id);
3323                             if (big != NULL){
3324                                 big->num_completed_timestamp_current_valid = true;
3325                                 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms();
3326                             }
3327                         }
3328                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3329                                  num_packets, handle, iso_stream->num_packets_sent);
3330                         notify_iso = true;
3331                     }
3332                 }
3333 #endif
3334             }
3335 
3336 #ifdef ENABLE_CLASSIC
3337             if (notify_sco){
3338                 hci_notify_if_sco_can_send_now();
3339             }
3340 #endif
3341 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3342             if (notify_iso){
3343                 hci_iso_notify_can_send_now();
3344             }
3345 #endif
3346             break;
3347         }
3348 
3349 #ifdef ENABLE_CLASSIC
3350         case HCI_EVENT_FLUSH_OCCURRED:
3351             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
3352             handle = hci_event_flush_occurred_get_handle(packet);
3353             conn = hci_connection_for_handle(handle);
3354             if (conn) {
3355                 log_info("Flush occurred, disconnect 0x%04x", handle);
3356                 conn->state = SEND_DISCONNECT;
3357             }
3358             break;
3359 
3360         case HCI_EVENT_INQUIRY_COMPLETE:
3361             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3362                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3363                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
3364                 hci_emit_event(event, sizeof(event), 1);
3365             }
3366             break;
3367         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3368             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3369                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3370             }
3371             break;
3372         case HCI_EVENT_CONNECTION_REQUEST:
3373             reverse_bd_addr(&packet[2], addr);
3374             link_type = (hci_link_type_t) packet[11];
3375 
3376             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
3377             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
3378                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
3379                 bd_addr_copy(hci_stack->decline_addr, addr);
3380                 break;
3381             }
3382 
3383             if (hci_stack->gap_classic_accept_callback != NULL){
3384                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3385                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
3386                     bd_addr_copy(hci_stack->decline_addr, addr);
3387                     break;
3388                 }
3389             }
3390 
3391             // TODO: eval COD 8-10
3392             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
3393             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
3394             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3395             if (!conn) {
3396                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3397             }
3398             if (!conn) {
3399                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
3400                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3401                 bd_addr_copy(hci_stack->decline_addr, addr);
3402                 hci_run();
3403                 // avoid event to higher layer
3404                 return;
3405             }
3406             conn->role  = HCI_ROLE_SLAVE;
3407             conn->state = RECEIVED_CONNECTION_REQUEST;
3408             // store info about eSCO
3409             if (link_type == HCI_LINK_TYPE_ESCO){
3410                 conn->remote_supported_features[0] |= 1;
3411             }
3412             hci_run();
3413             break;
3414 
3415         case HCI_EVENT_CONNECTION_COMPLETE:
3416             // Connection management
3417             reverse_bd_addr(&packet[5], addr);
3418             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3419             addr_type = BD_ADDR_TYPE_ACL;
3420             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3421             if (conn) {
3422                 if (!packet[2]){
3423                     conn->state = OPEN;
3424                     conn->con_handle = little_endian_read_16(packet, 3);
3425 
3426                     // trigger write supervision timeout if we're master
3427                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
3428                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
3429                     }
3430 
3431                     // trigger write automatic flush timeout
3432                     if (hci_stack->automatic_flush_timeout != 0){
3433                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
3434                     }
3435 
3436                     // restart timer
3437                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3438                     btstack_run_loop_add_timer(&conn->timeout);
3439 
3440                     // trigger remote features for dedicated bonding
3441                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3442                         hci_trigger_remote_features_for_connection(conn);
3443                     }
3444 
3445                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3446 
3447                     hci_emit_nr_connections_changed();
3448                 } else {
3449                     // connection failed
3450                     hci_handle_connection_failed(conn, packet[2]);
3451                 }
3452             }
3453             break;
3454 
3455         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3456             reverse_bd_addr(&packet[5], addr);
3457             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3458             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3459             if (packet[2]){
3460                 // connection failed
3461                 if (conn){
3462                     hci_handle_connection_failed(conn, packet[2]);
3463                 }
3464                 break;
3465             }
3466             if (!conn) {
3467                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3468             }
3469             if (!conn) {
3470                 break;
3471             }
3472             conn->state = OPEN;
3473             conn->con_handle = little_endian_read_16(packet, 3);
3474 
3475 #ifdef ENABLE_SCO_OVER_HCI
3476             // update SCO
3477             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3478                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3479             }
3480             // trigger can send now
3481             if (hci_have_usb_transport()){
3482                 hci_stack->sco_can_send_now = true;
3483             }
3484 #endif
3485 #ifdef HAVE_SCO_TRANSPORT
3486             // configure sco transport
3487             if (hci_stack->sco_transport != NULL){
3488                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3489                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3490             }
3491 #endif
3492             break;
3493 
3494         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3495             handle = little_endian_read_16(packet, 3);
3496             conn = hci_connection_for_handle(handle);
3497             if (!conn) break;
3498             if (!packet[2]){
3499                 const uint8_t * features = &packet[5];
3500                 hci_handle_remote_features_page_0(conn, features);
3501 
3502                 // read extended features if possible
3503                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
3504                 && ((conn->remote_supported_features[0] & 2) != 0)) {
3505                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
3506                     break;
3507                 }
3508             }
3509             hci_handle_remote_features_received(conn);
3510             break;
3511 
3512         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3513             handle = little_endian_read_16(packet, 3);
3514             conn = hci_connection_for_handle(handle);
3515             if (!conn) break;
3516             // status = ok, page = 1
3517             if (!packet[2]) {
3518                 uint8_t page_number = packet[5];
3519                 uint8_t maximum_page_number = packet[6];
3520                 const uint8_t * features = &packet[7];
3521                 bool done = false;
3522                 switch (page_number){
3523                     case 1:
3524                         hci_handle_remote_features_page_1(conn, features);
3525                         if (maximum_page_number >= 2){
3526                             // get Secure Connections (Controller) from Page 2 if available
3527                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
3528                         } else {
3529                             // otherwise, assume SC (Controller) == SC (Host)
3530                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
3531                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
3532                             }
3533                             done = true;
3534                         }
3535                         break;
3536                     case 2:
3537                         hci_handle_remote_features_page_2(conn, features);
3538                         done = true;
3539                         break;
3540                     default:
3541                         break;
3542                 }
3543                 if (!done) break;
3544             }
3545             hci_handle_remote_features_received(conn);
3546             break;
3547 
3548         case HCI_EVENT_LINK_KEY_REQUEST:
3549 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
3550             hci_event_link_key_request_get_bd_addr(packet, addr);
3551             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3552             if (!conn) break;
3553 
3554             // lookup link key in db if not cached
3555             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
3556                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
3557             }
3558 
3559             // response sent by hci_run()
3560             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
3561 #endif
3562             break;
3563 
3564         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
3565             hci_event_link_key_request_get_bd_addr(packet, addr);
3566             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3567             if (!conn) break;
3568 
3569             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
3570 
3571             // CVE-2020-26555: ignore NULL link key
3572             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
3573             if (btstack_is_null(&packet[8], 16)) break;
3574 
3575             link_key_type_t link_key_type = (link_key_type_t)packet[24];
3576             // Change Connection Encryption keeps link key type
3577             if (link_key_type != CHANGED_COMBINATION_KEY){
3578                 conn->link_key_type = link_key_type;
3579             }
3580 
3581             // cache link key. link keys stored in little-endian format for legacy reasons
3582             memcpy(&conn->link_key, &packet[8], 16);
3583 
3584             // only store link key:
3585             // - if bondable enabled
3586             if (hci_stack->bondable == false) break;
3587             // - if security level sufficient
3588             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
3589             // - for SSP, also check if remote side requested bonding as well
3590             if (conn->link_key_type != COMBINATION_KEY){
3591                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3592                 if (!remote_bonding){
3593                     break;
3594                 }
3595             }
3596             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
3597             break;
3598         }
3599 
3600         case HCI_EVENT_PIN_CODE_REQUEST:
3601             hci_event_pin_code_request_get_bd_addr(packet, addr);
3602             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3603             if (!conn) break;
3604 
3605             hci_pairing_started(conn, false);
3606             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
3607             if (!hci_stack->bondable ){
3608                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3609                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3610                 hci_run();
3611                 return;
3612             }
3613             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3614             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3615                 log_info("Level 4 required, but SC not supported -> abort");
3616                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3617                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3618                 hci_run();
3619                 return;
3620             }
3621             break;
3622 
3623         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
3624             hci_event_io_capability_response_get_bd_addr(packet, addr);
3625             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3626             if (!conn) break;
3627 
3628             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
3629             hci_pairing_started(conn, true);
3630             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3631             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3632 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3633             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3634 #endif
3635             break;
3636 
3637         case HCI_EVENT_IO_CAPABILITY_REQUEST:
3638             hci_event_io_capability_response_get_bd_addr(packet, addr);
3639             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3640             if (!conn) break;
3641 
3642             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
3643             hci_connection_timestamp(conn);
3644             hci_pairing_started(conn, true);
3645             break;
3646 
3647 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3648         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
3649             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
3650             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3651             if (!conn) break;
3652 
3653             hci_connection_timestamp(conn);
3654 
3655             hci_pairing_started(conn, true);
3656 
3657             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
3658             break;
3659 #endif
3660 
3661         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
3662             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
3663             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3664             if (!conn) break;
3665             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
3666                 if (hci_stack->ssp_auto_accept){
3667                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
3668                 };
3669             } else {
3670                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3671                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
3672                 // don't forward event to app
3673                 hci_run();
3674                 return;
3675             }
3676             break;
3677 
3678         case HCI_EVENT_USER_PASSKEY_REQUEST:
3679             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
3680             if (hci_stack->ssp_auto_accept){
3681                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
3682             };
3683             break;
3684 
3685         case HCI_EVENT_MODE_CHANGE:
3686             handle = hci_event_mode_change_get_handle(packet);
3687             conn = hci_connection_for_handle(handle);
3688             if (!conn) break;
3689             conn->connection_mode = hci_event_mode_change_get_mode(packet);
3690             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
3691             break;
3692 #endif
3693 
3694         case HCI_EVENT_ENCRYPTION_CHANGE:
3695         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
3696             handle = hci_event_encryption_change_get_connection_handle(packet);
3697             conn = hci_connection_for_handle(handle);
3698             if (!conn) break;
3699             if (hci_event_encryption_change_get_status(packet) == 0u) {
3700                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
3701                 if (encryption_enabled){
3702                     if (hci_is_le_connection(conn)){
3703                         // For LE, we accept connection as encrypted
3704                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
3705                     }
3706 #ifdef ENABLE_CLASSIC
3707                     else {
3708 
3709                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
3710                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
3711                         bool connected_uses_aes_ccm = encryption_enabled == 2;
3712                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
3713                             log_info("SC during pairing, but only E0 now -> abort");
3714                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3715                             break;
3716                         }
3717 
3718                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
3719                         if (connected_uses_aes_ccm){
3720                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3721                         }
3722 
3723 #ifdef ENABLE_TESTING_SUPPORT
3724                         // work around for issue with PTS dongle
3725                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3726 #endif
3727                         // validate encryption key size
3728                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
3729                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
3730                             // already got encryption key size
3731                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
3732                         } else {
3733                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
3734                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
3735                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
3736                             } else {
3737                                 // if not, pretend everything is perfect
3738                                 hci_handle_read_encryption_key_size_complete(conn, 16);
3739                             }
3740                         }
3741                     }
3742 #endif
3743                 } else {
3744                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
3745                 }
3746             } else {
3747                 uint8_t status = hci_event_encryption_change_get_status(packet);
3748                 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3749                     conn->bonding_flags &= ~BONDING_DEDICATED;
3750                     conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
3751                     conn->bonding_status = status;
3752                 }
3753             }
3754 
3755             break;
3756 
3757 #ifdef ENABLE_CLASSIC
3758         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
3759             handle = hci_event_authentication_complete_get_connection_handle(packet);
3760             conn = hci_connection_for_handle(handle);
3761             if (!conn) break;
3762 
3763             // clear authentication active flag
3764             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
3765             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
3766 
3767             // authenticated only if auth status == 0
3768             if (hci_event_authentication_complete_get_status(packet) == 0){
3769                 // authenticated
3770                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3771 
3772                 // If not already encrypted, start encryption
3773                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
3774                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3775                     break;
3776                 }
3777             }
3778 
3779             // emit updated security level
3780             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
3781             break;
3782 
3783         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3784             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3785             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3786             if (!conn) break;
3787 
3788             // treat successfully paired connection as authenticated
3789             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
3790                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3791             }
3792 
3793             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
3794             break;
3795 #endif
3796 
3797         // HCI_EVENT_DISCONNECTION_COMPLETE
3798         // has been split, to first notify stack before shutting connection down
3799         // see end of function, too.
3800         case HCI_EVENT_DISCONNECTION_COMPLETE:
3801             if (packet[2]) break;   // status != 0
3802             handle = little_endian_read_16(packet, 3);
3803             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
3804             if (hci_stack->acl_fragmentation_total_size > 0u) {
3805                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3806                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
3807                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
3808                     hci_stack->acl_fragmentation_total_size = 0;
3809                     hci_stack->acl_fragmentation_pos = 0;
3810                     if (release_buffer){
3811                         hci_release_packet_buffer();
3812                     }
3813                 }
3814             }
3815 
3816 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3817             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
3818             if (hci_stack->iso_fragmentation_total_size > 0u) {
3819                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3820                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
3821                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
3822                     hci_stack->iso_fragmentation_total_size = 0;
3823                     hci_stack->iso_fragmentation_pos = 0;
3824                     if (release_buffer){
3825                         hci_release_packet_buffer();
3826                     }
3827                 }
3828             }
3829 
3830             // finalize iso stream if handle matches
3831             iso_stream = hci_iso_stream_for_con_handle(handle);
3832             if (iso_stream != NULL){
3833                 hci_iso_stream_finalize(iso_stream);
3834                 break;
3835             }
3836 #endif
3837 
3838             conn = hci_connection_for_handle(handle);
3839             if (!conn) break;
3840 #ifdef ENABLE_CLASSIC
3841             // pairing failed if it was ongoing
3842             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
3843 #endif
3844 
3845             // emit dedicatd bonding event
3846             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3847                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3848             }
3849 
3850             // mark connection for shutdown, stop timers, reset state
3851             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3852             hci_connection_stop_timer(conn);
3853             hci_connection_init(conn);
3854 
3855 #ifdef ENABLE_BLE
3856 #ifdef ENABLE_LE_PERIPHERAL
3857             // re-enable advertisements for le connections if active
3858             if (hci_is_le_connection(conn)){
3859                 hci_update_advertisements_enabled_for_current_roles();
3860             }
3861 #endif
3862 #endif
3863             break;
3864 
3865         case HCI_EVENT_HARDWARE_ERROR:
3866             log_error("Hardware Error: 0x%02x", packet[2]);
3867             if (hci_stack->hardware_error_callback){
3868                 (*hci_stack->hardware_error_callback)(packet[2]);
3869             } else {
3870                 // if no special requests, just reboot stack
3871                 hci_power_control_off();
3872                 hci_power_control_on();
3873             }
3874             break;
3875 
3876 #ifdef ENABLE_CLASSIC
3877         case HCI_EVENT_ROLE_CHANGE:
3878             if (packet[2]) break;   // status != 0
3879             reverse_bd_addr(&packet[3], addr);
3880             addr_type = BD_ADDR_TYPE_ACL;
3881             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3882             if (!conn) break;
3883             conn->role = packet[9];
3884             break;
3885 #endif
3886 
3887         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3888             // release packet buffer only for asynchronous transport and if there are not further fragments
3889             if (hci_transport_synchronous()) {
3890                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
3891                 return; // instead of break: to avoid re-entering hci_run()
3892             }
3893             hci_stack->acl_fragmentation_tx_active = 0;
3894 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3895             hci_stack->iso_fragmentation_tx_active = 0;
3896             if (hci_stack->iso_fragmentation_total_size) break;
3897 #endif
3898             if (hci_stack->acl_fragmentation_total_size) break;
3899             hci_release_packet_buffer();
3900 
3901 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3902             hci_iso_notify_can_send_now();
3903 #endif
3904             // L2CAP receives this event via the hci_emit_event below
3905 
3906 #ifdef ENABLE_CLASSIC
3907             // For SCO, we do the can_send_now_check here
3908             hci_notify_if_sco_can_send_now();
3909 #endif
3910             break;
3911 
3912 #ifdef ENABLE_CLASSIC
3913         case HCI_EVENT_SCO_CAN_SEND_NOW:
3914             // For SCO, we do the can_send_now_check here
3915             hci_stack->sco_can_send_now = true;
3916             hci_notify_if_sco_can_send_now();
3917             return;
3918 
3919         // explode inquriy results for easier consumption
3920         case HCI_EVENT_INQUIRY_RESULT:
3921         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3922         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3923             gap_inquiry_explode(packet, size);
3924             break;
3925 #endif
3926 
3927 #ifdef ENABLE_BLE
3928         case HCI_EVENT_LE_META:
3929             switch (packet[2]){
3930 #ifdef ENABLE_LE_CENTRAL
3931                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
3932                     if (!hci_stack->le_scanning_enabled) break;
3933                     le_handle_advertisement_report(packet, size);
3934                     break;
3935 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3936                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
3937                     if (!hci_stack->le_scanning_enabled) break;
3938                     le_handle_extended_advertisement_report(packet, size);
3939                     break;
3940                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
3941                     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
3942                     hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE;
3943                     break;
3944 #endif
3945 #endif
3946                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3947 					event_handle_le_connection_complete(packet);
3948                     break;
3949 
3950                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3951                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3952                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3953                     conn = hci_connection_for_handle(handle);
3954                     if (!conn) break;
3955                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3956                     break;
3957 
3958                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
3959                     // connection
3960                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
3961                     conn = hci_connection_for_handle(handle);
3962                     if (conn) {
3963                         // read arguments
3964                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
3965                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
3966                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
3967                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
3968 
3969                         // validate against current connection parameter range
3970                         le_connection_parameter_range_t existing_range;
3971                         gap_get_connection_parameter_range(&existing_range);
3972                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3973                         if (update_parameter){
3974                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
3975                             conn->le_conn_interval_min = le_conn_interval_min;
3976                             conn->le_conn_interval_max = le_conn_interval_max;
3977                             conn->le_conn_latency = le_conn_latency;
3978                             conn->le_supervision_timeout = le_supervision_timeout;
3979                         } else {
3980                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
3981                         }
3982                     }
3983                     break;
3984 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3985                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
3986                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
3987                     conn = hci_connection_for_handle(handle);
3988                     if (conn) {
3989                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
3990                     }
3991                     break;
3992 #endif
3993 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3994                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
3995                     handle = hci_subevent_le_cis_established_get_connection_handle(packet);
3996                     iso_stream = hci_iso_stream_for_con_handle(handle);
3997                     if (iso_stream){
3998                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
3999                         uint8_t cig_id = iso_stream->group_id;
4000                         if (status == ERROR_CODE_SUCCESS){
4001                             iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4002                         } else {
4003                             hci_iso_stream_finalize(iso_stream);
4004                         }
4005                         // CIG/CIS
4006                         if (iso_stream->iso_type == HCI_ISO_TYPE_CIS){
4007                             le_audio_cig_t * cig = hci_cig_for_id(cig_id);
4008                             if (cig){
4009                                 uint8_t i;
4010                                 for (i=0;i<cig->num_cis;i++){
4011                                     if (cig->cis_con_handles[i] == handle){
4012                                         cig->cis_setup_active[i] = false;
4013                                         if (status == ERROR_CODE_SUCCESS){
4014                                             cig->cis_established[i] = true;
4015                                         } else {
4016                                             hci_emit_cis_created(cig_id, handle, status);
4017                                         }
4018                                     }
4019                                 }
4020                                 // check if complete
4021                                 bool complete = true;
4022                                 for (i=0;i<cig->num_cis;i++){
4023                                     complete &= cig->cis_setup_active[i];
4024                                 }
4025                                 cig->state_vars.next_cis = 0;
4026                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
4027                             }
4028                         }
4029                     }
4030                     break;
4031                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
4032                     hci_stack->iso_active_operation_group_id = 0xff;
4033                     big = hci_big_for_handle(packet[4]);
4034                     if (big != NULL){
4035                         uint8_t status = packet[3];
4036                         if (status == ERROR_CODE_SUCCESS){
4037                             // store bis_con_handles and trigger iso path setup
4038                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[20]);
4039                             uint8_t i;
4040                             for (i=0;i<num_bis;i++){
4041                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4042                                 big->bis_con_handles[i] = bis_handle;
4043                                 // assign bis handle
4044                                 btstack_linked_list_iterator_t it;
4045                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4046                                 while (btstack_linked_list_iterator_has_next(&it)){
4047                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4048                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4049                                         (iso_stream->group_id == big->big_handle)){
4050                                         iso_stream->con_handle = bis_handle;
4051                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4052                                         break;
4053                                     }
4054                                 }
4055                             }
4056                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4057                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4058                                 big->state_vars.next_bis = 0;
4059                             }
4060                         } else {
4061                             // create BIG failed or has been stopped by us
4062                             hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
4063                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4064                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
4065                                 hci_emit_big_created(big, status);
4066                             } else {
4067                                 hci_emit_big_terminated(big);
4068                             }
4069                         }
4070                     }
4071                     break;
4072                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4073                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
4074                     if (big != NULL){
4075                         // finalize associated ISO streams
4076                         btstack_linked_list_iterator_t it;
4077                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4078                         while (btstack_linked_list_iterator_has_next(&it)){
4079                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4080                             if (iso_stream->group_id == big->big_handle){
4081                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->con_handle);
4082                                 btstack_linked_list_iterator_remove(&it);
4083                                 btstack_memory_hci_iso_stream_free(iso_stream);
4084                             }
4085                         }
4086                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4087                         switch (big->state){
4088                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
4089                                 hci_emit_big_created(big, big->state_vars.status);
4090                                 break;
4091                             default:
4092                                 hci_emit_big_terminated(big);
4093                                 break;
4094                         }
4095                     }
4096                     break;
4097                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4098                     big_sync = hci_big_sync_for_handle(packet[4]);
4099                     if (big_sync != NULL){
4100                         uint8_t status = packet[3];
4101                         uint8_t big_handle = packet[4];
4102                         if (status == ERROR_CODE_SUCCESS){
4103                             // store bis_con_handles and trigger iso path setup
4104                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[16]);
4105                             uint8_t i;
4106                             for (i=0;i<num_bis;i++){
4107                                 big_sync->bis_con_handles[i] = little_endian_read_16(packet, 17 + (2 * i));
4108                             }
4109                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4110                                 // trigger iso path setup
4111                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4112                                 big_sync->state_vars.next_bis = 0;
4113                             }
4114                         } else {
4115                             // create BIG Sync failed or has been stopped by us
4116                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4117                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4118                                 hci_emit_big_sync_created(big_sync, status);
4119                             } else {
4120                                 hci_emit_big_sync_stopped(big_handle);
4121                             }
4122                         }
4123                     }
4124                     break;
4125                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4126                     big_sync = hci_big_sync_for_handle(packet[4]);
4127                     if (big_sync != NULL){
4128                         uint8_t big_handle = packet[4];
4129                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4130                         hci_emit_big_sync_stopped(big_handle);
4131                     }
4132                     break;
4133 #endif
4134                 default:
4135                     break;
4136             }
4137             break;
4138 #endif
4139         case HCI_EVENT_VENDOR_SPECIFIC:
4140             // Vendor specific commands often create vendor specific event instead of num completed packets
4141             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
4142             switch (hci_stack->manufacturer){
4143                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
4144                     hci_stack->num_cmd_packets = 1;
4145                     break;
4146                 default:
4147                     break;
4148             }
4149             break;
4150         default:
4151             break;
4152     }
4153 
4154     handle_event_for_current_stack_state(packet, size);
4155 
4156     // notify upper stack
4157 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
4158 
4159     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4160     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4161 		handle = little_endian_read_16(packet, 3);
4162 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4163 		// discard connection if app did not trigger a reconnect in the event handler
4164 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
4165 			hci_shutdown_connection(aConn);
4166 		}
4167 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
4168         hci_controller_dump_packets();
4169 #endif
4170     }
4171 
4172 	// execute main loop
4173 	hci_run();
4174 }
4175 
4176 #ifdef ENABLE_CLASSIC
4177 
4178 #ifdef ENABLE_SCO_OVER_HCI
4179 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
4180 static void sco_schedule_tx(hci_connection_t * conn);
4181 
4182 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
4183     log_debug("SCO TX Timeout");
4184     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
4185     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4186     if (!conn) return;
4187 
4188     // trigger send
4189     conn->sco_tx_ready = 1;
4190     // extra packet if CVSD but SCO buffer is too short
4191     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
4192         conn->sco_tx_ready++;
4193     }
4194     hci_notify_if_sco_can_send_now();
4195 }
4196 
4197 
4198 #define SCO_TX_AFTER_RX_MS (6)
4199 
4200 static void sco_schedule_tx(hci_connection_t * conn){
4201 
4202     uint32_t now = btstack_run_loop_get_time_ms();
4203     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
4204     int time_delta_ms = sco_tx_ms - now;
4205 
4206     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
4207 
4208     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
4209     btstack_run_loop_remove_timer(timer);
4210     btstack_run_loop_set_timer(timer, time_delta_ms);
4211     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
4212     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
4213     btstack_run_loop_add_timer(timer);
4214 }
4215 #endif
4216 
4217 static void sco_handler(uint8_t * packet, uint16_t size){
4218     // lookup connection struct
4219     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
4220     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
4221     if (!conn) return;
4222 
4223 #ifdef ENABLE_SCO_OVER_HCI
4224     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4225     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4226         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4227             packet[2] = 0x3c;
4228             memmove(&packet[3], &packet[23], 63);
4229             size = 63;
4230         }
4231     }
4232 
4233     if (hci_have_usb_transport()){
4234         // Nothing to do
4235     } else {
4236         // 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);
4237         if (hci_stack->synchronous_flow_control_enabled == 0){
4238             uint32_t now = btstack_run_loop_get_time_ms();
4239 
4240             if (!conn->sco_rx_valid){
4241                 // ignore first 10 packets
4242                 conn->sco_rx_count++;
4243                 // log_debug("sco rx count %u", conn->sco_rx_count);
4244                 if (conn->sco_rx_count == 10) {
4245                     // use first timestamp as is and pretent it just started
4246                     conn->sco_rx_ms = now;
4247                     conn->sco_rx_valid = 1;
4248                     conn->sco_rx_count = 0;
4249                     sco_schedule_tx(conn);
4250                 }
4251             } else {
4252                 // track expected arrival timme
4253                 conn->sco_rx_count++;
4254                 conn->sco_rx_ms += 7;
4255                 int delta = (int32_t) (now - conn->sco_rx_ms);
4256                 if (delta > 0){
4257                     conn->sco_rx_ms++;
4258                 }
4259                 // log_debug("sco rx %u", conn->sco_rx_ms);
4260                 sco_schedule_tx(conn);
4261             }
4262         }
4263     }
4264 #endif
4265 
4266     // deliver to app
4267     if (hci_stack->sco_packet_handler) {
4268         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
4269     }
4270 
4271 #ifdef HAVE_SCO_TRANSPORT
4272     // We can send one packet for each received packet
4273     conn->sco_tx_ready++;
4274     hci_notify_if_sco_can_send_now();
4275 #endif
4276 
4277 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4278     conn->num_packets_completed++;
4279     hci_stack->host_completed_packets = 1;
4280     hci_run();
4281 #endif
4282 }
4283 #endif
4284 
4285 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
4286     hci_dump_packet(packet_type, 1, packet, size);
4287     switch (packet_type) {
4288         case HCI_EVENT_PACKET:
4289             event_handler(packet, size);
4290             break;
4291         case HCI_ACL_DATA_PACKET:
4292             acl_handler(packet, size);
4293             break;
4294 #ifdef ENABLE_CLASSIC
4295         case HCI_SCO_DATA_PACKET:
4296             sco_handler(packet, size);
4297             break;
4298 #endif
4299 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4300         case HCI_ISO_DATA_PACKET:
4301             hci_iso_packet_handler(packet, size);
4302             break;
4303 #endif
4304         default:
4305             break;
4306     }
4307 }
4308 
4309 /**
4310  * @brief Add event packet handler.
4311  */
4312 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4313     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4314 }
4315 
4316 /**
4317  * @brief Remove event packet handler.
4318  */
4319 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
4320     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4321 }
4322 
4323 /** Register HCI packet handlers */
4324 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4325     hci_stack->acl_packet_handler = handler;
4326 }
4327 
4328 #ifdef ENABLE_CLASSIC
4329 /**
4330  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
4331  */
4332 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
4333     hci_stack->sco_packet_handler = handler;
4334 }
4335 #endif
4336 
4337 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4338 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
4339     hci_stack->iso_packet_handler = handler;
4340 }
4341 #endif
4342 
4343 static void hci_state_reset(void){
4344     // no connections yet
4345     hci_stack->connections = NULL;
4346 
4347     // keep discoverable/connectable as this has been requested by the client(s)
4348     // hci_stack->discoverable = 0;
4349     // hci_stack->connectable = 0;
4350     // hci_stack->bondable = 1;
4351     // hci_stack->own_addr_type = 0;
4352 
4353     // buffer is free
4354     hci_stack->hci_packet_buffer_reserved = false;
4355 
4356     // no pending cmds
4357     hci_stack->decline_reason = 0;
4358 
4359     hci_stack->secure_connections_active = false;
4360 
4361 #ifdef ENABLE_CLASSIC
4362     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
4363     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
4364 
4365     hci_stack->gap_tasks_classic =
4366             GAP_TASK_SET_DEFAULT_LINK_POLICY |
4367             GAP_TASK_SET_CLASS_OF_DEVICE |
4368             GAP_TASK_SET_LOCAL_NAME |
4369             GAP_TASK_SET_EIR_DATA |
4370             GAP_TASK_WRITE_SCAN_ENABLE |
4371             GAP_TASK_WRITE_PAGE_TIMEOUT;
4372 #endif
4373 
4374 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4375     hci_stack->classic_read_local_oob_data = false;
4376     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4377 #endif
4378 
4379     // LE
4380 #ifdef ENABLE_BLE
4381     memset(hci_stack->le_random_address, 0, 6);
4382     hci_stack->le_random_address_set = 0;
4383 #endif
4384 #ifdef ENABLE_LE_CENTRAL
4385     hci_stack->le_scanning_active  = false;
4386     hci_stack->le_scanning_param_update = true;
4387     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4388     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4389     hci_stack->le_whitelist_capacity = 0;
4390 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4391     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
4392 #endif
4393 #endif
4394 #ifdef ENABLE_LE_PERIPHERAL
4395     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4396     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4397         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4398     }
4399     if (hci_stack->le_advertisements_data != NULL){
4400         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4401     }
4402 #endif
4403 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4404     hci_stack->iso_active_operation_group_id = 0xff;
4405 #endif
4406 }
4407 
4408 #ifdef ENABLE_CLASSIC
4409 /**
4410  * @brief Configure Bluetooth hardware control. Has to be called before power on.
4411  */
4412 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
4413     // store and open remote device db
4414     hci_stack->link_key_db = link_key_db;
4415     if (hci_stack->link_key_db) {
4416         hci_stack->link_key_db->open();
4417     }
4418 }
4419 #endif
4420 
4421 void hci_init(const hci_transport_t *transport, const void *config){
4422 
4423 #ifdef HAVE_MALLOC
4424     if (!hci_stack) {
4425         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
4426     }
4427 #else
4428     hci_stack = &hci_stack_static;
4429 #endif
4430     memset(hci_stack, 0, sizeof(hci_stack_t));
4431 
4432     // reference to use transport layer implementation
4433     hci_stack->hci_transport = transport;
4434 
4435     // reference to used config
4436     hci_stack->config = config;
4437 
4438     // setup pointer for outgoing packet buffer
4439     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
4440 
4441     // max acl payload size defined in config.h
4442     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4443 
4444     // register packet handlers with transport
4445     transport->register_packet_handler(&packet_handler);
4446 
4447     hci_stack->state = HCI_STATE_OFF;
4448 
4449     // class of device
4450     hci_stack->class_of_device = 0x007a020c; // Smartphone
4451 
4452     // bondable by default
4453     hci_stack->bondable = 1;
4454 
4455 #ifdef ENABLE_CLASSIC
4456     // classic name
4457     hci_stack->local_name = default_classic_name;
4458 
4459     // Master slave policy
4460     hci_stack->master_slave_policy = 1;
4461 
4462     // Allow Role Switch
4463     hci_stack->allow_role_switch = 1;
4464 
4465     // Default / minimum security level = 2
4466     hci_stack->gap_security_level = LEVEL_2;
4467 
4468     // Default Security Mode 4
4469     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
4470 
4471     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4472     hci_stack->gap_required_encyrption_key_size = 7;
4473 
4474     // Link Supervision Timeout
4475     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4476 
4477 #endif
4478 
4479     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
4480     hci_stack->ssp_enable = 1;
4481     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
4482     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4483     hci_stack->ssp_auto_accept = 1;
4484 
4485     // Secure Connections: enable (requires support from Controller)
4486     hci_stack->secure_connections_enable = true;
4487 
4488     // voice setting - signed 16 bit pcm data with CVSD over the air
4489     hci_stack->sco_voice_setting = 0x60;
4490 
4491 #ifdef ENABLE_LE_CENTRAL
4492     // connection parameter to use for outgoing connections
4493     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
4494     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
4495     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
4496     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
4497     hci_stack->le_connection_latency      = 4;         // 4
4498     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
4499     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
4500     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
4501 
4502     // default LE Scanning
4503     hci_stack->le_scan_type     =   0x1; // active
4504     hci_stack->le_scan_interval = 0x1e0; // 300 ms
4505     hci_stack->le_scan_window   =  0x30; //  30 ms
4506 #endif
4507 
4508 #ifdef ENABLE_LE_PERIPHERAL
4509     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4510 #endif
4511 
4512     // connection parameter range used to answer connection parameter update requests in l2cap
4513     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4514     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4515     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4516     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4517     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4518     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4519 
4520 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4521     hci_stack->iso_packets_to_queue = 1;
4522 #endif
4523 
4524     hci_state_reset();
4525 }
4526 
4527 void hci_deinit(void){
4528     btstack_run_loop_remove_timer(&hci_stack->timeout);
4529 #ifdef HAVE_MALLOC
4530     if (hci_stack) {
4531         free(hci_stack);
4532     }
4533 #endif
4534     hci_stack = NULL;
4535 
4536 #ifdef ENABLE_CLASSIC
4537     disable_l2cap_timeouts = 0;
4538 #endif
4539 }
4540 
4541 /**
4542  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
4543  */
4544 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
4545     hci_stack->chipset = chipset_driver;
4546 
4547     // reset chipset driver - init is also called on power_up
4548     if (hci_stack->chipset && hci_stack->chipset->init){
4549         hci_stack->chipset->init(hci_stack->config);
4550     }
4551 }
4552 
4553 /**
4554  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
4555  */
4556 void hci_set_control(const btstack_control_t *hardware_control){
4557     // references to used control implementation
4558     hci_stack->control = hardware_control;
4559     // init with transport config
4560     hardware_control->init(hci_stack->config);
4561 }
4562 
4563 static void hci_discard_connections(void){
4564     btstack_linked_list_iterator_t it;
4565     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4566     while (btstack_linked_list_iterator_has_next(&it)){
4567         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
4568         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4569         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
4570         hci_shutdown_connection(connection);
4571     }
4572 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4573     while (hci_stack->iso_streams != NULL){
4574         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
4575     }
4576 #endif
4577 }
4578 
4579 void hci_close(void){
4580 
4581 #ifdef ENABLE_CLASSIC
4582     // close remote device db
4583     if (hci_stack->link_key_db) {
4584         hci_stack->link_key_db->close();
4585     }
4586 #endif
4587 
4588     hci_discard_connections();
4589 
4590     hci_power_control(HCI_POWER_OFF);
4591 
4592 #ifdef HAVE_MALLOC
4593     free(hci_stack);
4594 #endif
4595     hci_stack = NULL;
4596 }
4597 
4598 #ifdef HAVE_SCO_TRANSPORT
4599 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
4600     hci_stack->sco_transport = sco_transport;
4601     sco_transport->register_packet_handler(&packet_handler);
4602 }
4603 #endif
4604 
4605 #ifdef ENABLE_CLASSIC
4606 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
4607     // validate ranage and set
4608     if (encryption_key_size < 7)  return;
4609     if (encryption_key_size > 16) return;
4610     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
4611 }
4612 
4613 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
4614     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
4615         hci_stack->gap_security_mode = security_mode;
4616         return ERROR_CODE_SUCCESS;
4617     } else {
4618         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
4619     }
4620 }
4621 
4622 gap_security_mode_t gap_get_security_mode(void){
4623     return hci_stack->gap_security_mode;
4624 }
4625 
4626 void gap_set_security_level(gap_security_level_t security_level){
4627     hci_stack->gap_security_level = security_level;
4628 }
4629 
4630 gap_security_level_t gap_get_security_level(void){
4631     if (hci_stack->gap_secure_connections_only_mode){
4632         return LEVEL_4;
4633     }
4634     return hci_stack->gap_security_level;
4635 }
4636 
4637 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
4638     hci_stack->gap_minimal_service_security_level = security_level;
4639 }
4640 
4641 void gap_set_secure_connections_only_mode(bool enable){
4642     hci_stack->gap_secure_connections_only_mode = enable;
4643 }
4644 
4645 bool gap_get_secure_connections_only_mode(void){
4646     return hci_stack->gap_secure_connections_only_mode;
4647 }
4648 #endif
4649 
4650 #ifdef ENABLE_CLASSIC
4651 void gap_set_class_of_device(uint32_t class_of_device){
4652     hci_stack->class_of_device = class_of_device;
4653     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
4654     hci_run();
4655 }
4656 
4657 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4658     hci_stack->default_link_policy_settings = default_link_policy_settings;
4659     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
4660     hci_run();
4661 }
4662 
4663 void gap_set_allow_role_switch(bool allow_role_switch){
4664     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4665 }
4666 
4667 uint8_t hci_get_allow_role_switch(void){
4668     return  hci_stack->allow_role_switch;
4669 }
4670 
4671 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
4672     hci_stack->link_supervision_timeout = link_supervision_timeout;
4673 }
4674 
4675 void gap_enable_link_watchdog(uint16_t timeout_ms){
4676     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
4677 }
4678 
4679 uint16_t hci_automatic_flush_timeout(void){
4680     return hci_stack->automatic_flush_timeout;
4681 }
4682 
4683 void hci_disable_l2cap_timeout_check(void){
4684     disable_l2cap_timeouts = 1;
4685 }
4686 #endif
4687 
4688 #ifndef HAVE_HOST_CONTROLLER_API
4689 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4690 void hci_set_bd_addr(bd_addr_t addr){
4691     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4692     hci_stack->custom_bd_addr_set = 1;
4693 }
4694 #endif
4695 
4696 // State-Module-Driver overview
4697 // state                    module  low-level
4698 // HCI_STATE_OFF             off      close
4699 // HCI_STATE_INITIALIZING,   on       open
4700 // HCI_STATE_WORKING,        on       open
4701 // HCI_STATE_HALTING,        on       open
4702 // HCI_STATE_SLEEPING,    off/sleep   close
4703 // HCI_STATE_FALLING_ASLEEP  on       open
4704 
4705 static int hci_power_control_on(void){
4706 
4707     // power on
4708     int err = 0;
4709     if (hci_stack->control && hci_stack->control->on){
4710         err = (*hci_stack->control->on)();
4711     }
4712     if (err){
4713         log_error( "POWER_ON failed");
4714         hci_emit_hci_open_failed();
4715         return err;
4716     }
4717 
4718     // int chipset driver
4719     if (hci_stack->chipset && hci_stack->chipset->init){
4720         hci_stack->chipset->init(hci_stack->config);
4721     }
4722 
4723     // init transport
4724     if (hci_stack->hci_transport->init){
4725         hci_stack->hci_transport->init(hci_stack->config);
4726     }
4727 
4728     // open transport
4729     err = hci_stack->hci_transport->open();
4730     if (err){
4731         log_error( "HCI_INIT failed, turning Bluetooth off again");
4732         if (hci_stack->control && hci_stack->control->off){
4733             (*hci_stack->control->off)();
4734         }
4735         hci_emit_hci_open_failed();
4736         return err;
4737     }
4738     return 0;
4739 }
4740 
4741 static void hci_power_control_off(void){
4742 
4743     log_info("hci_power_control_off");
4744 
4745     // close low-level device
4746     hci_stack->hci_transport->close();
4747 
4748     log_info("hci_power_control_off - hci_transport closed");
4749 
4750     // power off
4751     if (hci_stack->control && hci_stack->control->off){
4752         (*hci_stack->control->off)();
4753     }
4754 
4755     log_info("hci_power_control_off - control closed");
4756 
4757     hci_stack->state = HCI_STATE_OFF;
4758 }
4759 
4760 static void hci_power_control_sleep(void){
4761 
4762     log_info("hci_power_control_sleep");
4763 
4764 #if 0
4765     // don't close serial port during sleep
4766 
4767     // close low-level device
4768     hci_stack->hci_transport->close(hci_stack->config);
4769 #endif
4770 
4771     // sleep mode
4772     if (hci_stack->control && hci_stack->control->sleep){
4773         (*hci_stack->control->sleep)();
4774     }
4775 
4776     hci_stack->state = HCI_STATE_SLEEPING;
4777 }
4778 
4779 static int hci_power_control_wake(void){
4780 
4781     log_info("hci_power_control_wake");
4782 
4783     // wake on
4784     if (hci_stack->control && hci_stack->control->wake){
4785         (*hci_stack->control->wake)();
4786     }
4787 
4788 #if 0
4789     // open low-level device
4790     int err = hci_stack->hci_transport->open(hci_stack->config);
4791     if (err){
4792         log_error( "HCI_INIT failed, turning Bluetooth off again");
4793         if (hci_stack->control && hci_stack->control->off){
4794             (*hci_stack->control->off)();
4795         }
4796         hci_emit_hci_open_failed();
4797         return err;
4798     }
4799 #endif
4800 
4801     return 0;
4802 }
4803 
4804 static void hci_power_enter_initializing_state(void){
4805     // set up state machine
4806     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
4807     hci_stack->hci_packet_buffer_reserved = false;
4808     hci_stack->state = HCI_STATE_INITIALIZING;
4809     hci_stack->substate = HCI_INIT_SEND_RESET;
4810 }
4811 
4812 static void hci_power_enter_halting_state(void){
4813 #ifdef ENABLE_BLE
4814     hci_whitelist_free();
4815 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4816     hci_periodic_advertiser_list_free();
4817 #endif
4818 #endif
4819     // see hci_run
4820     hci_stack->state = HCI_STATE_HALTING;
4821     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
4822     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
4823     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
4824     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4825     btstack_run_loop_add_timer(&hci_stack->timeout);
4826 }
4827 
4828 // returns error
4829 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
4830     int err;
4831     switch (power_mode){
4832         case HCI_POWER_ON:
4833             err = hci_power_control_on();
4834             if (err != 0) {
4835                 log_error("hci_power_control_on() error %d", err);
4836                 return err;
4837             }
4838             hci_power_enter_initializing_state();
4839             break;
4840         case HCI_POWER_OFF:
4841             // do nothing
4842             break;
4843         case HCI_POWER_SLEEP:
4844             // do nothing (with SLEEP == OFF)
4845             break;
4846         default:
4847             btstack_assert(false);
4848             break;
4849     }
4850     return ERROR_CODE_SUCCESS;
4851 }
4852 
4853 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
4854     switch (power_mode){
4855         case HCI_POWER_ON:
4856             // do nothing
4857             break;
4858         case HCI_POWER_OFF:
4859             // no connections yet, just turn it off
4860             hci_power_control_off();
4861             break;
4862         case HCI_POWER_SLEEP:
4863             // no connections yet, just turn it off
4864             hci_power_control_sleep();
4865             break;
4866         default:
4867             btstack_assert(false);
4868             break;
4869     }
4870     return ERROR_CODE_SUCCESS;
4871 }
4872 
4873 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
4874     switch (power_mode){
4875         case HCI_POWER_ON:
4876             // do nothing
4877             break;
4878         case HCI_POWER_OFF:
4879             hci_power_enter_halting_state();
4880             break;
4881         case HCI_POWER_SLEEP:
4882             // see hci_run
4883             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4884             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4885             break;
4886         default:
4887             btstack_assert(false);
4888             break;
4889     }
4890     return ERROR_CODE_SUCCESS;
4891 }
4892 
4893 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
4894     switch (power_mode){
4895         case HCI_POWER_ON:
4896             hci_power_enter_initializing_state();
4897             break;
4898         case HCI_POWER_OFF:
4899             // do nothing
4900             break;
4901         case HCI_POWER_SLEEP:
4902             // see hci_run
4903             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4904             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4905             break;
4906         default:
4907             btstack_assert(false);
4908             break;
4909     }
4910     return ERROR_CODE_SUCCESS;
4911 }
4912 
4913 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
4914     switch (power_mode){
4915         case HCI_POWER_ON:
4916             hci_power_enter_initializing_state();
4917             break;
4918         case HCI_POWER_OFF:
4919             hci_power_enter_halting_state();
4920             break;
4921         case HCI_POWER_SLEEP:
4922             // do nothing
4923             break;
4924         default:
4925             btstack_assert(false);
4926             break;
4927     }
4928     return ERROR_CODE_SUCCESS;
4929 }
4930 
4931 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
4932     int err;
4933     switch (power_mode){
4934         case HCI_POWER_ON:
4935             err = hci_power_control_wake();
4936             if (err) return err;
4937             hci_power_enter_initializing_state();
4938             break;
4939         case HCI_POWER_OFF:
4940             hci_power_enter_halting_state();
4941             break;
4942         case HCI_POWER_SLEEP:
4943             // do nothing
4944             break;
4945         default:
4946             btstack_assert(false);
4947             break;
4948     }
4949     return ERROR_CODE_SUCCESS;
4950 }
4951 
4952 int hci_power_control(HCI_POWER_MODE power_mode){
4953     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
4954     int err = 0;
4955     switch (hci_stack->state){
4956         case HCI_STATE_OFF:
4957             err = hci_power_control_state_off(power_mode);
4958             break;
4959         case HCI_STATE_INITIALIZING:
4960             err = hci_power_control_state_initializing(power_mode);
4961             break;
4962         case HCI_STATE_WORKING:
4963             err = hci_power_control_state_working(power_mode);
4964             break;
4965         case HCI_STATE_HALTING:
4966             err = hci_power_control_state_halting(power_mode);
4967             break;
4968         case HCI_STATE_FALLING_ASLEEP:
4969             err = hci_power_control_state_falling_asleep(power_mode);
4970             break;
4971         case HCI_STATE_SLEEPING:
4972             err = hci_power_control_state_sleeping(power_mode);
4973             break;
4974         default:
4975             btstack_assert(false);
4976             break;
4977     }
4978     if (err != 0){
4979         return err;
4980     }
4981 
4982     // create internal event
4983 	hci_emit_state();
4984 
4985 	// trigger next/first action
4986 	hci_run();
4987 
4988     return 0;
4989 }
4990 
4991 
4992 static void hci_halting_run(void) {
4993 
4994     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4995 
4996     hci_connection_t *connection;
4997 #ifdef ENABLE_BLE
4998 #ifdef ENABLE_LE_PERIPHERAL
4999     bool stop_advertismenets;
5000 #endif
5001 #endif
5002 
5003     switch (hci_stack->substate) {
5004         case HCI_HALTING_CLASSIC_STOP:
5005 #ifdef ENABLE_CLASSIC
5006             if (!hci_can_send_command_packet_now()) return;
5007 
5008             if (hci_stack->connectable || hci_stack->discoverable){
5009                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5010                 hci_send_cmd(&hci_write_scan_enable, 0);
5011                 return;
5012             }
5013 #endif
5014             /* fall through */
5015 
5016         case HCI_HALTING_LE_ADV_STOP:
5017             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5018 
5019 #ifdef ENABLE_BLE
5020 #ifdef ENABLE_LE_PERIPHERAL
5021             if (!hci_can_send_command_packet_now()) return;
5022 
5023             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5024 
5025 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5026             if (hci_extended_advertising_supported()){
5027 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5028                 btstack_linked_list_iterator_t it;
5029                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5030                 // stop all periodic advertisements and check if an extended set is active
5031                 while (btstack_linked_list_iterator_has_next(&it)){
5032                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5033                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5034                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5035                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
5036                         return;
5037                     }
5038                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5039                         stop_advertismenets = true;
5040                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5041                     }
5042                 }
5043 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5044                 if (stop_advertismenets){
5045                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5046                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5047                     return;
5048                 }
5049             }
5050             else
5051 #else /* ENABLE_LE_PERIPHERAL */
5052             {
5053                 if (stop_advertismenets) {
5054                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5055                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5056                     return;
5057                 }
5058             }
5059 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5060 #endif  /* ENABLE_LE_PERIPHERAL */
5061 #endif  /* ENABLE_BLE */
5062 
5063             /* fall through */
5064 
5065         case HCI_HALTING_LE_SCAN_STOP:
5066             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5067             if (!hci_can_send_command_packet_now()) return;
5068 
5069 #ifdef ENABLE_BLE
5070 #ifdef ENABLE_LE_CENTRAL
5071             if (hci_stack->le_scanning_active){
5072                 hci_le_scan_stop();
5073                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5074                 return;
5075             }
5076 #endif
5077 #endif
5078 
5079             /* fall through */
5080 
5081         case HCI_HALTING_DISCONNECT_ALL:
5082             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5083             if (!hci_can_send_command_packet_now()) return;
5084 
5085             // close all open connections
5086             connection = (hci_connection_t *) hci_stack->connections;
5087             if (connection) {
5088                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5089 
5090                 // check state
5091                 if (connection->state == SENT_DISCONNECT) return;
5092                 connection->state = SENT_DISCONNECT;
5093 
5094                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
5095 
5096                 // finally, send the disconnect command
5097                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5098                 return;
5099             }
5100 
5101 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5102             // stop BIGs and BIG Syncs
5103             if (hci_stack->le_audio_bigs != NULL){
5104                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5105                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5106                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5107                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5108                 return;
5109             }
5110             if (hci_stack->le_audio_big_syncs != NULL){
5111                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5112                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5113                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5114                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5115                 return;
5116             }
5117 #endif
5118 
5119             btstack_run_loop_remove_timer(&hci_stack->timeout);
5120 
5121             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5122             log_info("HCI_STATE_HALTING: wait 50 ms");
5123             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5124             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5125             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5126             btstack_run_loop_add_timer(&hci_stack->timeout);
5127             break;
5128 
5129         case HCI_HALTING_CLOSE:
5130             // close left over connections (that had not been properly closed before)
5131             hci_discard_connections();
5132 
5133             log_info("HCI_STATE_HALTING, calling off");
5134 
5135             // switch mode
5136             hci_power_control_off();
5137 
5138             log_info("HCI_STATE_HALTING, emitting state");
5139             hci_emit_state();
5140             log_info("HCI_STATE_HALTING, done");
5141             break;
5142 
5143         case HCI_HALTING_W4_CLOSE_TIMER:
5144             // keep waiting
5145 
5146             break;
5147         default:
5148             break;
5149     }
5150 };
5151 
5152 static void hci_falling_asleep_run(void){
5153     hci_connection_t * connection;
5154     switch(hci_stack->substate) {
5155         case HCI_FALLING_ASLEEP_DISCONNECT:
5156             log_info("HCI_STATE_FALLING_ASLEEP");
5157             // close all open connections
5158             connection =  (hci_connection_t *) hci_stack->connections;
5159             if (connection){
5160 
5161                 // send disconnect
5162                 if (!hci_can_send_command_packet_now()) return;
5163 
5164                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5165                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5166 
5167                 // send disconnected event right away - causes higher layer connections to get closed, too.
5168                 hci_shutdown_connection(connection);
5169                 return;
5170             }
5171 
5172             if (hci_classic_supported()){
5173                 // disable page and inquiry scan
5174                 if (!hci_can_send_command_packet_now()) return;
5175 
5176                 log_info("HCI_STATE_HALTING, disabling inq scans");
5177                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5178 
5179                 // continue in next sub state
5180                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5181                 break;
5182             }
5183 
5184             /* fall through */
5185 
5186             case HCI_FALLING_ASLEEP_COMPLETE:
5187                 log_info("HCI_STATE_HALTING, calling sleep");
5188                 // switch mode
5189                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5190                 hci_emit_state();
5191                 break;
5192 
5193                 default:
5194                     break;
5195     }
5196 }
5197 
5198 #ifdef ENABLE_CLASSIC
5199 
5200 static void hci_update_scan_enable(void){
5201     // 2 = page scan, 1 = inq scan
5202     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5203     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5204     hci_run();
5205 }
5206 
5207 void gap_discoverable_control(uint8_t enable){
5208     if (enable) enable = 1; // normalize argument
5209 
5210     if (hci_stack->discoverable == enable){
5211         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5212         return;
5213     }
5214 
5215     hci_stack->discoverable = enable;
5216     hci_update_scan_enable();
5217 }
5218 
5219 void gap_connectable_control(uint8_t enable){
5220     if (enable) enable = 1; // normalize argument
5221 
5222     // don't emit event
5223     if (hci_stack->connectable == enable) return;
5224 
5225     hci_stack->connectable = enable;
5226     hci_update_scan_enable();
5227 }
5228 #endif
5229 
5230 void gap_local_bd_addr(bd_addr_t address_buffer){
5231     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5232 }
5233 
5234 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5235 static void hci_host_num_completed_packets(void){
5236 
5237     // create packet manually as arrays are not supported and num_commands should not get reduced
5238     hci_reserve_packet_buffer();
5239     uint8_t * packet = hci_get_outgoing_packet_buffer();
5240 
5241     uint16_t size = 0;
5242     uint16_t num_handles = 0;
5243     packet[size++] = 0x35;
5244     packet[size++] = 0x0c;
5245     size++;  // skip param len
5246     size++;  // skip num handles
5247 
5248     // add { handle, packets } entries
5249     btstack_linked_item_t * it;
5250     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5251         hci_connection_t * connection = (hci_connection_t *) it;
5252         if (connection->num_packets_completed){
5253             little_endian_store_16(packet, size, connection->con_handle);
5254             size += 2;
5255             little_endian_store_16(packet, size, connection->num_packets_completed);
5256             size += 2;
5257             //
5258             num_handles++;
5259             connection->num_packets_completed = 0;
5260         }
5261     }
5262 
5263     packet[2] = size - 3;
5264     packet[3] = num_handles;
5265 
5266     hci_stack->host_completed_packets = 0;
5267 
5268     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5269     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5270 
5271     // release packet buffer for synchronous transport implementations
5272     if (hci_transport_synchronous()){
5273         hci_release_packet_buffer();
5274         hci_emit_transport_packet_sent();
5275     }
5276 }
5277 #endif
5278 
5279 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5280     UNUSED(ds);
5281     hci_stack->substate = HCI_HALTING_CLOSE;
5282     // allow packet handlers to defer final shutdown
5283     hci_emit_state();
5284     hci_run();
5285 }
5286 
5287 static bool hci_run_acl_fragments(void){
5288     if (hci_stack->acl_fragmentation_total_size > 0u) {
5289         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5290         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5291         if (connection) {
5292             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5293                 hci_send_acl_packet_fragments(connection);
5294                 return true;
5295             }
5296         } else {
5297             // connection gone -> discard further fragments
5298             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5299             hci_stack->acl_fragmentation_total_size = 0;
5300             hci_stack->acl_fragmentation_pos = 0;
5301         }
5302     }
5303     return false;
5304 }
5305 
5306 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5307 static bool hci_run_iso_fragments(void){
5308     if (hci_stack->iso_fragmentation_total_size > 0u) {
5309         // TODO: flow control
5310         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5311             hci_send_iso_packet_fragments();
5312             return true;
5313         }
5314     }
5315     return false;
5316 }
5317 #endif
5318 
5319 #ifdef ENABLE_CLASSIC
5320 
5321 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5322 static bool hci_classic_operation_active(void) {
5323     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5324         return true;
5325     }
5326     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5327         return true;
5328     }
5329     btstack_linked_item_t * it;
5330     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5331         hci_connection_t *connection = (hci_connection_t *) it;
5332         switch (connection->state) {
5333             case SENT_CREATE_CONNECTION:
5334             case SENT_CANCEL_CONNECTION:
5335             case SENT_DISCONNECT:
5336                 return true;
5337             default:
5338                 break;
5339         }
5340     }
5341     return false;
5342 }
5343 #endif
5344 
5345 static bool hci_run_general_gap_classic(void){
5346 
5347     // assert stack is working and classic is active
5348     if (hci_classic_supported() == false)      return false;
5349     if (hci_stack->state != HCI_STATE_WORKING) return false;
5350 
5351     // decline incoming connections
5352     if (hci_stack->decline_reason){
5353         uint8_t reason = hci_stack->decline_reason;
5354         hci_stack->decline_reason = 0;
5355         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5356         return true;
5357     }
5358 
5359     if (hci_stack->gap_tasks_classic != 0){
5360         hci_run_gap_tasks_classic();
5361         return true;
5362     }
5363 
5364     // start/stop inquiry
5365     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5366 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5367         if (hci_classic_operation_active() == false)
5368 #endif
5369         {
5370             uint8_t duration = hci_stack->inquiry_state;
5371             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5372             if (hci_stack->inquiry_max_period_length != 0){
5373                 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);
5374             } else {
5375                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5376             }
5377             return true;
5378         }
5379     }
5380     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5381         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5382         hci_send_cmd(&hci_inquiry_cancel);
5383         return true;
5384     }
5385 
5386     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5387         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5388         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5389         return true;
5390     }
5391 
5392     // remote name request
5393     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5394 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5395         if (hci_classic_operation_active() == false)
5396 #endif
5397         {
5398             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5399             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5400                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5401             return true;
5402         }
5403     }
5404 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5405     // Local OOB data
5406     if (hci_stack->classic_read_local_oob_data){
5407         hci_stack->classic_read_local_oob_data = false;
5408         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5409             hci_send_cmd(&hci_read_local_extended_oob_data);
5410         } else {
5411             hci_send_cmd(&hci_read_local_oob_data);
5412         }
5413     }
5414 #endif
5415     // pairing
5416     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5417         uint8_t state = hci_stack->gap_pairing_state;
5418         uint8_t pin_code[16];
5419         switch (state){
5420             case GAP_PAIRING_STATE_SEND_PIN:
5421                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5422                 memset(pin_code, 0, 16);
5423                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5424                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5425                 break;
5426             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5427                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5428                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5429                 break;
5430             case GAP_PAIRING_STATE_SEND_PASSKEY:
5431                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5432                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5433                 break;
5434             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5435                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5436                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5437                 break;
5438             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5439                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5440                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5441                 break;
5442             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5443                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5444                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5445                 break;
5446             default:
5447                 break;
5448         }
5449         return true;
5450     }
5451     return false;
5452 }
5453 #endif
5454 
5455 #ifdef ENABLE_BLE
5456 
5457 #ifdef ENABLE_LE_CENTRAL
5458 static void hci_le_scan_stop(void){
5459 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5460     if (hci_extended_advertising_supported()) {
5461             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5462         } else
5463 #endif
5464     {
5465         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5466     }
5467 }
5468 #endif
5469 
5470 #ifdef ENABLE_LE_PERIPHERAL
5471 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5472 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
5473     uint8_t  operation = 0;
5474     if (pos == 0){
5475         // first fragment or complete data
5476         operation |= 1;
5477     }
5478     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
5479         // last fragment or complete data
5480         operation |= 2;
5481     }
5482     return operation;
5483 }
5484 #endif
5485 #endif
5486 
5487 static bool hci_run_general_gap_le(void){
5488 
5489     btstack_linked_list_iterator_t lit;
5490 
5491     // Phase 1: collect what to stop
5492 
5493 #ifdef ENABLE_LE_CENTRAL
5494     bool scanning_stop = false;
5495     bool connecting_stop = false;
5496 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5497 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5498     bool periodic_sync_stop = false;
5499 #endif
5500 #endif
5501 #endif
5502 
5503 #ifdef ENABLE_LE_PERIPHERAL
5504     bool advertising_stop = false;
5505 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5506     le_advertising_set_t * advertising_stop_set = NULL;
5507 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5508     bool periodic_advertising_stop = false;
5509 #endif
5510 #endif
5511 #endif
5512 
5513     // check if own address changes
5514     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5515 
5516     // check if whitelist needs modification
5517     bool whitelist_modification_pending = false;
5518     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5519     while (btstack_linked_list_iterator_has_next(&lit)){
5520         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5521         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
5522             whitelist_modification_pending = true;
5523             break;
5524         }
5525     }
5526 
5527     // check if resolving list needs modification
5528     bool resolving_list_modification_pending = false;
5529 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5530     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
5531 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
5532         resolving_list_modification_pending = true;
5533     }
5534 #endif
5535 
5536 #ifdef ENABLE_LE_CENTRAL
5537 
5538 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5539     // check if periodic advertiser list needs modification
5540     bool periodic_list_modification_pending = false;
5541     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5542     while (btstack_linked_list_iterator_has_next(&lit)){
5543         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5544         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
5545             periodic_list_modification_pending = true;
5546             break;
5547         }
5548     }
5549 #endif
5550 
5551     // scanning control
5552     if (hci_stack->le_scanning_active) {
5553         // stop if:
5554         // - parameter change required
5555         // - it's disabled
5556         // - whitelist change required but used for scanning
5557         // - resolving list modified
5558         // - own address changes
5559         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
5560         if ((hci_stack->le_scanning_param_update) ||
5561             !hci_stack->le_scanning_enabled ||
5562             (scanning_uses_whitelist && whitelist_modification_pending) ||
5563             resolving_list_modification_pending ||
5564             random_address_change){
5565 
5566             scanning_stop = true;
5567         }
5568     }
5569 
5570     // connecting control
5571     bool connecting_with_whitelist;
5572     switch (hci_stack->le_connecting_state){
5573         case LE_CONNECTING_DIRECT:
5574         case LE_CONNECTING_WHITELIST:
5575             // stop connecting if:
5576             // - connecting uses white and whitelist modification pending
5577             // - if it got disabled
5578             // - resolving list modified
5579             // - own address changes
5580             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
5581             if ((connecting_with_whitelist && whitelist_modification_pending) ||
5582                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
5583                 resolving_list_modification_pending ||
5584                 random_address_change) {
5585 
5586                 connecting_stop = true;
5587             }
5588             break;
5589         default:
5590             break;
5591     }
5592 
5593 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5594 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5595     // periodic sync control
5596     bool sync_with_advertiser_list;
5597     switch(hci_stack->le_periodic_sync_state){
5598         case LE_CONNECTING_DIRECT:
5599         case LE_CONNECTING_WHITELIST:
5600             // stop sync if:
5601             // - sync with advertiser list and advertiser list modification pending
5602             // - if it got disabled
5603             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
5604             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
5605                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
5606                 periodic_sync_stop = true;
5607             }
5608             break;
5609         default:
5610             break;
5611     }
5612 #endif
5613 #endif
5614 
5615 #endif /* ENABLE_LE_CENTRAL */
5616 
5617 #ifdef ENABLE_LE_PERIPHERAL
5618     // le advertisement control
5619     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
5620         // stop if:
5621         // - parameter change required
5622         // - random address used in advertising and changes
5623         // - it's disabled
5624         // - whitelist change required but used for advertisement filter policy
5625         // - resolving list modified
5626         // - own address changes
5627         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
5628         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
5629         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
5630         if (advertising_change ||
5631             (advertising_uses_random_address && random_address_change) ||
5632             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
5633             (advertising_uses_whitelist && whitelist_modification_pending) ||
5634             resolving_list_modification_pending ||
5635             random_address_change) {
5636 
5637             advertising_stop = true;
5638         }
5639     }
5640 
5641 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5642     if (hci_extended_advertising_supported() && (advertising_stop == false)){
5643         btstack_linked_list_iterator_t it;
5644         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5645         while (btstack_linked_list_iterator_has_next(&it)){
5646             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5647             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5648                 // stop if:
5649                 // - parameter change required
5650                 // - random address used in connectable advertising and changes
5651                 // - it's disabled
5652                 // - whitelist change required but used for advertisement filter policy
5653                 // - resolving list modified
5654                 // - own address changes
5655                 // - advertisement set will be removed
5656                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
5657                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
5658                 bool advertising_uses_random_address =
5659                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
5660                         advertising_connectable;
5661                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
5662                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
5663                 bool advertising_set_random_address_change =
5664                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5665                 bool advertising_set_will_be_removed =
5666                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
5667                 if (advertising_parameter_change ||
5668                     (advertising_uses_random_address && advertising_set_random_address_change) ||
5669                     (advertising_enabled == false) ||
5670                     (advertising_uses_whitelist && whitelist_modification_pending) ||
5671                     resolving_list_modification_pending ||
5672                     advertising_set_will_be_removed) {
5673 
5674                     advertising_stop = true;
5675                     advertising_stop_set = advertising_set;
5676                     break;
5677                 }
5678             }
5679 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5680             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5681                 // stop if:
5682                 // - it's disabled
5683                 // - parameter change required
5684                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
5685                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
5686                 if ((periodic_enabled == false) || periodic_parameter_change){
5687                     periodic_advertising_stop = true;
5688                     advertising_stop_set = advertising_set;
5689                 }
5690             }
5691 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5692         }
5693     }
5694 #endif
5695 
5696 #endif
5697 
5698 
5699     // Phase 2: stop everything that should be off during modifications
5700 
5701 
5702     // 2.1 Outgoing connection
5703 #ifdef ENABLE_LE_CENTRAL
5704     if (connecting_stop){
5705         hci_send_cmd(&hci_le_create_connection_cancel);
5706         return true;
5707     }
5708 #endif
5709 
5710     // 2.2 Scanning
5711 #ifdef ENABLE_LE_CENTRAL
5712     if (scanning_stop){
5713         hci_stack->le_scanning_active = false;
5714         hci_le_scan_stop();
5715         return true;
5716     }
5717 
5718     // 2.3 Periodic Sync
5719 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5720     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
5721         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
5722         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
5723         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
5724         return true;
5725     }
5726 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5727     if (periodic_sync_stop){
5728         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
5729         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
5730         return true;
5731     }
5732 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5733 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5734 #endif /* ENABLE_LE_CENTRAL */
5735 
5736     // 2.4 Advertising: legacy, extended, periodic
5737 #ifdef ENABLE_LE_PERIPHERAL
5738     if (advertising_stop){
5739 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5740         if (hci_extended_advertising_supported()) {
5741             uint8_t advertising_stop_handle;
5742             if (advertising_stop_set != NULL){
5743                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5744                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5745             } else {
5746                 advertising_stop_handle = 0;
5747                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5748             }
5749             const uint8_t advertising_handles[] = { advertising_stop_handle };
5750             const uint16_t durations[] = { 0 };
5751             const uint16_t max_events[] = { 0 };
5752             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5753         } else
5754 #endif
5755         {
5756             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5757             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5758         }
5759         return true;
5760     }
5761 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5762 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5763     if (periodic_advertising_stop){
5764         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5765         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
5766         return true;
5767     }
5768 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5769 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5770 #endif /* ENABLE_LE_PERIPHERAL */
5771 
5772 
5773     // Phase 3: modify
5774 
5775     if (random_address_change){
5776         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5777 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5778         if (hci_extended_advertising_supported()) {
5779             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5780         }
5781 #endif
5782         {
5783             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5784         }
5785         return true;
5786     }
5787 
5788 #ifdef ENABLE_LE_CENTRAL
5789     if (hci_stack->le_scanning_param_update){
5790         hci_stack->le_scanning_param_update = false;
5791 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5792         if (hci_extended_advertising_supported()){
5793             // prepare arrays for all PHYs
5794             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
5795             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
5796             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
5797             uint8_t  scanning_phys     = 1;  // LE 1M PHY
5798             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
5799                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
5800         } else
5801 #endif
5802         {
5803             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5804                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
5805         }
5806         return true;
5807     }
5808 #endif
5809 
5810 #ifdef ENABLE_LE_PERIPHERAL
5811     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
5812         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5813         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5814 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5815         if (hci_extended_advertising_supported()){
5816             // map advertisment type to advertising event properties
5817             uint16_t adv_event_properties = 0;
5818             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5819             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5820                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5821             }
5822             hci_stack->le_advertising_set_in_current_command = 0;
5823             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5824                          0,
5825                          adv_event_properties,
5826                          hci_stack->le_advertisements_interval_min,
5827                          hci_stack->le_advertisements_interval_max,
5828                          hci_stack->le_advertisements_channel_map,
5829                          hci_stack->le_advertisements_own_addr_type,
5830                          hci_stack->le_advertisements_direct_address_type,
5831                          hci_stack->le_advertisements_direct_address,
5832                          hci_stack->le_advertisements_filter_policy,
5833                          0x7f,  // tx power: no preference
5834                          0x01,  // primary adv phy: LE 1M
5835                          0,     // secondary adv max skip
5836                          0,     // secondary adv phy
5837                          0,     // adv sid
5838                          0      // scan request notification
5839                          );
5840         }
5841 #endif
5842         {
5843             hci_send_cmd(&hci_le_set_advertising_parameters,
5844                          hci_stack->le_advertisements_interval_min,
5845                          hci_stack->le_advertisements_interval_max,
5846                          hci_stack->le_advertisements_type,
5847                          hci_stack->le_advertisements_own_addr_type,
5848                          hci_stack->le_advertisements_direct_address_type,
5849                          hci_stack->le_advertisements_direct_address,
5850                          hci_stack->le_advertisements_channel_map,
5851                          hci_stack->le_advertisements_filter_policy);
5852         }
5853         return true;
5854     }
5855 
5856     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
5857         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5858         uint8_t adv_data_clean[31];
5859         memset(adv_data_clean, 0, sizeof(adv_data_clean));
5860         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
5861                      hci_stack->le_advertisements_data_len);
5862         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
5863 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5864         if (hci_extended_advertising_supported()){
5865             hci_stack->le_advertising_set_in_current_command = 0;
5866             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
5867         } else
5868 #endif
5869         {
5870             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
5871         }
5872         return true;
5873     }
5874 
5875     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
5876         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5877         uint8_t scan_data_clean[31];
5878         memset(scan_data_clean, 0, sizeof(scan_data_clean));
5879         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
5880                      hci_stack->le_scan_response_data_len);
5881         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
5882 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5883         if (hci_extended_advertising_supported()){
5884             hci_stack->le_advertising_set_in_current_command = 0;
5885             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
5886         } else
5887 #endif
5888         {
5889             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
5890         }
5891         return true;
5892     }
5893 
5894 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5895     if (hci_extended_advertising_supported()) {
5896         btstack_linked_list_iterator_t it;
5897         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5898         while (btstack_linked_list_iterator_has_next(&it)){
5899             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5900             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
5901                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
5902                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5903                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
5904                 return true;
5905             }
5906             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
5907                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5908                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
5909                 return true;
5910             }
5911             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
5912                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5913                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5914                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5915                              advertising_set->advertising_handle,
5916                              advertising_set->extended_params.advertising_event_properties,
5917                              advertising_set->extended_params.primary_advertising_interval_min,
5918                              advertising_set->extended_params.primary_advertising_interval_max,
5919                              advertising_set->extended_params.primary_advertising_channel_map,
5920                              advertising_set->extended_params.own_address_type,
5921                              advertising_set->extended_params.peer_address_type,
5922                              advertising_set->extended_params.peer_address,
5923                              advertising_set->extended_params.advertising_filter_policy,
5924                              advertising_set->extended_params.advertising_tx_power,
5925                              advertising_set->extended_params.primary_advertising_phy,
5926                              advertising_set->extended_params.secondary_advertising_max_skip,
5927                              advertising_set->extended_params.secondary_advertising_phy,
5928                              advertising_set->extended_params.advertising_sid,
5929                              advertising_set->extended_params.scan_request_notification_enable
5930                 );
5931                 return true;
5932             }
5933             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
5934                 uint16_t pos = advertising_set->adv_data_pos;
5935                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
5936                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5937                 if ((operation & 0x02) != 0){
5938                     // last fragment or complete data
5939                     operation |= 2;
5940                     advertising_set->adv_data_pos = 0;
5941                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5942                 } else {
5943                     advertising_set->adv_data_pos += data_to_upload;
5944                 }
5945                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5946                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
5947                 return true;
5948             }
5949             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
5950                 uint16_t pos = advertising_set->scan_data_pos;
5951                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
5952                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5953                 if ((operation & 0x02) != 0){
5954                     advertising_set->scan_data_pos = 0;
5955                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5956                 } else {
5957                     advertising_set->scan_data_pos += data_to_upload;
5958                 }
5959                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5960                 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
5961                 return true;
5962             }
5963 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5964             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
5965                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
5966                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5967                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
5968                              advertising_set->advertising_handle,
5969                              advertising_set->periodic_params.periodic_advertising_interval_min,
5970                              advertising_set->periodic_params.periodic_advertising_interval_max,
5971                              advertising_set->periodic_params.periodic_advertising_properties);
5972                 return true;
5973             }
5974             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
5975                 uint16_t pos = advertising_set->periodic_data_pos;
5976                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
5977                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5978                 if ((operation & 0x02) != 0){
5979                     // last fragment or complete data
5980                     operation |= 2;
5981                     advertising_set->periodic_data_pos = 0;
5982                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
5983                 } else {
5984                     advertising_set->periodic_data_pos += data_to_upload;
5985                 }
5986                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5987                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
5988                 return true;
5989             }
5990 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5991         }
5992     }
5993 #endif
5994 
5995 #endif
5996 
5997 #ifdef ENABLE_LE_CENTRAL
5998     // if connect with whitelist was active and is not cancelled yet, wait until next time
5999     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
6000 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6001     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
6002     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
6003 #endif
6004 #endif
6005 
6006     // LE Whitelist Management
6007     if (whitelist_modification_pending){
6008         // add/remove entries
6009         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6010         while (btstack_linked_list_iterator_has_next(&lit)){
6011             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6012 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
6013 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6014 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
6015 				return true;
6016 			}
6017             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
6018 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
6019                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
6020                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
6021                 return true;
6022             }
6023             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
6024 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6025 				btstack_memory_whitelist_entry_free(entry);
6026             }
6027         }
6028     }
6029 
6030 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6031     // LE Resolving List Management
6032     if (resolving_list_supported) {
6033 		uint16_t i;
6034 		switch (hci_stack->le_resolving_list_state) {
6035 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
6036 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6037 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
6038 				return true;
6039 			case LE_RESOLVING_LIST_READ_SIZE:
6040 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
6041 				hci_send_cmd(&hci_le_read_resolving_list_size);
6042 				return true;
6043 			case LE_RESOLVING_LIST_SEND_CLEAR:
6044 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6045 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6046 							  sizeof(hci_stack->le_resolving_list_add_entries));
6047 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6048 							  sizeof(hci_stack->le_resolving_list_remove_entries));
6049 				hci_send_cmd(&hci_le_clear_resolving_list);
6050 				return true;
6051 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
6052 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6053 					uint8_t offset = i >> 3;
6054 					uint8_t mask = 1 << (i & 7);
6055 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
6056 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
6057 					bd_addr_t peer_identity_addreses;
6058 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6059 					sm_key_t peer_irk;
6060 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6061 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6062 
6063 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6064 					// trigger whitelist entry 'update' (work around for controller bug)
6065 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6066 					while (btstack_linked_list_iterator_has_next(&lit)) {
6067 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6068 						if (entry->address_type != peer_identity_addr_type) continue;
6069 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6070 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6071 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6072 					}
6073 #endif
6074 
6075 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6076 								 peer_identity_addreses);
6077 					return true;
6078 				}
6079 
6080 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
6081 
6082 				/* fall through */
6083 
6084 			case LE_RESOLVING_LIST_ADD_ENTRIES:
6085 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6086 					uint8_t offset = i >> 3;
6087 					uint8_t mask = 1 << (i & 7);
6088 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
6089 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
6090 					bd_addr_t peer_identity_addreses;
6091 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6092 					sm_key_t peer_irk;
6093 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6094 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6095                     if (btstack_is_null(peer_irk, 16)) continue;
6096 					const uint8_t *local_irk = gap_get_persistent_irk();
6097 					// command uses format specifier 'P' that stores 16-byte value without flip
6098 					uint8_t local_irk_flipped[16];
6099 					uint8_t peer_irk_flipped[16];
6100 					reverse_128(local_irk, local_irk_flipped);
6101 					reverse_128(peer_irk, peer_irk_flipped);
6102 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6103 								 peer_irk_flipped, local_irk_flipped);
6104 					return true;
6105 				}
6106 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6107 				break;
6108 
6109 			default:
6110 				break;
6111 		}
6112 	}
6113     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6114 #endif
6115 
6116 #ifdef ENABLE_LE_CENTRAL
6117 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6118     // LE Whitelist Management
6119     if (periodic_list_modification_pending){
6120         // add/remove entries
6121         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6122         while (btstack_linked_list_iterator_has_next(&lit)){
6123             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6124             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6125                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6126                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
6127                 return true;
6128             }
6129             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6130                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6131                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
6132                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6133                 return true;
6134             }
6135             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6136                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6137                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6138             }
6139         }
6140     }
6141 #endif
6142 #endif
6143 
6144     // post-pone all actions until stack is fully working
6145     if (hci_stack->state != HCI_STATE_WORKING) return false;
6146 
6147     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6148     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6149 
6150     // Phase 4: restore state
6151 
6152 #ifdef ENABLE_LE_CENTRAL
6153     // re-start scanning
6154     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6155         hci_stack->le_scanning_active = true;
6156 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6157         if (hci_extended_advertising_supported()){
6158             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0);
6159         } else
6160 #endif
6161         {
6162             hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
6163         }
6164         return true;
6165     }
6166 #endif
6167 
6168 #ifdef ENABLE_LE_CENTRAL
6169     // re-start connecting
6170     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6171         bd_addr_t null_addr;
6172         memset(null_addr, 0, 6);
6173         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6174         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6175         hci_send_cmd(&hci_le_create_connection,
6176                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
6177                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
6178                      1,         // use whitelist
6179                      0,         // peer address type
6180                      null_addr, // peer bd addr
6181                      hci_stack->le_connection_own_addr_type,   // our addr type:
6182                      hci_stack->le_connection_interval_min,    // conn interval min
6183                      hci_stack->le_connection_interval_max,    // conn interval max
6184                      hci_stack->le_connection_latency,         // conn latency
6185                      hci_stack->le_supervision_timeout,        // conn latency
6186                      hci_stack->le_minimum_ce_length,          // min ce length
6187                      hci_stack->le_maximum_ce_length           // max ce length
6188         );
6189         return true;
6190     }
6191 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6192     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6193         switch(hci_stack->le_periodic_sync_request){
6194             case LE_CONNECTING_DIRECT:
6195             case LE_CONNECTING_WHITELIST:
6196                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6197                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6198                              hci_stack->le_periodic_sync_options,
6199                              hci_stack->le_periodic_sync_advertising_sid,
6200                              hci_stack->le_periodic_sync_advertiser_address_type,
6201                              hci_stack->le_periodic_sync_advertiser_address,
6202                              hci_stack->le_periodic_sync_skip,
6203                              hci_stack->le_periodic_sync_timeout,
6204                              hci_stack->le_periodic_sync_cte_type);
6205                 return true;
6206             default:
6207                 break;
6208         }
6209     }
6210 #endif
6211 #endif
6212 
6213 #ifdef ENABLE_LE_PERIPHERAL
6214     // re-start advertising
6215     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6216         // check if advertisements should be enabled given
6217         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6218         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6219 
6220 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6221         if (hci_extended_advertising_supported()){
6222             const uint8_t advertising_handles[] = { 0 };
6223             const uint16_t durations[] = { 0 };
6224             const uint16_t max_events[] = { 0 };
6225             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6226         } else
6227 #endif
6228         {
6229             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6230         }
6231         return true;
6232     }
6233 
6234 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6235     if (hci_extended_advertising_supported()) {
6236         btstack_linked_list_iterator_t it;
6237         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6238         while (btstack_linked_list_iterator_has_next(&it)) {
6239             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6240             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6241                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6242                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6243                 const uint16_t durations[] = { advertising_set->enable_timeout };
6244                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6245                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6246                 return true;
6247             }
6248 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6249             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6250                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6251                 uint8_t enable = 1;
6252                 if (advertising_set->periodic_include_adi){
6253                     enable |= 2;
6254                 }
6255                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6256                 return true;
6257             }
6258 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6259         }
6260     }
6261 #endif
6262 #endif
6263 
6264     return false;
6265 }
6266 
6267 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6268 static bool hci_run_iso_tasks(void){
6269     btstack_linked_list_iterator_t it;
6270 
6271     if (hci_stack->iso_active_operation_group_id != 0xff) {
6272         return false;
6273     }
6274 
6275     // BIG
6276     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6277     while (btstack_linked_list_iterator_has_next(&it)){
6278         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6279         switch (big->state){
6280             case LE_AUDIO_BIG_STATE_CREATE:
6281                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
6282                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6283                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6284                 hci_send_cmd(&hci_le_create_big,
6285                              big->params->big_handle,
6286                              big->params->advertising_handle,
6287                              big->params->num_bis,
6288                              big->params->sdu_interval_us,
6289                              big->params->max_sdu,
6290                              big->params->max_transport_latency_ms,
6291                              big->params->rtn,
6292                              big->params->phy,
6293                              big->params->packing,
6294                              big->params->framing,
6295                              big->params->encryption,
6296                              big->params->broadcast_code);
6297                 return true;
6298             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6299                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6300                 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);
6301                 return true;
6302             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6303                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6304                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6305                 return true;
6306             case LE_AUDIO_BIG_STATE_TERMINATE:
6307                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6308                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6309                 return true;
6310             default:
6311                 break;
6312         }
6313     }
6314 
6315     // BIG Sync
6316     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6317     while (btstack_linked_list_iterator_has_next(&it)){
6318         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6319         switch (big_sync->state){
6320             case LE_AUDIO_BIG_STATE_CREATE:
6321                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
6322                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6323                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6324                 hci_send_cmd(&hci_le_big_create_sync,
6325                              big_sync->params->big_handle,
6326                              big_sync->params->sync_handle,
6327                              big_sync->params->encryption,
6328                              big_sync->params->broadcast_code,
6329                              big_sync->params->mse,
6330                              big_sync->params->big_sync_timeout_10ms,
6331                              big_sync->params->num_bis,
6332                              big_sync->params->bis_indices);
6333                 return true;
6334             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6335                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6336                 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);
6337                 return true;
6338             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6339                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6340                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6341                 return true;
6342             case LE_AUDIO_BIG_STATE_TERMINATE:
6343                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6344                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6345                 return true;
6346             default:
6347                 break;
6348         }
6349     }
6350 
6351     // CIG
6352     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
6353     while (btstack_linked_list_iterator_has_next(&it)) {
6354         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
6355         uint8_t i;
6356         // Set CIG Parameters
6357         uint8_t cis_id[MAX_NR_CIS];
6358         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
6359         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
6360         uint8_t phy_c_to_p[MAX_NR_CIS];
6361         uint8_t phy_p_to_c[MAX_NR_CIS];
6362         uint8_t rtn_c_to_p[MAX_NR_CIS];
6363         uint8_t rtn_p_to_c[MAX_NR_CIS];
6364         switch (cig->state) {
6365             case LE_AUDIO_CIG_STATE_CREATE:
6366                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6367                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6368                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
6369                 le_audio_cig_params_t * params = cig->params;
6370                 for (i = 0; i < params->num_cis; i++) {
6371                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
6372                     cis_id[i]         = cis_params->cis_id;
6373                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
6374                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
6375                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
6376                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
6377                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
6378                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
6379                 }
6380                 hci_send_cmd(&hci_le_set_cig_parameters,
6381                              cig->cig_id,
6382                              params->sdu_interval_c_to_p,
6383                              params->sdu_interval_p_to_c,
6384                              params->worst_case_sca,
6385                              params->packing,
6386                              params->framing,
6387                              params->max_transport_latency_c_to_p,
6388                              params->max_transport_latency_p_to_c,
6389                              params->num_cis,
6390                              cis_id,
6391                              max_sdu_c_to_p,
6392                              max_sdu_p_to_c,
6393                              phy_c_to_p,
6394                              phy_p_to_c,
6395                              rtn_c_to_p,
6396                              rtn_p_to_c
6397                 );
6398                 return true;
6399             case LE_AUDIO_CIG_STATE_CREATE_CIS:
6400                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6401                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6402                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
6403                 for (i=0;i<cig->num_cis;i++){
6404                     cig->cis_setup_active[i] = true;
6405                 }
6406                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
6407                 return true;
6408             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
6409                 while (cig->state_vars.next_cis < (cig->num_cis * 2)){
6410                     // find next path to setup
6411                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
6412                     if (cig->cis_established[cis_index] == false) {
6413                         continue;
6414                     }
6415                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
6416                     bool setup = true;
6417                     if (cis_direction){
6418                         // 0 - input - host to controller
6419                         // we are central => central to peripheral
6420                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
6421                     } else {
6422                         // 1 - output - controller to host
6423                         // we are central => peripheral to central
6424                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
6425                     }
6426                     if (setup){
6427                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6428                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6429                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
6430                         return true;
6431                     }
6432                 }
6433                 // emit done
6434                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
6435             default:
6436                 break;
6437         }
6438     }
6439 
6440     return false;
6441 }
6442 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6443 #endif
6444 
6445 static bool hci_run_general_pending_commands(void){
6446     btstack_linked_item_t * it;
6447     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6448         hci_connection_t * connection = (hci_connection_t *) it;
6449 
6450         switch(connection->state){
6451             case SEND_CREATE_CONNECTION:
6452                 switch(connection->address_type){
6453 #ifdef ENABLE_CLASSIC
6454                     case BD_ADDR_TYPE_ACL:
6455                         log_info("sending hci_create_connection");
6456                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
6457                         break;
6458 #endif
6459                     default:
6460 #ifdef ENABLE_BLE
6461 #ifdef ENABLE_LE_CENTRAL
6462                         log_info("sending hci_le_create_connection");
6463                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6464                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6465 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6466                         if (hci_extended_advertising_supported()) {
6467                             uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval };
6468                             uint16_t le_connection_scan_window[1]   = { hci_stack->le_connection_scan_window };
6469                             uint16_t le_connection_interval_min[1]  = { hci_stack->le_connection_interval_min };
6470                             uint16_t le_connection_interval_max[1]  = { hci_stack->le_connection_interval_max };
6471                             uint16_t le_connection_latency[1]       = { hci_stack->le_connection_latency };
6472                             uint16_t le_supervision_timeout[1]      = { hci_stack->le_supervision_timeout };
6473                             uint16_t le_minimum_ce_length[1]        = { hci_stack->le_minimum_ce_length };
6474                             uint16_t le_maximum_ce_length[1]        = { hci_stack->le_maximum_ce_length };
6475                             hci_send_cmd(&hci_le_extended_create_connection,
6476                                          0,         // don't use whitelist
6477                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6478                                          connection->address_type,      // peer address type
6479                                          connection->address,           // peer bd addr
6480                                          1,                             // initiating PHY - 1M
6481                                          le_connection_scan_interval,   // conn scan interval
6482                                          le_connection_scan_window,     // conn scan windows
6483                                          le_connection_interval_min,    // conn interval min
6484                                          le_connection_interval_max,    // conn interval max
6485                                          le_connection_latency,         // conn latency
6486                                          le_supervision_timeout,        // conn latency
6487                                          le_minimum_ce_length,          // min ce length
6488                                          le_maximum_ce_length           // max ce length
6489                             );                        }
6490                         else
6491 #endif
6492                         {
6493                             hci_send_cmd(&hci_le_create_connection,
6494                                          hci_stack->le_connection_scan_interval,    // conn scan interval
6495                                          hci_stack->le_connection_scan_window,      // conn scan windows
6496                                          0,         // don't use whitelist
6497                                          connection->address_type, // peer address type
6498                                          connection->address,      // peer bd addr
6499                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6500                                          hci_stack->le_connection_interval_min,    // conn interval min
6501                                          hci_stack->le_connection_interval_max,    // conn interval max
6502                                          hci_stack->le_connection_latency,         // conn latency
6503                                          hci_stack->le_supervision_timeout,        // conn latency
6504                                          hci_stack->le_minimum_ce_length,          // min ce length
6505                                          hci_stack->le_maximum_ce_length          // max ce length
6506                             );
6507                         }
6508                         connection->state = SENT_CREATE_CONNECTION;
6509 #endif
6510 #endif
6511                         break;
6512                 }
6513                 return true;
6514 
6515 #ifdef ENABLE_CLASSIC
6516             case RECEIVED_CONNECTION_REQUEST:
6517                 connection->role  = HCI_ROLE_SLAVE;
6518                 if (connection->address_type == BD_ADDR_TYPE_ACL){
6519                     log_info("sending hci_accept_connection_request");
6520                     connection->state = ACCEPTED_CONNECTION_REQUEST;
6521                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
6522                     return true;
6523                 }
6524                 break;
6525 #endif
6526             case SEND_DISCONNECT:
6527                 connection->state = SENT_DISCONNECT;
6528                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6529                 return true;
6530 
6531             default:
6532                 break;
6533         }
6534 
6535         // no further commands if connection is about to get shut down
6536         if (connection->state == SENT_DISCONNECT) continue;
6537 
6538 #ifdef ENABLE_CLASSIC
6539 
6540         // Handling link key request requires remote supported features
6541         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
6542             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
6543             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
6544 
6545             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
6546             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
6547             if (have_link_key && security_level_sufficient){
6548                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
6549             } else {
6550                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
6551             }
6552             return true;
6553         }
6554 
6555         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
6556             log_info("denying to pin request");
6557             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
6558             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
6559             return true;
6560         }
6561 
6562         // security assessment requires remote features
6563         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
6564             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
6565             hci_ssp_assess_security_on_io_cap_request(connection);
6566             // 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
6567         }
6568 
6569         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
6570             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6571             // set authentication requirements:
6572             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
6573             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
6574             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
6575             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
6576                 authreq |= 1;
6577             }
6578             bool bonding = hci_stack->bondable;
6579             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
6580                 // if we have received IO Cap Response, we're in responder role
6581                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6582                 if (bonding && !remote_bonding){
6583                     log_info("Remote not bonding, dropping local flag");
6584                     bonding = false;
6585                 }
6586             }
6587             if (bonding){
6588                 if (connection->bonding_flags & BONDING_DEDICATED){
6589                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6590                 } else {
6591                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
6592                 }
6593             }
6594             uint8_t have_oob_data = 0;
6595 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6596             if (connection->classic_oob_c_192 != NULL){
6597                     have_oob_data |= 1;
6598             }
6599             if (connection->classic_oob_c_256 != NULL){
6600                 have_oob_data |= 2;
6601             }
6602 #endif
6603             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
6604             return true;
6605         }
6606 
6607         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
6608             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6609             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
6610             return true;
6611         }
6612 
6613 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6614         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
6615             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
6616             const uint8_t zero[16] = { 0 };
6617             const uint8_t * r_192 = zero;
6618             const uint8_t * c_192 = zero;
6619             const uint8_t * r_256 = zero;
6620             const uint8_t * c_256 = zero;
6621             // verify P-256 OOB
6622             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
6623                 c_256 = connection->classic_oob_c_256;
6624                 if (connection->classic_oob_r_256 != NULL) {
6625                     r_256 = connection->classic_oob_r_256;
6626                 }
6627             }
6628             // verify P-192 OOB
6629             if ((connection->classic_oob_c_192 != NULL)) {
6630                 c_192 = connection->classic_oob_c_192;
6631                 if (connection->classic_oob_r_192 != NULL) {
6632                     r_192 = connection->classic_oob_r_192;
6633                 }
6634             }
6635 
6636             // assess security
6637             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
6638             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
6639             if (need_level_4 && !can_reach_level_4){
6640                 log_info("Level 4 required, but not possible -> abort");
6641                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
6642                 // send oob negative reply
6643                 c_256 = NULL;
6644                 c_192 = NULL;
6645             }
6646 
6647             // Reply
6648             if (c_256 != zero) {
6649                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
6650             } else if (c_192 != zero){
6651                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
6652             } else {
6653                 hci_stack->classic_oob_con_handle = connection->con_handle;
6654                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
6655             }
6656             return true;
6657         }
6658 #endif
6659 
6660         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
6661             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
6662             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
6663             return true;
6664         }
6665 
6666         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
6667             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
6668             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
6669             return true;
6670         }
6671 
6672         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
6673             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
6674             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
6675             return true;
6676         }
6677 
6678         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
6679             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
6680             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
6681             connection->state = SENT_DISCONNECT;
6682             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6683             return true;
6684         }
6685 
6686         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
6687             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
6688             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
6689             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
6690             return true;
6691         }
6692 
6693         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
6694             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
6695             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
6696             return true;
6697         }
6698 
6699         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
6700             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
6701             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
6702             return true;
6703         }
6704 
6705         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
6706             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6707             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
6708             return true;
6709         }
6710 
6711         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
6712             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
6713             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
6714             return true;
6715         }
6716 
6717         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
6718             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
6719             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
6720             return true;
6721         }
6722 #endif
6723 
6724         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
6725             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
6726 #ifdef ENABLE_CLASSIC
6727             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
6728 #endif
6729             if (connection->state != SENT_DISCONNECT){
6730                 connection->state = SENT_DISCONNECT;
6731                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
6732                 return true;
6733             }
6734         }
6735 
6736 #ifdef ENABLE_CLASSIC
6737         uint16_t sniff_min_interval;
6738         switch (connection->sniff_min_interval){
6739             case 0:
6740                 break;
6741             case 0xffff:
6742                 connection->sniff_min_interval = 0;
6743                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
6744                 return true;
6745             default:
6746                 sniff_min_interval = connection->sniff_min_interval;
6747                 connection->sniff_min_interval = 0;
6748                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
6749                 return true;
6750         }
6751 
6752         if (connection->sniff_subrating_max_latency != 0xffff){
6753             uint16_t max_latency = connection->sniff_subrating_max_latency;
6754             connection->sniff_subrating_max_latency = 0;
6755             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
6756             return true;
6757         }
6758 
6759         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
6760             uint8_t service_type = (uint8_t) connection->qos_service_type;
6761             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
6762             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);
6763             return true;
6764         }
6765 
6766         if (connection->request_role != HCI_ROLE_INVALID){
6767             hci_role_t role = connection->request_role;
6768             connection->request_role = HCI_ROLE_INVALID;
6769             hci_send_cmd(&hci_switch_role_command, connection->address, role);
6770             return true;
6771         }
6772 #endif
6773 
6774         if (connection->gap_connection_tasks != 0){
6775 #ifdef ENABLE_CLASSIC
6776             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
6777                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
6778                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
6779                 return true;
6780             }
6781             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
6782                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
6783                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
6784                 return true;
6785             }
6786 #endif
6787             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
6788                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
6789                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
6790                 return true;
6791             }
6792         }
6793 
6794 #ifdef ENABLE_BLE
6795         switch (connection->le_con_parameter_update_state){
6796             // response to L2CAP CON PARAMETER UPDATE REQUEST
6797             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
6798                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6799                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
6800                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6801                              0x0000, 0xffff);
6802                 return true;
6803             case CON_PARAMETER_UPDATE_REPLY:
6804                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6805                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
6806                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6807                              0x0000, 0xffff);
6808                 return true;
6809             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
6810                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6811                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
6812                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
6813                 return true;
6814             default:
6815                 break;
6816         }
6817         if (connection->le_phy_update_all_phys != 0xffu){
6818             uint8_t all_phys = connection->le_phy_update_all_phys;
6819             connection->le_phy_update_all_phys = 0xff;
6820             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);
6821             return true;
6822         }
6823 #endif
6824     }
6825     return false;
6826 }
6827 
6828 static void hci_run(void){
6829 
6830     // stack state sub statemachines
6831     switch (hci_stack->state) {
6832         case HCI_STATE_INITIALIZING:
6833             hci_initializing_run();
6834             break;
6835         case HCI_STATE_HALTING:
6836             hci_halting_run();
6837             break;
6838         case HCI_STATE_FALLING_ASLEEP:
6839             hci_falling_asleep_run();
6840             break;
6841         default:
6842             break;
6843     }
6844 
6845     // allow to run after initialization to working transition
6846     if (hci_stack->state != HCI_STATE_WORKING){
6847         return;
6848     }
6849 
6850     bool done;
6851 
6852     // send continuation fragments first, as they block the prepared packet buffer
6853     done = hci_run_acl_fragments();
6854     if (done) return;
6855 
6856 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6857     done = hci_run_iso_fragments();
6858     if (done) return;
6859 #endif
6860 
6861 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
6862     // send host num completed packets next as they don't require num_cmd_packets > 0
6863     if (!hci_can_send_comand_packet_transport()) return;
6864     if (hci_stack->host_completed_packets){
6865         hci_host_num_completed_packets();
6866         return;
6867     }
6868 #endif
6869 
6870     if (!hci_can_send_command_packet_now()) return;
6871 
6872     // global/non-connection oriented commands
6873 
6874 
6875 #ifdef ENABLE_CLASSIC
6876     // general gap classic
6877     done = hci_run_general_gap_classic();
6878     if (done) return;
6879 #endif
6880 
6881 #ifdef ENABLE_BLE
6882     // general gap le
6883     done = hci_run_general_gap_le();
6884     if (done) return;
6885 
6886 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6887     // ISO related tasks, e.g. BIG create/terminate/sync
6888     done = hci_run_iso_tasks();
6889     if (done) return;
6890 #endif
6891 #endif
6892 
6893     // send pending HCI commands
6894     hci_run_general_pending_commands();
6895 }
6896 
6897 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
6898     // house-keeping
6899 
6900 #ifdef ENABLE_CLASSIC
6901     bd_addr_t addr;
6902     hci_connection_t * conn;
6903 #endif
6904 #ifdef ENABLE_LE_CENTRAL
6905     uint8_t initiator_filter_policy;
6906 #endif
6907 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6908     uint8_t i;
6909     uint8_t num_cis;
6910     hci_con_handle_t cis_handle;
6911     uint8_t status;
6912 #endif
6913 
6914     uint16_t opcode = little_endian_read_16(packet, 0);
6915     switch (opcode) {
6916         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
6917             hci_stack->loopback_mode = packet[3];
6918             break;
6919 
6920 #ifdef ENABLE_CLASSIC
6921         case HCI_OPCODE_HCI_CREATE_CONNECTION:
6922             reverse_bd_addr(&packet[3], addr);
6923             log_info("Create_connection to %s", bd_addr_to_str(addr));
6924 
6925             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
6926             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
6927                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
6928                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
6929             }
6930 
6931             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6932             if (!conn) {
6933                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6934                 if (!conn) {
6935                     // notify client that alloc failed
6936                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6937                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
6938                 }
6939                 conn->state = SEND_CREATE_CONNECTION;
6940                 conn->role  = HCI_ROLE_MASTER;
6941             }
6942 
6943             log_info("conn state %u", conn->state);
6944             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
6945             switch (conn->state) {
6946                 // if connection active exists
6947                 case OPEN:
6948                     // and OPEN, emit connection complete command
6949                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
6950                     // packet not sent to controller
6951                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6952                 case RECEIVED_DISCONNECTION_COMPLETE:
6953                     // create connection triggered in disconnect complete event, let's do it now
6954                     break;
6955                 case SEND_CREATE_CONNECTION:
6956 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
6957                     if (hci_classic_operation_active()){
6958                         return ERROR_CODE_SUCCESS;
6959                     }
6960 #endif
6961                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
6962                     break;
6963                 default:
6964                     // otherwise, just ignore as it is already in the open process
6965                     // packet not sent to controller
6966                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6967             }
6968             conn->state = SENT_CREATE_CONNECTION;
6969 
6970             // track outgoing connection
6971             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
6972             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
6973             break;
6974 
6975 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
6976         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
6977             // setup_synchronous_connection? Voice setting at offset 22
6978             // TODO: compare to current setting if sco connection already active
6979             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
6980             break;
6981         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
6982             // accept_synchronous_connection? Voice setting at offset 18
6983             // TODO: compare to current setting if sco connection already active
6984             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
6985             // track outgoing connection
6986             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
6987             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
6988             break;
6989 #endif
6990 #endif
6991 
6992 #ifdef ENABLE_BLE
6993 #ifdef ENABLE_LE_CENTRAL
6994         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
6995             // white list used?
6996             initiator_filter_policy = packet[7];
6997             switch (initiator_filter_policy) {
6998                 case 0:
6999                     // whitelist not used
7000                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7001                     break;
7002                 case 1:
7003                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7004                     break;
7005                 default:
7006                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7007                     break;
7008             }
7009             // track outgoing connection
7010             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
7011             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
7012             break;
7013         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
7014             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
7015             break;
7016 #endif
7017 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7018 #ifdef ENABLE_LE_CENTRAL
7019         case HCI_OPCODE_HCI_LE_CREATE_CIS:
7020             status = ERROR_CODE_SUCCESS;
7021             num_cis = packet[3];
7022             // setup hci_iso_streams
7023             for (i=0;i<num_cis;i++){
7024                 cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 4 + (4 * i));
7025                 status = hci_iso_stream_create(HCI_ISO_TYPE_BIS, cis_handle, 0xff);
7026                 if (status != ERROR_CODE_SUCCESS) {
7027                     break;
7028                 }
7029             }
7030             // free structs on error
7031             if (status != ERROR_CODE_SUCCESS){
7032                 hci_iso_stream_requested_finalize(0xff);
7033                 return status;
7034             }
7035             break;
7036 #endif /* ENABLE_LE_CENTRAL */
7037 #ifdef ENABLE_LE_PERIPHERAL
7038         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
7039             cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 3);
7040             status = hci_iso_stream_create(HCI_ISO_TYPE_BIS, cis_handle, 0xff);
7041             if (status != ERROR_CODE_SUCCESS){
7042                 return status;
7043             }
7044             break;
7045 #endif /* ENABLE_LE_PERIPHERAL */
7046 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
7047 #endif /* ENABLE_BLE */
7048         default:
7049             break;
7050     }
7051 
7052     hci_stack->num_cmd_packets--;
7053 
7054     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
7055     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7056     if (err != 0){
7057         return ERROR_CODE_HARDWARE_FAILURE;
7058     }
7059     return ERROR_CODE_SUCCESS;
7060 }
7061 
7062 // disconnect because of security block
7063 void hci_disconnect_security_block(hci_con_handle_t con_handle){
7064     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7065     if (!connection) return;
7066     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
7067 }
7068 
7069 
7070 // Configure Secure Simple Pairing
7071 
7072 #ifdef ENABLE_CLASSIC
7073 
7074 // enable will enable SSP during init
7075 void gap_ssp_set_enable(int enable){
7076     hci_stack->ssp_enable = enable;
7077 }
7078 
7079 static int hci_local_ssp_activated(void){
7080     return gap_ssp_supported() && hci_stack->ssp_enable;
7081 }
7082 
7083 // if set, BTstack will respond to io capability request using authentication requirement
7084 void gap_ssp_set_io_capability(int io_capability){
7085     hci_stack->ssp_io_capability = io_capability;
7086 }
7087 void gap_ssp_set_authentication_requirement(int authentication_requirement){
7088     hci_stack->ssp_authentication_requirement = authentication_requirement;
7089 }
7090 
7091 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
7092 void gap_ssp_set_auto_accept(int auto_accept){
7093     hci_stack->ssp_auto_accept = auto_accept;
7094 }
7095 
7096 void gap_secure_connections_enable(bool enable){
7097     hci_stack->secure_connections_enable = enable;
7098 }
7099 bool gap_secure_connections_active(void){
7100     return hci_stack->secure_connections_active;
7101 }
7102 
7103 #endif
7104 
7105 // va_list part of hci_send_cmd
7106 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
7107     if (!hci_can_send_command_packet_now()){
7108         log_error("hci_send_cmd called but cannot send packet now");
7109         return ERROR_CODE_COMMAND_DISALLOWED;
7110     }
7111 
7112     // for HCI INITIALIZATION
7113     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
7114     hci_stack->last_cmd_opcode = cmd->opcode;
7115 
7116     hci_reserve_packet_buffer();
7117     uint8_t * packet = hci_stack->hci_packet_buffer;
7118     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
7119     uint8_t status = hci_send_cmd_packet(packet, size);
7120 
7121     // release packet buffer on error or for synchronous transport implementations
7122     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7123         hci_release_packet_buffer();
7124         hci_emit_transport_packet_sent();
7125     }
7126 
7127     return status;
7128 }
7129 
7130 /**
7131  * pre: numcmds >= 0 - it's allowed to send a command to the controller
7132  */
7133 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
7134     va_list argptr;
7135     va_start(argptr, cmd);
7136     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
7137     va_end(argptr);
7138     return status;
7139 }
7140 
7141 // Create various non-HCI events.
7142 // TODO: generalize, use table similar to hci_create_command
7143 
7144 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
7145     // dump packet
7146     if (dump) {
7147         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
7148     }
7149 
7150     // dispatch to all event handlers
7151     btstack_linked_list_iterator_t it;
7152     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
7153     while (btstack_linked_list_iterator_has_next(&it)){
7154         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
7155         entry->callback(HCI_EVENT_PACKET, 0, event, size);
7156     }
7157 }
7158 
7159 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
7160     if (!hci_stack->acl_packet_handler) return;
7161     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
7162 }
7163 
7164 #ifdef ENABLE_CLASSIC
7165 static void hci_notify_if_sco_can_send_now(void){
7166     // notify SCO sender if waiting
7167     if (!hci_stack->sco_waiting_for_can_send_now) return;
7168     if (hci_can_send_sco_packet_now()){
7169         hci_stack->sco_waiting_for_can_send_now = 0;
7170         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
7171         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
7172         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
7173     }
7174 }
7175 
7176 // parsing end emitting has been merged to reduce code size
7177 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
7178     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
7179 
7180     uint8_t * eir_data;
7181     ad_context_t context;
7182     const uint8_t * name;
7183     uint8_t         name_len;
7184 
7185     if (size < 3) return;
7186 
7187     int event_type = hci_event_packet_get_type(packet);
7188     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
7189     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
7190 
7191     switch (event_type){
7192         case HCI_EVENT_INQUIRY_RESULT:
7193         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7194             if (size != (3 + (num_responses * 14))) return;
7195             break;
7196         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7197             if (size != 257) return;
7198             if (num_responses != 1) return;
7199             break;
7200         default:
7201             return;
7202     }
7203 
7204     // event[1] is set at the end
7205     int i;
7206     for (i=0; i<num_responses;i++){
7207         memset(event, 0, sizeof(event));
7208         event[0] = GAP_EVENT_INQUIRY_RESULT;
7209         uint8_t event_size = 27;    // if name is not set by EIR
7210 
7211         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
7212         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
7213         (void)memcpy(&event[9],
7214                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
7215                      3); // class of device
7216         (void)memcpy(&event[12],
7217                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
7218                      2); // clock offset
7219 
7220         switch (event_type){
7221             case HCI_EVENT_INQUIRY_RESULT:
7222                 // 14,15,16,17 = 0, size 18
7223                 break;
7224             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7225                 event[14] = 1;
7226                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7227                 // 16,17 = 0, size 18
7228                 break;
7229             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7230                 event[14] = 1;
7231                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7232                 // EIR packets only contain a single inquiry response
7233                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
7234                 name = NULL;
7235                 // Iterate over EIR data
7236                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
7237                     uint8_t data_type    = ad_iterator_get_data_type(&context);
7238                     uint8_t data_size    = ad_iterator_get_data_len(&context);
7239                     const uint8_t * data = ad_iterator_get_data(&context);
7240                     // Prefer Complete Local Name over Shortened Local Name
7241                     switch (data_type){
7242                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
7243                             if (name) continue;
7244                             /* fall through */
7245                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
7246                             name = data;
7247                             name_len = data_size;
7248                             break;
7249                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
7250                             if (data_size != 8) break;
7251                             event[16] = 1;
7252                             memcpy(&event[17], data, 8);
7253                             break;
7254                         default:
7255                             break;
7256                     }
7257                 }
7258                 if (name){
7259                     event[25] = 1;
7260                     // truncate name if needed
7261                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
7262                     event[26] = len;
7263                     (void)memcpy(&event[27], name, len);
7264                     event_size += len;
7265                 }
7266                 break;
7267             default:
7268                 return;
7269         }
7270         event[1] = event_size - 2;
7271         hci_emit_event(event, event_size, 1);
7272     }
7273 }
7274 #endif
7275 
7276 void hci_emit_state(void){
7277     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
7278     uint8_t event[3];
7279     event[0] = BTSTACK_EVENT_STATE;
7280     event[1] = sizeof(event) - 2u;
7281     event[2] = hci_stack->state;
7282     hci_emit_event(event, sizeof(event), 1);
7283 }
7284 
7285 #ifdef ENABLE_CLASSIC
7286 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
7287     uint8_t event[13];
7288     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
7289     event[1] = sizeof(event) - 2;
7290     event[2] = status;
7291     little_endian_store_16(event, 3, con_handle);
7292     reverse_bd_addr(address, &event[5]);
7293     event[11] = 1; // ACL connection
7294     event[12] = 0; // encryption disabled
7295     hci_emit_event(event, sizeof(event), 1);
7296 }
7297 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
7298     if (disable_l2cap_timeouts) return;
7299     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
7300     uint8_t event[4];
7301     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
7302     event[1] = sizeof(event) - 2;
7303     little_endian_store_16(event, 2, conn->con_handle);
7304     hci_emit_event(event, sizeof(event), 1);
7305 }
7306 #endif
7307 
7308 #ifdef ENABLE_BLE
7309 #ifdef ENABLE_LE_CENTRAL
7310 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){
7311     uint8_t event[21];
7312     event[0] = HCI_EVENT_LE_META;
7313     event[1] = sizeof(event) - 2u;
7314     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
7315     event[3] = status;
7316     little_endian_store_16(event, 4, con_handle);
7317     event[6] = 0; // TODO: role
7318     event[7] = address_type;
7319     reverse_bd_addr(address, &event[8]);
7320     little_endian_store_16(event, 14, 0); // interval
7321     little_endian_store_16(event, 16, 0); // latency
7322     little_endian_store_16(event, 18, 0); // supervision timeout
7323     event[20] = 0; // master clock accuracy
7324     hci_emit_event(event, sizeof(event), 1);
7325 }
7326 #endif
7327 #endif
7328 
7329 static void hci_emit_transport_packet_sent(void){
7330     // notify upper stack that it might be possible to send again
7331     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
7332     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
7333 }
7334 
7335 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
7336     uint8_t event[6];
7337     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
7338     event[1] = sizeof(event) - 2u;
7339     event[2] = 0; // status = OK
7340     little_endian_store_16(event, 3, con_handle);
7341     event[5] = reason;
7342     hci_emit_event(event, sizeof(event), 1);
7343 }
7344 
7345 static void hci_emit_nr_connections_changed(void){
7346     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
7347     uint8_t event[3];
7348     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
7349     event[1] = sizeof(event) - 2u;
7350     event[2] = nr_hci_connections();
7351     hci_emit_event(event, sizeof(event), 1);
7352 }
7353 
7354 static void hci_emit_hci_open_failed(void){
7355     log_info("BTSTACK_EVENT_POWERON_FAILED");
7356     uint8_t event[2];
7357     event[0] = BTSTACK_EVENT_POWERON_FAILED;
7358     event[1] = sizeof(event) - 2u;
7359     hci_emit_event(event, sizeof(event), 1);
7360 }
7361 
7362 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
7363     log_info("hci_emit_dedicated_bonding_result %u ", status);
7364     uint8_t event[9];
7365     int pos = 0;
7366     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
7367     event[pos++] = sizeof(event) - 2u;
7368     event[pos++] = status;
7369     reverse_bd_addr(address, &event[pos]);
7370     hci_emit_event(event, sizeof(event), 1);
7371 }
7372 
7373 
7374 #ifdef ENABLE_CLASSIC
7375 
7376 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
7377     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
7378     uint8_t event[5];
7379     int pos = 0;
7380     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
7381     event[pos++] = sizeof(event) - 2;
7382     little_endian_store_16(event, 2, con_handle);
7383     pos += 2;
7384     event[pos++] = level;
7385     hci_emit_event(event, sizeof(event), 1);
7386 }
7387 
7388 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
7389     if (!connection) return LEVEL_0;
7390     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
7391     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
7392     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
7393     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
7394     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
7395     // LEVEL 4 always requires 128 bit encrytion key size
7396     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
7397         security_level = LEVEL_3;
7398     }
7399     return security_level;
7400 }
7401 
7402 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
7403     uint8_t event[4];
7404     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
7405     event[1] = sizeof(event) - 2;
7406     event[2] = discoverable;
7407     event[3] = connectable;
7408     hci_emit_event(event, sizeof(event), 1);
7409 }
7410 
7411 // query if remote side supports eSCO
7412 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
7413     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7414     if (!connection) return false;
7415     return (connection->remote_supported_features[0] & 1) != 0;
7416 }
7417 
7418 static bool hci_ssp_supported(hci_connection_t * connection){
7419     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
7420     return (connection->bonding_flags & mask) == mask;
7421 }
7422 
7423 // query if remote side supports SSP
7424 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
7425     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7426     if (!connection) return false;
7427     return hci_ssp_supported(connection) ? 1 : 0;
7428 }
7429 
7430 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
7431     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
7432 }
7433 
7434 /**
7435  * Check if remote supported features query has completed
7436  */
7437 bool hci_remote_features_available(hci_con_handle_t handle){
7438     hci_connection_t * connection = hci_connection_for_handle(handle);
7439     if (!connection) return false;
7440     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
7441 }
7442 
7443 /**
7444  * Trigger remote supported features query
7445  */
7446 
7447 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
7448     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
7449         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7450     }
7451 }
7452 
7453 void hci_remote_features_query(hci_con_handle_t con_handle){
7454     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7455     if (!connection) return;
7456     hci_trigger_remote_features_for_connection(connection);
7457     hci_run();
7458 }
7459 
7460 // GAP API
7461 /**
7462  * @bbrief enable/disable bonding. default is enabled
7463  * @praram enabled
7464  */
7465 void gap_set_bondable_mode(int enable){
7466     hci_stack->bondable = enable ? 1 : 0;
7467 }
7468 /**
7469  * @brief Get bondable mode.
7470  * @return 1 if bondable
7471  */
7472 int gap_get_bondable_mode(void){
7473     return hci_stack->bondable;
7474 }
7475 
7476 /**
7477  * @brief map link keys to security levels
7478  */
7479 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
7480     switch (link_key_type){
7481         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7482             return LEVEL_4;
7483         case COMBINATION_KEY:
7484         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7485             return LEVEL_3;
7486         default:
7487             return LEVEL_2;
7488     }
7489 }
7490 
7491 /**
7492  * @brief map link keys to secure connection yes/no
7493  */
7494 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
7495     switch (link_key_type){
7496         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7497         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7498             return true;
7499         default:
7500             return false;
7501     }
7502 }
7503 
7504 /**
7505  * @brief map link keys to authenticated
7506  */
7507 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
7508     switch (link_key_type){
7509         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7510         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7511             return true;
7512         default:
7513             return false;
7514     }
7515 }
7516 
7517 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
7518     log_info("gap_mitm_protection_required_for_security_level %u", level);
7519     return level > LEVEL_2;
7520 }
7521 
7522 /**
7523  * @brief get current security level
7524  */
7525 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
7526     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7527     if (!connection) return LEVEL_0;
7528     return gap_security_level_for_connection(connection);
7529 }
7530 
7531 /**
7532  * @brief request connection to device to
7533  * @result GAP_AUTHENTICATION_RESULT
7534  */
7535 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
7536     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7537     if (!connection){
7538         hci_emit_security_level(con_handle, LEVEL_0);
7539         return;
7540     }
7541 
7542     btstack_assert(hci_is_le_connection(connection) == false);
7543 
7544     // 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)
7545     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
7546     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
7547         requested_level = LEVEL_4;
7548     }
7549 
7550     gap_security_level_t current_level = gap_security_level(con_handle);
7551     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
7552         requested_level, connection->requested_security_level, current_level);
7553 
7554     // authentication active if authentication request was sent or planned level > 0
7555     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
7556     if (authentication_active){
7557         // authentication already active
7558         if (connection->requested_security_level < requested_level){
7559             // increase requested level as new level is higher
7560             // TODO: handle re-authentication when done
7561             connection->requested_security_level = requested_level;
7562         }
7563     } else {
7564         // no request active, notify if security sufficient
7565         if (requested_level <= current_level){
7566             hci_emit_security_level(con_handle, current_level);
7567             return;
7568         }
7569 
7570         // store request
7571         connection->requested_security_level = requested_level;
7572 
7573         // start to authenticate connection
7574         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
7575 
7576         // request remote features if not already active, also trigger hci_run
7577         hci_remote_features_query(con_handle);
7578     }
7579 }
7580 
7581 /**
7582  * @brief start dedicated bonding with device. disconnect after bonding
7583  * @param device
7584  * @param request MITM protection
7585  * @result GAP_DEDICATED_BONDING_COMPLETE
7586  */
7587 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
7588 
7589     // create connection state machine
7590     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
7591 
7592     if (!connection){
7593         return BTSTACK_MEMORY_ALLOC_FAILED;
7594     }
7595 
7596     // delete linkn key
7597     gap_drop_link_key_for_bd_addr(device);
7598 
7599     // configure LEVEL_2/3, dedicated bonding
7600     connection->state = SEND_CREATE_CONNECTION;
7601     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
7602     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
7603     connection->bonding_flags = BONDING_DEDICATED;
7604 
7605     // wait for GAP Security Result and send GAP Dedicated Bonding complete
7606 
7607     // handle: connnection failure (connection complete != ok)
7608     // handle: authentication failure
7609     // handle: disconnect on done
7610 
7611     hci_run();
7612 
7613     return 0;
7614 }
7615 
7616 void gap_set_local_name(const char * local_name){
7617     hci_stack->local_name = local_name;
7618     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
7619     // also update EIR if not set by user
7620     if (hci_stack->eir_data == NULL){
7621         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7622     }
7623     hci_run();
7624 }
7625 #endif
7626 
7627 
7628 #ifdef ENABLE_BLE
7629 
7630 #ifdef ENABLE_LE_CENTRAL
7631 void gap_start_scan(void){
7632     hci_stack->le_scanning_enabled = true;
7633     hci_run();
7634 }
7635 
7636 void gap_stop_scan(void){
7637     hci_stack->le_scanning_enabled = false;
7638     hci_run();
7639 }
7640 
7641 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
7642     hci_stack->le_scan_type          = scan_type;
7643     hci_stack->le_scan_filter_policy = scanning_filter_policy;
7644     hci_stack->le_scan_interval      = scan_interval;
7645     hci_stack->le_scan_window        = scan_window;
7646     hci_stack->le_scanning_param_update = true;
7647     hci_run();
7648 }
7649 
7650 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
7651     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
7652 }
7653 
7654 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
7655     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
7656     if (!conn){
7657         // disallow if le connection is already outgoing
7658         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7659             log_error("le connection already active");
7660             return ERROR_CODE_COMMAND_DISALLOWED;
7661         }
7662 
7663         log_info("gap_connect: no connection exists yet, creating context");
7664         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
7665         if (!conn){
7666             // notify client that alloc failed
7667             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7668             log_info("gap_connect: failed to alloc hci_connection_t");
7669             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
7670         }
7671 
7672         // set le connecting state
7673         if (hci_is_le_connection_type(addr_type)){
7674             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
7675         }
7676 
7677         conn->state = SEND_CREATE_CONNECTION;
7678         log_info("gap_connect: send create connection next");
7679         hci_run();
7680         return ERROR_CODE_SUCCESS;
7681     }
7682 
7683     if (!hci_is_le_connection(conn) ||
7684         (conn->state == SEND_CREATE_CONNECTION) ||
7685         (conn->state == SENT_CREATE_CONNECTION)) {
7686         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
7687         log_error("gap_connect: classic connection or connect is already being created");
7688         return GATT_CLIENT_IN_WRONG_STATE;
7689     }
7690 
7691     // check if connection was just disconnected
7692     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7693         log_info("gap_connect: send create connection (again)");
7694         conn->state = SEND_CREATE_CONNECTION;
7695         hci_run();
7696         return ERROR_CODE_SUCCESS;
7697     }
7698 
7699     log_info("gap_connect: context exists with state %u", conn->state);
7700     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
7701     hci_run();
7702     return ERROR_CODE_SUCCESS;
7703 }
7704 
7705 // @assumption: only a single outgoing LE Connection exists
7706 static hci_connection_t * gap_get_outgoing_connection(void){
7707     btstack_linked_item_t *it;
7708     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7709         hci_connection_t * conn = (hci_connection_t *) it;
7710         if (!hci_is_le_connection(conn)) continue;
7711         switch (conn->state){
7712             case SEND_CREATE_CONNECTION:
7713             case SENT_CREATE_CONNECTION:
7714                 return conn;
7715             default:
7716                 break;
7717         };
7718     }
7719     return NULL;
7720 }
7721 
7722 uint8_t gap_connect_cancel(void){
7723     hci_connection_t * conn;
7724     switch (hci_stack->le_connecting_request){
7725         case LE_CONNECTING_IDLE:
7726             break;
7727         case LE_CONNECTING_WHITELIST:
7728             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7729             hci_run();
7730             break;
7731         case LE_CONNECTING_DIRECT:
7732             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7733             conn = gap_get_outgoing_connection();
7734             if (conn == NULL){
7735                 hci_run();
7736             } else {
7737                 switch (conn->state){
7738                     case SEND_CREATE_CONNECTION:
7739                         // skip sending create connection and emit event instead
7740                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
7741                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
7742                         btstack_memory_hci_connection_free( conn );
7743                         break;
7744                     case SENT_CREATE_CONNECTION:
7745                         // let hci_run_general_gap_le cancel outgoing connection
7746                         hci_run();
7747                         break;
7748                     default:
7749                         break;
7750                 }
7751             }
7752             break;
7753         default:
7754             btstack_unreachable();
7755             break;
7756     }
7757     return ERROR_CODE_SUCCESS;
7758 }
7759 
7760 /**
7761  * @brief Set connection parameters for outgoing connections
7762  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
7763  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
7764  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
7765  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
7766  * @param conn_latency, default: 4
7767  * @param supervision_timeout (unit: 10ms), default: 720 ms
7768  * @param min_ce_length (unit: 0.625ms), default: 10 ms
7769  * @param max_ce_length (unit: 0.625ms), default: 30 ms
7770  */
7771 
7772 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
7773     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
7774     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
7775     hci_stack->le_connection_scan_interval = conn_scan_interval;
7776     hci_stack->le_connection_scan_window = conn_scan_window;
7777     hci_stack->le_connection_interval_min = conn_interval_min;
7778     hci_stack->le_connection_interval_max = conn_interval_max;
7779     hci_stack->le_connection_latency = conn_latency;
7780     hci_stack->le_supervision_timeout = supervision_timeout;
7781     hci_stack->le_minimum_ce_length = min_ce_length;
7782     hci_stack->le_maximum_ce_length = max_ce_length;
7783 }
7784 #endif
7785 
7786 /**
7787  * @brief Updates the connection parameters for a given LE connection
7788  * @param handle
7789  * @param conn_interval_min (unit: 1.25ms)
7790  * @param conn_interval_max (unit: 1.25ms)
7791  * @param conn_latency
7792  * @param supervision_timeout (unit: 10ms)
7793  * @return 0 if ok
7794  */
7795 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7796     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7797     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7798     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7799     connection->le_conn_interval_min = conn_interval_min;
7800     connection->le_conn_interval_max = conn_interval_max;
7801     connection->le_conn_latency = conn_latency;
7802     connection->le_supervision_timeout = supervision_timeout;
7803     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
7804     hci_run();
7805     return 0;
7806 }
7807 
7808 /**
7809  * @brief Request an update of the connection parameter for a given LE connection
7810  * @param handle
7811  * @param conn_interval_min (unit: 1.25ms)
7812  * @param conn_interval_max (unit: 1.25ms)
7813  * @param conn_latency
7814  * @param supervision_timeout (unit: 10ms)
7815  * @return 0 if ok
7816  */
7817 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7818     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7819     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7820     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7821     connection->le_conn_interval_min = conn_interval_min;
7822     connection->le_conn_interval_max = conn_interval_max;
7823     connection->le_conn_latency = conn_latency;
7824     connection->le_supervision_timeout = supervision_timeout;
7825     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
7826     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
7827     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
7828     return 0;
7829 }
7830 
7831 #ifdef ENABLE_LE_PERIPHERAL
7832 
7833 /**
7834  * @brief Set Advertisement Data
7835  * @param advertising_data_length
7836  * @param advertising_data (max 31 octets)
7837  * @note data is not copied, pointer has to stay valid
7838  */
7839 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
7840     hci_stack->le_advertisements_data_len = advertising_data_length;
7841     hci_stack->le_advertisements_data = advertising_data;
7842     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7843     hci_run();
7844 }
7845 
7846 /**
7847  * @brief Set Scan Response Data
7848  * @param advertising_data_length
7849  * @param advertising_data (max 31 octets)
7850  * @note data is not copied, pointer has to stay valid
7851  */
7852 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
7853     hci_stack->le_scan_response_data_len = scan_response_data_length;
7854     hci_stack->le_scan_response_data = scan_response_data;
7855     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7856     hci_run();
7857 }
7858 
7859 /**
7860  * @brief Set Advertisement Parameters
7861  * @param adv_int_min
7862  * @param adv_int_max
7863  * @param adv_type
7864  * @param direct_address_type
7865  * @param direct_address
7866  * @param channel_map
7867  * @param filter_policy
7868  *
7869  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
7870  */
7871  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
7872     uint8_t direct_address_typ, bd_addr_t direct_address,
7873     uint8_t channel_map, uint8_t filter_policy) {
7874 
7875     hci_stack->le_advertisements_interval_min = adv_int_min;
7876     hci_stack->le_advertisements_interval_max = adv_int_max;
7877     hci_stack->le_advertisements_type = adv_type;
7878     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
7879     hci_stack->le_advertisements_channel_map = channel_map;
7880     hci_stack->le_advertisements_filter_policy = filter_policy;
7881     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
7882                  6);
7883 
7884     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7885     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
7886     hci_run();
7887  }
7888 
7889 /**
7890  * @brief Enable/Disable Advertisements
7891  * @param enabled
7892  */
7893 void gap_advertisements_enable(int enabled){
7894     if (enabled == 0){
7895         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7896     } else {
7897         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
7898     }
7899     hci_update_advertisements_enabled_for_current_roles();
7900     hci_run();
7901 }
7902 
7903 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7904 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
7905     btstack_linked_list_iterator_t it;
7906     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
7907     while (btstack_linked_list_iterator_has_next(&it)){
7908         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
7909         if ( item->advertising_handle == advertising_handle ) {
7910             return item;
7911         }
7912     }
7913     return NULL;
7914 }
7915 
7916 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
7917     // find free advertisement handle
7918     uint8_t advertisement_handle;
7919     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
7920         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
7921     }
7922     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7923     // clear
7924     memset(storage, 0, sizeof(le_advertising_set_t));
7925     // copy params
7926     storage->advertising_handle = advertisement_handle;
7927     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7928     // add to list
7929     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
7930     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7931     *out_advertising_handle = advertisement_handle;
7932     // set tasks and start
7933     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7934     hci_run();
7935     return ERROR_CODE_SUCCESS;
7936 }
7937 
7938 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
7939     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7940     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7941     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7942     // set tasks and start
7943     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7944     hci_run();
7945     return ERROR_CODE_SUCCESS;
7946 }
7947 
7948 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
7949     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7950     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7951     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
7952     return ERROR_CODE_SUCCESS;
7953 }
7954 
7955 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
7956     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7957     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7958     memcpy(advertising_set->random_address, random_address, 6);
7959     // set tasks and start
7960     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7961     hci_run();
7962     return ERROR_CODE_SUCCESS;
7963 }
7964 
7965 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
7966     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7967     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7968     advertising_set->adv_data = advertising_data;
7969     advertising_set->adv_data_len = advertising_data_length;
7970     // set tasks and start
7971     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7972     hci_run();
7973     return ERROR_CODE_SUCCESS;
7974 }
7975 
7976 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){
7977     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7978     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7979     advertising_set->scan_data = scan_response_data;
7980     advertising_set->scan_data_len = scan_response_data_length;
7981     // set tasks and start
7982     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7983     hci_run();
7984     return ERROR_CODE_SUCCESS;
7985 }
7986 
7987 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
7988     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7989     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7990     advertising_set->enable_timeout = timeout;
7991     advertising_set->enable_max_scan_events = num_extended_advertising_events;
7992     // set tasks and start
7993     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
7994     hci_run();
7995     return ERROR_CODE_SUCCESS;
7996 }
7997 
7998 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
7999     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8000     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8001     // set tasks and start
8002     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8003     hci_run();
8004     return ERROR_CODE_SUCCESS;
8005 }
8006 
8007 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8008     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8009     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8010     // set tasks and start
8011     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8012     hci_run();
8013     return ERROR_CODE_SUCCESS;
8014 }
8015 
8016 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8017 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8018     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8019     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8020     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8021     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8022     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8023     // set tasks and start
8024     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8025     hci_run();
8026     return ERROR_CODE_SUCCESS;
8027 }
8028 
8029 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8030     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8031     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8032     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8033     return ERROR_CODE_SUCCESS;
8034 }
8035 
8036 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8037     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8038     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8039     advertising_set->periodic_data = periodic_data;
8040     advertising_set->periodic_data_len = periodic_data_length;
8041     // set tasks and start
8042     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8043     hci_run();
8044     return ERROR_CODE_SUCCESS;
8045 }
8046 
8047 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
8048     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8049     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8050     // set tasks and start
8051     advertising_set->periodic_include_adi = include_adi;
8052     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8053     hci_run();
8054     return ERROR_CODE_SUCCESS;
8055 }
8056 
8057 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
8058     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8059     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8060     // set tasks and start
8061     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8062     hci_run();
8063     return ERROR_CODE_SUCCESS;
8064 }
8065 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
8066 
8067 #endif
8068 
8069 #endif
8070 
8071 void hci_le_set_own_address_type(uint8_t own_address_type){
8072     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
8073     if (own_address_type == hci_stack->le_own_addr_type) return;
8074     hci_stack->le_own_addr_type = own_address_type;
8075 
8076 #ifdef ENABLE_LE_PERIPHERAL
8077     // update advertisement parameters, too
8078     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8079     hci_run();
8080 #endif
8081 #ifdef ENABLE_LE_CENTRAL
8082     // note: we don't update scan parameters or modify ongoing connection attempts
8083 #endif
8084 }
8085 
8086 void hci_le_random_address_set(const bd_addr_t random_address){
8087     memcpy(hci_stack->le_random_address, random_address, 6);
8088     hci_stack->le_random_address_set = true;
8089     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8090     hci_run();
8091 }
8092 
8093 #endif
8094 
8095 uint8_t gap_disconnect(hci_con_handle_t handle){
8096     hci_connection_t * conn = hci_connection_for_handle(handle);
8097     if (!conn){
8098         hci_emit_disconnection_complete(handle, 0);
8099         return 0;
8100     }
8101     // ignore if already disconnected
8102     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
8103         return 0;
8104     }
8105     conn->state = SEND_DISCONNECT;
8106     hci_run();
8107     return 0;
8108 }
8109 
8110 int gap_read_rssi(hci_con_handle_t con_handle){
8111     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8112     if (hci_connection == NULL) return 0;
8113     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
8114     hci_run();
8115     return 1;
8116 }
8117 
8118 /**
8119  * @brief Get connection type
8120  * @param con_handle
8121  * @result connection_type
8122  */
8123 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
8124     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8125     if (!conn) return GAP_CONNECTION_INVALID;
8126     switch (conn->address_type){
8127         case BD_ADDR_TYPE_LE_PUBLIC:
8128         case BD_ADDR_TYPE_LE_RANDOM:
8129             return GAP_CONNECTION_LE;
8130         case BD_ADDR_TYPE_SCO:
8131             return GAP_CONNECTION_SCO;
8132         case BD_ADDR_TYPE_ACL:
8133             return GAP_CONNECTION_ACL;
8134         default:
8135             return GAP_CONNECTION_INVALID;
8136     }
8137 }
8138 
8139 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
8140     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8141     if (!conn) return HCI_ROLE_INVALID;
8142     return (hci_role_t) conn->role;
8143 }
8144 
8145 
8146 #ifdef ENABLE_CLASSIC
8147 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
8148     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8149     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8150     conn->request_role = role;
8151     hci_run();
8152     return ERROR_CODE_SUCCESS;
8153 }
8154 #endif
8155 
8156 #ifdef ENABLE_BLE
8157 
8158 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){
8159     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8160     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8161 
8162     conn->le_phy_update_all_phys    = all_phys;
8163     conn->le_phy_update_tx_phys     = tx_phys;
8164     conn->le_phy_update_rx_phys     = rx_phys;
8165     conn->le_phy_update_phy_options = phy_options;
8166 
8167     hci_run();
8168 
8169     return 0;
8170 }
8171 
8172 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8173     // check if already in list
8174     btstack_linked_list_iterator_t it;
8175     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8176     while (btstack_linked_list_iterator_has_next(&it)) {
8177         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
8178         if (entry->address_type != address_type) {
8179             continue;
8180         }
8181         if (memcmp(entry->address, address, 6) != 0) {
8182             continue;
8183         }
8184 		// disallow if already scheduled to add
8185 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
8186 			return ERROR_CODE_COMMAND_DISALLOWED;
8187 		}
8188 		// still on controller, but scheduled to remove -> re-add
8189 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
8190 		return ERROR_CODE_SUCCESS;
8191     }
8192     // alloc and add to list
8193     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
8194     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8195     entry->address_type = address_type;
8196     (void)memcpy(entry->address, address, 6);
8197     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
8198     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
8199     return ERROR_CODE_SUCCESS;
8200 }
8201 
8202 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8203     btstack_linked_list_iterator_t it;
8204     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8205     while (btstack_linked_list_iterator_has_next(&it)){
8206         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8207         if (entry->address_type != address_type) {
8208             continue;
8209         }
8210         if (memcmp(entry->address, address, 6) != 0) {
8211             continue;
8212         }
8213         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8214             // remove from controller if already present
8215             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8216         }  else {
8217             // directly remove entry from whitelist
8218             btstack_linked_list_iterator_remove(&it);
8219             btstack_memory_whitelist_entry_free(entry);
8220         }
8221         return ERROR_CODE_SUCCESS;
8222     }
8223     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8224 }
8225 
8226 static void hci_whitelist_clear(void){
8227     btstack_linked_list_iterator_t it;
8228     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8229     while (btstack_linked_list_iterator_has_next(&it)){
8230         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8231         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8232             // remove from controller if already present
8233             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8234             continue;
8235         }
8236         // directly remove entry from whitelist
8237         btstack_linked_list_iterator_remove(&it);
8238         btstack_memory_whitelist_entry_free(entry);
8239     }
8240 }
8241 
8242 // free all entries unconditionally
8243 static void hci_whitelist_free(void){
8244     btstack_linked_list_iterator_t lit;
8245     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
8246     while (btstack_linked_list_iterator_has_next(&lit)){
8247         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
8248         btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
8249         btstack_memory_whitelist_entry_free(entry);
8250     }
8251 }
8252 
8253 /**
8254  * @brief Clear Whitelist
8255  * @return 0 if ok
8256  */
8257 uint8_t gap_whitelist_clear(void){
8258     hci_whitelist_clear();
8259     hci_run();
8260     return ERROR_CODE_SUCCESS;
8261 }
8262 
8263 /**
8264  * @brief Add Device to Whitelist
8265  * @param address_typ
8266  * @param address
8267  * @return 0 if ok
8268  */
8269 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8270     uint8_t status = hci_whitelist_add(address_type, address);
8271     if (status){
8272         return status;
8273     }
8274     hci_run();
8275     return ERROR_CODE_SUCCESS;
8276 }
8277 
8278 /**
8279  * @brief Remove Device from Whitelist
8280  * @param address_typ
8281  * @param address
8282  * @return 0 if ok
8283  */
8284 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8285     uint8_t status = hci_whitelist_remove(address_type, address);
8286     if (status){
8287         return status;
8288     }
8289     hci_run();
8290     return ERROR_CODE_SUCCESS;
8291 }
8292 
8293 #ifdef ENABLE_LE_CENTRAL
8294 /**
8295  * @brief Connect with Whitelist
8296  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
8297  * @return - if ok
8298  */
8299 uint8_t gap_connect_with_whitelist(void){
8300     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8301         return ERROR_CODE_COMMAND_DISALLOWED;
8302     }
8303     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8304     hci_run();
8305     return ERROR_CODE_SUCCESS;
8306 }
8307 
8308 /**
8309  * @brief Auto Connection Establishment - Start Connecting to device
8310  * @param address_typ
8311  * @param address
8312  * @return 0 if ok
8313  */
8314 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
8315     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8316         return ERROR_CODE_COMMAND_DISALLOWED;
8317     }
8318 
8319     uint8_t status = hci_whitelist_add(address_type, address);
8320     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
8321         return status;
8322     }
8323 
8324     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8325 
8326     hci_run();
8327     return ERROR_CODE_SUCCESS;
8328 }
8329 
8330 /**
8331  * @brief Auto Connection Establishment - Stop Connecting to device
8332  * @param address_typ
8333  * @param address
8334  * @return 0 if ok
8335  */
8336 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
8337     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8338         return ERROR_CODE_COMMAND_DISALLOWED;
8339     }
8340 
8341     hci_whitelist_remove(address_type, address);
8342     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
8343         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8344     }
8345     hci_run();
8346     return 0;
8347 }
8348 
8349 /**
8350  * @brief Auto Connection Establishment - Stop everything
8351  * @note  Convenience function to stop all active auto connection attempts
8352  */
8353 uint8_t gap_auto_connection_stop_all(void){
8354     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
8355         return ERROR_CODE_COMMAND_DISALLOWED;
8356     }
8357     hci_whitelist_clear();
8358     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8359     hci_run();
8360     return ERROR_CODE_SUCCESS;
8361 }
8362 
8363 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
8364     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8365     if (!conn) return 0;
8366     return conn->le_connection_interval;
8367 }
8368 #endif
8369 #endif
8370 
8371 #ifdef ENABLE_CLASSIC
8372 /**
8373  * @brief Set Extended Inquiry Response data
8374  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
8375  * @note has to be done before stack starts up
8376  */
8377 void gap_set_extended_inquiry_response(const uint8_t * data){
8378     hci_stack->eir_data = data;
8379     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
8380     hci_run();
8381 }
8382 
8383 /**
8384  * @brief Start GAP Classic Inquiry
8385  * @param duration in 1.28s units
8386  * @return 0 if ok
8387  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
8388  */
8389 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
8390     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
8391     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8392     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
8393         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8394     }
8395     hci_stack->inquiry_state = duration_in_1280ms_units;
8396     hci_stack->inquiry_max_period_length = 0;
8397     hci_stack->inquiry_min_period_length = 0;
8398     hci_run();
8399     return 0;
8400 }
8401 
8402 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
8403     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
8404     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
8405     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8406     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8407     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8408     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8409 
8410     hci_stack->inquiry_state = duration;
8411     hci_stack->inquiry_max_period_length = max_period_length;
8412     hci_stack->inquiry_min_period_length = min_period_length;
8413     hci_run();
8414     return 0;
8415 }
8416 
8417 /**
8418  * @brief Stop GAP Classic Inquiry
8419  * @return 0 if ok
8420  */
8421 int gap_inquiry_stop(void){
8422     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
8423         // emit inquiry complete event, before it even started
8424         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
8425         hci_emit_event(event, sizeof(event), 1);
8426         return 0;
8427     }
8428     switch (hci_stack->inquiry_state){
8429         case GAP_INQUIRY_STATE_ACTIVE:
8430             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
8431             hci_run();
8432             return ERROR_CODE_SUCCESS;
8433         case GAP_INQUIRY_STATE_PERIODIC:
8434             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
8435             hci_run();
8436             return ERROR_CODE_SUCCESS;
8437         default:
8438             return ERROR_CODE_COMMAND_DISALLOWED;
8439     }
8440 }
8441 
8442 void gap_inquiry_set_lap(uint32_t lap){
8443     hci_stack->inquiry_lap = lap;
8444 }
8445 
8446 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
8447     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
8448     hci_stack->inquiry_scan_window   = inquiry_scan_window;
8449     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
8450     hci_run();
8451 }
8452 
8453 
8454 /**
8455  * @brief Remote Name Request
8456  * @param addr
8457  * @param page_scan_repetition_mode
8458  * @param clock_offset only used when bit 15 is set
8459  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
8460  */
8461 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
8462     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8463     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
8464     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
8465     hci_stack->remote_name_clock_offset = clock_offset;
8466     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
8467     hci_run();
8468     return 0;
8469 }
8470 
8471 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
8472     hci_stack->gap_pairing_state = state;
8473     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
8474     hci_run();
8475     return 0;
8476 }
8477 
8478 /**
8479  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
8480  * @param addr
8481  * @param pin_data
8482  * @param pin_len
8483  * @return 0 if ok
8484  */
8485 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
8486     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8487     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
8488     hci_stack->gap_pairing_pin_len = pin_len;
8489     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
8490 }
8491 
8492 /**
8493  * @brief Legacy Pairing Pin Code Response
8494  * @param addr
8495  * @param pin
8496  * @return 0 if ok
8497  */
8498 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
8499     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
8500 }
8501 
8502 /**
8503  * @brief Abort Legacy Pairing
8504  * @param addr
8505  * @param pin
8506  * @return 0 if ok
8507  */
8508 int gap_pin_code_negative(bd_addr_t addr){
8509     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8510     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
8511 }
8512 
8513 /**
8514  * @brief SSP Passkey Response
8515  * @param addr
8516  * @param passkey
8517  * @return 0 if ok
8518  */
8519 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
8520     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8521     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
8522     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
8523 }
8524 
8525 /**
8526  * @brief Abort SSP Passkey Entry/Pairing
8527  * @param addr
8528  * @param pin
8529  * @return 0 if ok
8530  */
8531 int gap_ssp_passkey_negative(const bd_addr_t addr){
8532     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8533     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
8534 }
8535 
8536 /**
8537  * @brief Accept SSP Numeric Comparison
8538  * @param addr
8539  * @param passkey
8540  * @return 0 if ok
8541  */
8542 int gap_ssp_confirmation_response(const bd_addr_t addr){
8543     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8544     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
8545 }
8546 
8547 /**
8548  * @brief Abort SSP Numeric Comparison/Pairing
8549  * @param addr
8550  * @param pin
8551  * @return 0 if ok
8552  */
8553 int gap_ssp_confirmation_negative(const bd_addr_t addr){
8554     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8555     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
8556 }
8557 
8558 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
8559 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
8560     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8561     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8562     connectionSetAuthenticationFlags(conn, flag);
8563     hci_run();
8564     return ERROR_CODE_SUCCESS;
8565 }
8566 #endif
8567 
8568 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
8569 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
8570     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
8571 }
8572 
8573 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
8574     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
8575 }
8576 #endif
8577 
8578 #ifdef ENABLE_CLASSIC_PAIRING_OOB
8579 /**
8580  * @brief Report Remote OOB Data
8581  * @param bd_addr
8582  * @param c_192 Simple Pairing Hash C derived from P-192 public key
8583  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
8584  * @param c_256 Simple Pairing Hash C derived from P-256 public key
8585  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
8586  */
8587 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){
8588     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8589     if (connection == NULL) {
8590         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8591     }
8592     connection->classic_oob_c_192 = c_192;
8593     connection->classic_oob_r_192 = r_192;
8594 
8595     // ignore P-256 if not supported by us
8596     if (hci_stack->secure_connections_active){
8597         connection->classic_oob_c_256 = c_256;
8598         connection->classic_oob_r_256 = r_256;
8599     }
8600 
8601     return ERROR_CODE_SUCCESS;
8602 }
8603 /**
8604  * @brief Generate new OOB data
8605  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
8606  */
8607 void gap_ssp_generate_oob_data(void){
8608     hci_stack->classic_read_local_oob_data = true;
8609     hci_run();
8610 }
8611 
8612 #endif
8613 
8614 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
8615 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
8616     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8617     if (connection == NULL) {
8618         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8619     }
8620 
8621     memcpy(connection->link_key, link_key, sizeof(link_key_t));
8622     connection->link_key_type = type;
8623 
8624     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
8625 }
8626 
8627 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
8628 /**
8629  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
8630  * @param inquiry_mode see bluetooth_defines.h
8631  */
8632 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
8633     hci_stack->inquiry_mode = inquiry_mode;
8634 }
8635 
8636 /**
8637  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
8638  */
8639 void hci_set_sco_voice_setting(uint16_t voice_setting){
8640     hci_stack->sco_voice_setting = voice_setting;
8641 }
8642 
8643 /**
8644  * @brief Get SCO Voice Setting
8645  * @return current voice setting
8646  */
8647 uint16_t hci_get_sco_voice_setting(void){
8648     return hci_stack->sco_voice_setting;
8649 }
8650 
8651 static int hci_have_usb_transport(void){
8652     if (!hci_stack->hci_transport) return 0;
8653     const char * transport_name = hci_stack->hci_transport->name;
8654     if (!transport_name) return 0;
8655     return (transport_name[0] == 'H') && (transport_name[1] == '2');
8656 }
8657 
8658 /** @brief Get SCO packet length for current SCO Voice setting
8659  *  @note  Using SCO packets of the exact length is required for USB transfer
8660  *  @return Length of SCO packets in bytes (not audio frames)
8661  */
8662 uint16_t hci_get_sco_packet_length(void){
8663     uint16_t sco_packet_length = 0;
8664 
8665 #ifdef ENABLE_SCO_OVER_HCI
8666     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8667     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8668 
8669     if (hci_have_usb_transport()){
8670         // see Core Spec for H2 USB Transfer.
8671         // 3 byte SCO header + 24 bytes per connection
8672         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
8673         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
8674     } else {
8675         // 3 byte SCO header + SCO packet size over the air (60 bytes)
8676         sco_packet_length = 3 + 60 * multiplier;
8677         // assert that it still fits inside an SCO buffer
8678         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
8679             sco_packet_length = 3 + 60;
8680         }
8681     }
8682 #endif
8683 
8684 #ifdef HAVE_SCO_TRANSPORT
8685     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8686     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8687     sco_packet_length = 3 + 60 * multiplier;
8688 #endif
8689     return sco_packet_length;
8690 }
8691 
8692 /**
8693 * @brief Sets the master/slave policy
8694 * @param policy (0: attempt to become master, 1: let connecting device decide)
8695 */
8696 void hci_set_master_slave_policy(uint8_t policy){
8697     hci_stack->master_slave_policy = policy;
8698 }
8699 
8700 #endif
8701 
8702 HCI_STATE hci_get_state(void){
8703     return hci_stack->state;
8704 }
8705 
8706 #ifdef ENABLE_CLASSIC
8707 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
8708     hci_stack->gap_classic_accept_callback = accept_callback;
8709 }
8710 #endif
8711 
8712 /**
8713  * @brief Set callback for Bluetooth Hardware Error
8714  */
8715 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
8716     hci_stack->hardware_error_callback = fn;
8717 }
8718 
8719 void hci_disconnect_all(void){
8720     btstack_linked_list_iterator_t it;
8721     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
8722     while (btstack_linked_list_iterator_has_next(&it)){
8723         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
8724         if (con->state == SENT_DISCONNECT) continue;
8725         con->state = SEND_DISCONNECT;
8726     }
8727     hci_run();
8728 }
8729 
8730 uint16_t hci_get_manufacturer(void){
8731     return hci_stack->manufacturer;
8732 }
8733 
8734 #ifdef ENABLE_BLE
8735 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
8736     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
8737     if (!hci_con) return NULL;
8738     return &hci_con->sm_connection;
8739 }
8740 
8741 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
8742 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
8743 #endif
8744 
8745 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
8746     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8747     if (hci_connection == NULL) return 0;
8748     if (hci_is_le_connection(hci_connection)){
8749 #ifdef ENABLE_BLE
8750         sm_connection_t * sm_conn = &hci_connection->sm_connection;
8751         if (sm_conn->sm_connection_encrypted) {
8752             return sm_conn->sm_actual_encryption_key_size;
8753         }
8754 #endif
8755     } else {
8756 #ifdef ENABLE_CLASSIC
8757         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
8758             return hci_connection->encryption_key_size;
8759         }
8760 #endif
8761     }
8762     return 0;
8763 }
8764 
8765 bool gap_authenticated(hci_con_handle_t con_handle){
8766     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8767     if (hci_connection == NULL) return false;
8768 
8769     switch (hci_connection->address_type){
8770 #ifdef ENABLE_BLE
8771         case BD_ADDR_TYPE_LE_PUBLIC:
8772         case BD_ADDR_TYPE_LE_RANDOM:
8773             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
8774             return hci_connection->sm_connection.sm_connection_authenticated != 0;
8775 #endif
8776 #ifdef ENABLE_CLASSIC
8777         case BD_ADDR_TYPE_SCO:
8778         case BD_ADDR_TYPE_ACL:
8779             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
8780 #endif
8781         default:
8782             return false;
8783     }
8784 }
8785 
8786 bool gap_secure_connection(hci_con_handle_t con_handle){
8787     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8788     if (hci_connection == NULL) return 0;
8789 
8790     switch (hci_connection->address_type){
8791 #ifdef ENABLE_BLE
8792         case BD_ADDR_TYPE_LE_PUBLIC:
8793         case BD_ADDR_TYPE_LE_RANDOM:
8794             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
8795             return hci_connection->sm_connection.sm_connection_sc != 0;
8796 #endif
8797 #ifdef ENABLE_CLASSIC
8798         case BD_ADDR_TYPE_SCO:
8799         case BD_ADDR_TYPE_ACL:
8800             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
8801 #endif
8802         default:
8803             return false;
8804     }
8805 }
8806 
8807 bool gap_bonded(hci_con_handle_t con_handle){
8808 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8809 	if (hci_connection == NULL) return 0;
8810 
8811 #ifdef ENABLE_CLASSIC
8812 	link_key_t link_key;
8813 	link_key_type_t link_key_type;
8814 #endif
8815 	switch (hci_connection->address_type){
8816 #ifdef ENABLE_BLE
8817 		case BD_ADDR_TYPE_LE_PUBLIC:
8818 		case BD_ADDR_TYPE_LE_RANDOM:
8819 			return hci_connection->sm_connection.sm_le_db_index >= 0;
8820 #endif
8821 #ifdef ENABLE_CLASSIC
8822 		case BD_ADDR_TYPE_SCO:
8823 		case BD_ADDR_TYPE_ACL:
8824 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
8825 #endif
8826 		default:
8827 			return false;
8828 	}
8829 }
8830 
8831 #ifdef ENABLE_BLE
8832 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
8833     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
8834     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
8835     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
8836     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
8837     return sm_conn->sm_connection_authorization_state;
8838 }
8839 #endif
8840 
8841 #ifdef ENABLE_CLASSIC
8842 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){
8843     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8844     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8845     conn->sniff_min_interval = sniff_min_interval;
8846     conn->sniff_max_interval = sniff_max_interval;
8847     conn->sniff_attempt = sniff_attempt;
8848     conn->sniff_timeout = sniff_timeout;
8849     hci_run();
8850     return 0;
8851 }
8852 
8853 /**
8854  * @brief Exit Sniff mode
8855  * @param con_handle
8856  @ @return 0 if ok
8857  */
8858 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
8859     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8860     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8861     conn->sniff_min_interval = 0xffff;
8862     hci_run();
8863     return 0;
8864 }
8865 
8866 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){
8867     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8868     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8869     conn->sniff_subrating_max_latency = max_latency;
8870     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
8871     conn->sniff_subrating_min_local_timeout = min_local_timeout;
8872     hci_run();
8873     return ERROR_CODE_SUCCESS;
8874 }
8875 
8876 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){
8877     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8878     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8879     conn->qos_service_type = service_type;
8880     conn->qos_token_rate = token_rate;
8881     conn->qos_peak_bandwidth = peak_bandwidth;
8882     conn->qos_latency = latency;
8883     conn->qos_delay_variation = delay_variation;
8884     hci_run();
8885     return ERROR_CODE_SUCCESS;
8886 }
8887 
8888 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
8889     hci_stack->new_page_scan_interval = page_scan_interval;
8890     hci_stack->new_page_scan_window = page_scan_window;
8891     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
8892     hci_run();
8893 }
8894 
8895 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
8896     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
8897     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
8898     hci_run();
8899 }
8900 
8901 void gap_set_page_timeout(uint16_t page_timeout){
8902     hci_stack->page_timeout = page_timeout;
8903     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
8904     hci_run();
8905 }
8906 
8907 #endif
8908 
8909 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
8910 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
8911     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
8912     if (le_device_db_index >= le_device_db_max_count()) return;
8913     uint8_t offset = le_device_db_index >> 3;
8914     uint8_t mask = 1 << (le_device_db_index & 7);
8915     hci_stack->le_resolving_list_add_entries[offset] |= mask;
8916     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
8917     	// note: go back to remove entries, otherwise, a remove + add will skip the add
8918         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
8919     }
8920 }
8921 
8922 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
8923 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
8924 	if (le_device_db_index >= le_device_db_max_count()) return;
8925 	uint8_t offset = le_device_db_index >> 3;
8926 	uint8_t mask = 1 << (le_device_db_index & 7);
8927 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
8928 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
8929 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
8930 	}
8931 }
8932 
8933 uint8_t gap_load_resolving_list_from_le_device_db(void){
8934     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
8935 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
8936 	}
8937 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
8938 		// restart le resolving list update
8939 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
8940 	}
8941 	return ERROR_CODE_SUCCESS;
8942 }
8943 #endif
8944 
8945 #ifdef ENABLE_BLE
8946 #ifdef ENABLE_LE_CENTRAL
8947 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8948 
8949 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8950     // check if already in list
8951     btstack_linked_list_iterator_t it;
8952     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8953     while (btstack_linked_list_iterator_has_next(&it)) {
8954         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
8955         if (entry->sid != advertising_sid) {
8956             continue;
8957         }
8958         if (entry->address_type != address_type) {
8959             continue;
8960         }
8961         if (memcmp(entry->address, address, 6) != 0) {
8962             continue;
8963         }
8964         // disallow if already scheduled to add
8965         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
8966             return ERROR_CODE_COMMAND_DISALLOWED;
8967         }
8968         // still on controller, but scheduled to remove -> re-add
8969         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8970         return ERROR_CODE_SUCCESS;
8971     }
8972     // alloc and add to list
8973     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
8974     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8975     entry->sid = advertising_sid;
8976     entry->address_type = address_type;
8977     (void)memcpy(entry->address, address, 6);
8978     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8979     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
8980     return ERROR_CODE_SUCCESS;
8981 }
8982 
8983 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8984     btstack_linked_list_iterator_t it;
8985     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8986     while (btstack_linked_list_iterator_has_next(&it)){
8987         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8988         if (entry->sid != advertising_sid) {
8989             continue;
8990         }
8991         if (entry->address_type != address_type) {
8992             continue;
8993         }
8994         if (memcmp(entry->address, address, 6) != 0) {
8995             continue;
8996         }
8997         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8998             // remove from controller if already present
8999             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9000         }  else {
9001             // directly remove entry from whitelist
9002             btstack_linked_list_iterator_remove(&it);
9003             btstack_memory_periodic_advertiser_list_entry_free(entry);
9004         }
9005         return ERROR_CODE_SUCCESS;
9006     }
9007     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9008 }
9009 
9010 static void hci_periodic_advertiser_list_clear(void){
9011     btstack_linked_list_iterator_t it;
9012     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9013     while (btstack_linked_list_iterator_has_next(&it)){
9014         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9015         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9016             // remove from controller if already present
9017             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9018             continue;
9019         }
9020         // directly remove entry from whitelist
9021         btstack_linked_list_iterator_remove(&it);
9022         btstack_memory_periodic_advertiser_list_entry_free(entry);
9023     }
9024 }
9025 
9026 // free all entries unconditionally
9027 static void hci_periodic_advertiser_list_free(void){
9028     btstack_linked_list_iterator_t lit;
9029     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
9030     while (btstack_linked_list_iterator_has_next(&lit)){
9031         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
9032         btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
9033         btstack_memory_periodic_advertiser_list_entry_free(entry);
9034     }
9035 }
9036 
9037 uint8_t gap_periodic_advertiser_list_clear(void){
9038     hci_periodic_advertiser_list_clear();
9039     hci_run();
9040     return ERROR_CODE_SUCCESS;
9041 }
9042 
9043 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9044     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
9045     if (status){
9046         return status;
9047     }
9048     hci_run();
9049     return ERROR_CODE_SUCCESS;
9050 }
9051 
9052 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9053     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
9054     if (status){
9055         return status;
9056     }
9057     hci_run();
9058     return ERROR_CODE_SUCCESS;
9059 }
9060 
9061 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
9062                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
9063     // abort if already active
9064     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
9065         return ERROR_CODE_COMMAND_DISALLOWED;
9066     }
9067     // store request
9068     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
9069     hci_stack->le_periodic_sync_options = options;
9070     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
9071     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
9072     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
9073     hci_stack->le_periodic_sync_skip = skip;
9074     hci_stack->le_periodic_sync_timeout = sync_timeout;
9075     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
9076 
9077     hci_run();
9078     return ERROR_CODE_SUCCESS;
9079 }
9080 
9081 uint8_t gap_periodic_advertising_create_sync_cancel(void){
9082     // abort if not requested
9083     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
9084         return ERROR_CODE_COMMAND_DISALLOWED;
9085     }
9086     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
9087     hci_run();
9088     return ERROR_CODE_SUCCESS;
9089 }
9090 
9091 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
9092     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
9093         return ERROR_CODE_COMMAND_DISALLOWED;
9094     }
9095     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
9096     hci_run();
9097     return ERROR_CODE_SUCCESS;
9098 }
9099 
9100 #endif
9101 #endif
9102 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
9103 static uint8_t hci_iso_stream_create(hci_iso_type_t iso_type, hci_con_handle_t con_handle, uint8_t group_id) {
9104     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
9105     if (iso_stream == NULL){
9106         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
9107     } else {
9108         iso_stream->iso_type = iso_type;
9109         iso_stream->state = HCI_ISO_STREAM_STATE_REQUESTED;
9110         iso_stream->con_handle = con_handle;
9111         iso_stream->group_id = group_id;
9112         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
9113         return ERROR_CODE_SUCCESS;
9114     }
9115 }
9116 
9117 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
9118     btstack_linked_list_iterator_t it;
9119     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9120     while (btstack_linked_list_iterator_has_next(&it)){
9121         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9122         if (iso_stream->con_handle == con_handle ) {
9123             return iso_stream;
9124         }
9125     }
9126     return NULL;
9127 }
9128 
9129 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
9130     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->con_handle, iso_stream->group_id);
9131     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
9132     btstack_memory_hci_iso_stream_free(iso_stream);
9133 }
9134 
9135 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
9136     btstack_linked_list_iterator_t it;
9137     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9138     while (btstack_linked_list_iterator_has_next(&it)){
9139         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9140         if ((iso_stream->group_id == group_id) &&
9141             (iso_stream->iso_type == iso_type)){
9142             btstack_linked_list_iterator_remove(&it);
9143             btstack_memory_hci_iso_stream_free(iso_stream);
9144         }
9145     }
9146 }
9147 
9148 static void hci_iso_stream_requested_finalize(uint8_t group_id) {
9149     btstack_linked_list_iterator_t it;
9150     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9151     while (btstack_linked_list_iterator_has_next(&it)){
9152         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9153         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
9154             (iso_stream->group_id == group_id)){
9155             btstack_linked_list_iterator_remove(&it);
9156             btstack_memory_hci_iso_stream_free(iso_stream);
9157         }
9158     }
9159 }
9160 static void hci_iso_stream_requested_confirm(uint8_t big_handle){
9161     btstack_linked_list_iterator_t it;
9162     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9163     while (btstack_linked_list_iterator_has_next(&it)){
9164         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9165         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
9166             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
9167         }
9168     }
9169 }
9170 
9171 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
9172     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
9173     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
9174     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
9175     return (sdu_len_offset + 2 + sdu_len) == size;
9176 }
9177 
9178 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){
9179     if (hci_stack->iso_packet_handler == NULL) {
9180         return;
9181     }
9182     if (size < 4) {
9183         return;
9184     }
9185 
9186     // parse header
9187     uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0);
9188     uint16_t iso_data_len = little_endian_read_16(packet, 2);
9189     hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff);
9190     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
9191     uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3;
9192 
9193     // assert packet is complete
9194     if ((iso_data_len + 4u) != size){
9195         return;
9196     }
9197 
9198     if ((pb_flag & 0x01) == 0){
9199         if (pb_flag == 0x02){
9200             // The ISO_Data_Load field contains a header and a complete SDU.
9201             if (hci_iso_sdu_complete(packet, size)) {
9202                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
9203             }
9204         } else {
9205             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
9206             if (iso_stream == NULL){
9207                 return;
9208             }
9209             if (size > HCI_ISO_PAYLOAD_SIZE){
9210                 return;
9211             }
9212             memcpy(iso_stream->reassembly_buffer, packet, size);
9213             // fix pb_flag
9214             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
9215             iso_stream->reassembly_pos = size;
9216         }
9217     } else {
9218         // iso_data_load contains continuation or last fragment of an SDU
9219         uint8_t  ts_flag = (conn_handle_and_flags >> 14) & 1;
9220         if (ts_flag != 0){
9221            return;
9222         }
9223         // append fragment
9224         if (iso_stream == NULL){
9225             return;
9226         }
9227         if (iso_stream->reassembly_pos == 0){
9228             return;
9229         }
9230         if ((iso_stream->reassembly_pos + iso_data_len) > size){
9231             // reset reassembly buffer
9232             iso_stream->reassembly_pos = 0;
9233             return;
9234         }
9235         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len);
9236         iso_stream->reassembly_pos += iso_data_len;
9237 
9238         // deliver if last fragment and SDU complete
9239         if (pb_flag == 0x03){
9240             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
9241                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
9242             }
9243             iso_stream->reassembly_pos = 0;
9244         }
9245     }
9246 }
9247 
9248 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
9249     uint8_t event [6 + (MAX_NR_BIS * 2)];
9250     uint16_t pos = 0;
9251     event[pos++] = HCI_EVENT_META_GAP;
9252     event[pos++] = 4 + (2 * big->num_bis);
9253     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
9254     event[pos++] = status;
9255     event[pos++] = big->big_handle;
9256     event[pos++] = big->num_bis;
9257     uint8_t i;
9258     for (i=0;i<big->num_bis;i++){
9259         little_endian_store_16(event, pos, big->bis_con_handles[i]);
9260         pos += 2;
9261     }
9262     hci_emit_event(event, pos, 0);
9263 }
9264 
9265 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
9266     uint8_t event [6 + (MAX_NR_CIS * 2)];
9267     uint16_t pos = 0;
9268     event[pos++] = HCI_EVENT_META_GAP;
9269     event[pos++] = 4 + (2 * cig->num_cis);
9270     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
9271     event[pos++] = status;
9272     event[pos++] = cig->cig_id;
9273     event[pos++] = cig->num_cis;
9274     uint8_t i;
9275     for (i=0;i<cig->num_cis;i++){
9276         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
9277         pos += 2;
9278     }
9279     hci_emit_event(event, pos, 0);
9280 }
9281 
9282 static void
9283 hci_emit_cis_created(uint8_t cig_id, hci_con_handle_t cis_con_handle, uint8_t status) {
9284     uint8_t event [7];
9285     uint16_t pos = 0;
9286     event[pos++] = HCI_EVENT_META_GAP;
9287     event[pos++] = 5;
9288     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
9289     event[pos++] = status;
9290     event[pos++] = cig_id;
9291     little_endian_store_16(event, pos, cis_con_handle);
9292     pos += 2;
9293     hci_emit_event(event, pos, 0);
9294 }
9295 
9296 static void hci_emit_big_terminated(const le_audio_big_t * big){
9297     uint8_t event [4];
9298     uint16_t pos = 0;
9299     event[pos++] = HCI_EVENT_META_GAP;
9300     event[pos++] = 2;
9301     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
9302     event[pos++] = big->big_handle;
9303     hci_emit_event(event, pos, 0);
9304 }
9305 
9306 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
9307     uint8_t event [6 + (MAX_NR_BIS * 2)];
9308     uint16_t pos = 0;
9309     event[pos++] = HCI_EVENT_META_GAP;
9310     event[pos++] = 4;
9311     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
9312     event[pos++] = status;
9313     event[pos++] = big_sync->big_handle;
9314     event[pos++] = big_sync->num_bis;
9315     uint8_t i;
9316     for (i=0;i<big_sync->num_bis;i++){
9317         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
9318         pos += 2;
9319     }
9320     hci_emit_event(event, pos, 0);
9321 }
9322 
9323 static void hci_emit_big_sync_stopped(uint8_t big_handle){
9324     uint8_t event [4];
9325     uint16_t pos = 0;
9326     event[pos++] = HCI_EVENT_META_GAP;
9327     event[pos++] = 2;
9328     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
9329     event[pos++] = big_handle;
9330     hci_emit_event(event, pos, 0);
9331 }
9332 
9333 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
9334     uint8_t event[6];
9335     uint16_t pos = 0;
9336     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
9337     event[pos++] = sizeof(event) - 2;
9338     event[pos++] = big->big_handle;
9339     event[pos++] = bis_index;
9340     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
9341     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
9342 }
9343 
9344 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
9345     btstack_linked_list_iterator_t it;
9346     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9347     while (btstack_linked_list_iterator_has_next(&it)){
9348         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9349         if ( big->big_handle == big_handle ) {
9350             return big;
9351         }
9352     }
9353     return NULL;
9354 }
9355 
9356 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
9357     btstack_linked_list_iterator_t it;
9358     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
9359     while (btstack_linked_list_iterator_has_next(&it)){
9360         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
9361         if ( big_sync->big_handle == big_handle ) {
9362             return big_sync;
9363         }
9364     }
9365     return NULL;
9366 }
9367 
9368 void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
9369     hci_stack->iso_packets_to_queue = num_packets;
9370 }
9371 
9372 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
9373     btstack_linked_list_iterator_t it;
9374     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
9375     while (btstack_linked_list_iterator_has_next(&it)){
9376         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
9377         if ( cig->cig_id == cig_id ) {
9378             return cig;
9379         }
9380     }
9381     return NULL;
9382 }
9383 
9384 static void hci_iso_notify_can_send_now(void){
9385     btstack_linked_list_iterator_t it;
9386     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9387     while (btstack_linked_list_iterator_has_next(&it)){
9388         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9389         // track number completed packet timestamps
9390         if (big->num_completed_timestamp_current_valid){
9391             big->num_completed_timestamp_current_valid = false;
9392             if (big->num_completed_timestamp_previous_valid){
9393                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
9394                 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
9395                 int32_t  num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
9396                                                                                big->num_completed_timestamp_previous_ms);
9397                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
9398                     // to catch up, skip packet on all BIS
9399                     uint8_t i;
9400                     for (i=0;i<big->num_bis;i++){
9401                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9402                         if (iso_stream){
9403                             iso_stream->num_packets_to_skip++;
9404                         }
9405                     }
9406                 }
9407             }
9408             big->num_completed_timestamp_previous_valid = true;
9409             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
9410         }
9411 
9412         if (big->can_send_now_requested){
9413             // check if no outgoing iso packets pending and no can send now have to be emitted
9414             uint8_t i;
9415             bool can_send = true;
9416             uint8_t num_iso_queued_minimum = 0;
9417             for (i=0;i<big->num_bis;i++){
9418                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9419                 if (iso_stream == NULL) continue;
9420                 // handle case where individual ISO packet was sent too late:
9421                 // for each additionally queued packet, a new one needs to get skipped
9422                 if (i==0){
9423                     num_iso_queued_minimum = iso_stream->num_packets_sent;
9424                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
9425                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
9426                     iso_stream->num_packets_to_skip += num_packets_to_skip;
9427                     iso_stream->num_packets_sent    -= num_packets_to_skip;
9428                 }
9429                 // check if we can send now
9430                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
9431                     can_send = false;
9432                     break;
9433                 }
9434             }
9435             if (can_send){
9436                 // propagate can send now to individual streams
9437                 big->can_send_now_requested = false;
9438                 for (i=0;i<big->num_bis;i++){
9439                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9440                     iso_stream->emit_ready_to_send = true;
9441                 }
9442             }
9443         }
9444     }
9445 
9446     if (hci_stack->hci_packet_buffer_reserved) return;
9447 
9448     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9449     while (btstack_linked_list_iterator_has_next(&it)){
9450         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9451         // report bis ready
9452         uint8_t i;
9453         for (i=0;i<big->num_bis;i++){
9454             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9455             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
9456                 iso_stream->emit_ready_to_send = false;
9457                 hci_emit_bis_can_send_now(big, i);
9458                 break;
9459             }
9460         }
9461     }
9462 }
9463 
9464 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
9465     if (hci_big_for_handle(big_params->big_handle) != NULL){
9466         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9467     }
9468     if (big_params->num_bis == 0){
9469         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9470     }
9471     if (big_params->num_bis > MAX_NR_BIS){
9472         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9473     }
9474 
9475     // reserve ISO Streams
9476     uint8_t i;
9477     uint8_t status = ERROR_CODE_SUCCESS;
9478     for (i=0;i<big_params->num_bis;i++){
9479         status = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_CON_HANDLE_INVALID, big_params->big_handle);
9480         if (status != ERROR_CODE_SUCCESS) {
9481             break;
9482         }
9483     }
9484 
9485     // free structs on error
9486     if (status != ERROR_CODE_SUCCESS){
9487         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_params->big_handle);
9488         return status;
9489     }
9490 
9491     le_audio_big_t * big = storage;
9492     big->big_handle = big_params->big_handle;
9493     big->params = big_params;
9494     big->state = LE_AUDIO_BIG_STATE_CREATE;
9495     big->num_bis = big_params->num_bis;
9496     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9497 
9498     hci_run();
9499 
9500     return ERROR_CODE_SUCCESS;
9501 }
9502 
9503 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
9504     if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){
9505         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9506     }
9507     if (big_sync_params->num_bis == 0){
9508         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9509     }
9510     if (big_sync_params->num_bis > MAX_NR_BIS){
9511         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9512     }
9513 
9514     le_audio_big_sync_t * big_sync = storage;
9515     big_sync->big_handle = big_sync_params->big_handle;
9516     big_sync->params = big_sync_params;
9517     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
9518     big_sync->num_bis = big_sync_params->num_bis;
9519     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9520 
9521     hci_run();
9522 
9523     return ERROR_CODE_SUCCESS;
9524 }
9525 
9526 uint8_t gap_big_terminate(uint8_t big_handle){
9527     le_audio_big_t * big = hci_big_for_handle(big_handle);
9528     if (big == NULL){
9529         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9530     }
9531     switch (big->state){
9532         case LE_AUDIO_BIG_STATE_CREATE:
9533             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9534             hci_emit_big_terminated(big);
9535             break;
9536         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9537             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9538             break;
9539         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9540         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9541         case LE_AUDIO_BIG_STATE_ACTIVE:
9542             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
9543             hci_run();
9544             break;
9545         default:
9546             return ERROR_CODE_COMMAND_DISALLOWED;
9547     }
9548     return ERROR_CODE_SUCCESS;
9549 }
9550 
9551 uint8_t gap_big_sync_terminate(uint8_t big_handle){
9552     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
9553     if (big_sync == NULL){
9554         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9555     }
9556     switch (big_sync->state){
9557         case LE_AUDIO_BIG_STATE_CREATE:
9558             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9559             hci_emit_big_sync_stopped(big_handle);
9560             break;
9561         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9562             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9563             break;
9564         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9565         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9566         case LE_AUDIO_BIG_STATE_ACTIVE:
9567             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
9568             hci_run();
9569             break;
9570         default:
9571             return ERROR_CODE_COMMAND_DISALLOWED;
9572     }
9573     return ERROR_CODE_SUCCESS;
9574 }
9575 
9576 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
9577     le_audio_big_t * big = hci_big_for_handle(big_handle);
9578     if (big == NULL){
9579         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9580     }
9581     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
9582         return ERROR_CODE_COMMAND_DISALLOWED;
9583     }
9584     big->can_send_now_requested = true;
9585     hci_iso_notify_can_send_now();
9586     return ERROR_CODE_SUCCESS;
9587 }
9588 
9589 uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
9590     if (hci_cig_for_id(cig_params->cig_id) != NULL){
9591         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9592     }
9593     if (cig_params->num_cis == 0){
9594         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9595     }
9596     if (cig_params->num_cis > MAX_NR_BIS){
9597         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9598     }
9599 
9600     // reserve ISO Streams
9601     uint8_t i;
9602     uint8_t status = ERROR_CODE_SUCCESS;
9603     for (i=0;i<cig_params->num_cis;i++){
9604         status = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_CON_HANDLE_INVALID, cig_params->cig_id);
9605         if (status != ERROR_CODE_SUCCESS) {
9606             break;
9607         }
9608     }
9609 
9610     // free structs on error
9611     if (status != ERROR_CODE_SUCCESS){
9612         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
9613         return status;
9614     }
9615 
9616     le_audio_cig_t * cig = storage;
9617     cig->cig_id = cig_params->cig_id;
9618     cig->num_cis = cig_params->num_cis;
9619     cig->params = cig_params;
9620     cig->state = LE_AUDIO_CIG_STATE_CREATE;
9621     for (i=0;i<cig->num_cis;i++){
9622         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
9623         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
9624     }
9625     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
9626 
9627     hci_run();
9628 
9629     return ERROR_CODE_SUCCESS;
9630 }
9631 
9632 uint8_t gap_cis_create(uint8_t cig_handle, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
9633     le_audio_cig_t * cig = hci_cig_for_id(cig_handle);
9634     if (cig == NULL){
9635         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9636     }
9637 
9638     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
9639         return ERROR_CODE_COMMAND_DISALLOWED;
9640     }
9641 
9642     // store ACL Connection Handles
9643     uint8_t i;
9644     for (i=0;i<cig->num_cis;i++){
9645         // check that all con handles exit
9646         hci_con_handle_t cis_handle = cis_con_handles[i];
9647         uint8_t j;
9648         bool found = false;
9649         for (j=0;j<cig->num_cis;j++){
9650             if (cig->cis_con_handles[j] == cis_handle){
9651                 cig->acl_con_handles[j] = acl_con_handles[j];
9652                 found = true;
9653                 break;
9654             }
9655         }
9656         if (!found){
9657             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9658         }
9659     }
9660 
9661     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
9662     hci_run();
9663 
9664     return ERROR_CODE_SUCCESS;
9665 }
9666 
9667 #endif
9668 #endif /* ENABLE_BLE */
9669 
9670 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
9671 void hci_setup_test_connections_fuzz(void){
9672     hci_connection_t * conn;
9673 
9674     // default address: 66:55:44:33:00:01
9675     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
9676 
9677     // setup Controller info
9678     hci_stack->num_cmd_packets = 255;
9679     hci_stack->acl_packets_total_num = 255;
9680 
9681     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
9682     addr[5] = 0x01;
9683     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9684     conn->con_handle = addr[5];
9685     conn->role  = HCI_ROLE_SLAVE;
9686     conn->state = RECEIVED_CONNECTION_REQUEST;
9687     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9688 
9689     // setup incoming Classic SCO connection with con handle 0x0002
9690     addr[5] = 0x02;
9691     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9692     conn->con_handle = addr[5];
9693     conn->role  = HCI_ROLE_SLAVE;
9694     conn->state = RECEIVED_CONNECTION_REQUEST;
9695     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9696 
9697     // setup ready Classic ACL connection with con handle 0x0003
9698     addr[5] = 0x03;
9699     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9700     conn->con_handle = addr[5];
9701     conn->role  = HCI_ROLE_SLAVE;
9702     conn->state = OPEN;
9703     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9704 
9705     // setup ready Classic SCO connection with con handle 0x0004
9706     addr[5] = 0x04;
9707     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9708     conn->con_handle = addr[5];
9709     conn->role  = HCI_ROLE_SLAVE;
9710     conn->state = OPEN;
9711     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9712 
9713     // setup ready LE ACL connection with con handle 0x005 and public address
9714     addr[5] = 0x05;
9715     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
9716     conn->con_handle = addr[5];
9717     conn->role  = HCI_ROLE_SLAVE;
9718     conn->state = OPEN;
9719     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9720     conn->sm_connection.sm_connection_encrypted = 1;
9721 }
9722 
9723 void hci_free_connections_fuzz(void){
9724     btstack_linked_list_iterator_t it;
9725     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9726     while (btstack_linked_list_iterator_has_next(&it)){
9727         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9728         btstack_linked_list_iterator_remove(&it);
9729         btstack_memory_hci_connection_free(con);
9730     }
9731 }
9732 void hci_simulate_working_fuzz(void){
9733     hci_stack->le_scanning_param_update = false;
9734     hci_init_done();
9735     hci_stack->num_cmd_packets = 255;
9736 }
9737 #endif
9738