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