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