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