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