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