xref: /btstack/src/hci.c (revision d4e5d4fa6be260ce9b0eeb2b112db27adaf747ba)
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     hci_state_reset();
4388 }
4389 
4390 void hci_deinit(void){
4391     btstack_run_loop_remove_timer(&hci_stack->timeout);
4392 #ifdef HAVE_MALLOC
4393     if (hci_stack) {
4394         free(hci_stack);
4395     }
4396 #endif
4397     hci_stack = NULL;
4398 
4399 #ifdef ENABLE_CLASSIC
4400     disable_l2cap_timeouts = 0;
4401 #endif
4402 }
4403 
4404 /**
4405  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
4406  */
4407 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
4408     hci_stack->chipset = chipset_driver;
4409 
4410     // reset chipset driver - init is also called on power_up
4411     if (hci_stack->chipset && hci_stack->chipset->init){
4412         hci_stack->chipset->init(hci_stack->config);
4413     }
4414 }
4415 
4416 /**
4417  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
4418  */
4419 void hci_set_control(const btstack_control_t *hardware_control){
4420     // references to used control implementation
4421     hci_stack->control = hardware_control;
4422     // init with transport config
4423     hardware_control->init(hci_stack->config);
4424 }
4425 
4426 static void hci_discard_connections(void){
4427     btstack_linked_list_iterator_t it;
4428     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4429     while (btstack_linked_list_iterator_has_next(&it)){
4430         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
4431         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4432         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
4433         hci_shutdown_connection(connection);
4434     }
4435 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4436     while (hci_stack->iso_streams != NULL){
4437         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
4438     }
4439 #endif
4440 }
4441 
4442 void hci_close(void){
4443 
4444 #ifdef ENABLE_CLASSIC
4445     // close remote device db
4446     if (hci_stack->link_key_db) {
4447         hci_stack->link_key_db->close();
4448     }
4449 #endif
4450 
4451     hci_discard_connections();
4452 
4453     hci_power_control(HCI_POWER_OFF);
4454 
4455 #ifdef HAVE_MALLOC
4456     free(hci_stack);
4457 #endif
4458     hci_stack = NULL;
4459 }
4460 
4461 #ifdef HAVE_SCO_TRANSPORT
4462 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
4463     hci_stack->sco_transport = sco_transport;
4464     sco_transport->register_packet_handler(&packet_handler);
4465 }
4466 #endif
4467 
4468 #ifdef ENABLE_CLASSIC
4469 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
4470     // validate ranage and set
4471     if (encryption_key_size < 7)  return;
4472     if (encryption_key_size > 16) return;
4473     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
4474 }
4475 
4476 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
4477     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
4478         hci_stack->gap_security_mode = security_mode;
4479         return ERROR_CODE_SUCCESS;
4480     } else {
4481         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
4482     }
4483 }
4484 
4485 gap_security_mode_t gap_get_security_mode(void){
4486     return hci_stack->gap_security_mode;
4487 }
4488 
4489 void gap_set_security_level(gap_security_level_t security_level){
4490     hci_stack->gap_security_level = security_level;
4491 }
4492 
4493 gap_security_level_t gap_get_security_level(void){
4494     if (hci_stack->gap_secure_connections_only_mode){
4495         return LEVEL_4;
4496     }
4497     return hci_stack->gap_security_level;
4498 }
4499 
4500 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
4501     hci_stack->gap_minimal_service_security_level = security_level;
4502 }
4503 
4504 void gap_set_secure_connections_only_mode(bool enable){
4505     hci_stack->gap_secure_connections_only_mode = enable;
4506 }
4507 
4508 bool gap_get_secure_connections_only_mode(void){
4509     return hci_stack->gap_secure_connections_only_mode;
4510 }
4511 #endif
4512 
4513 #ifdef ENABLE_CLASSIC
4514 void gap_set_class_of_device(uint32_t class_of_device){
4515     hci_stack->class_of_device = class_of_device;
4516     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
4517     hci_run();
4518 }
4519 
4520 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4521     hci_stack->default_link_policy_settings = default_link_policy_settings;
4522     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
4523     hci_run();
4524 }
4525 
4526 void gap_set_allow_role_switch(bool allow_role_switch){
4527     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4528 }
4529 
4530 uint8_t hci_get_allow_role_switch(void){
4531     return  hci_stack->allow_role_switch;
4532 }
4533 
4534 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
4535     hci_stack->link_supervision_timeout = link_supervision_timeout;
4536 }
4537 
4538 void gap_enable_link_watchdog(uint16_t timeout_ms){
4539     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
4540 }
4541 
4542 uint16_t hci_automatic_flush_timeout(void){
4543     return hci_stack->automatic_flush_timeout;
4544 }
4545 
4546 void hci_disable_l2cap_timeout_check(void){
4547     disable_l2cap_timeouts = 1;
4548 }
4549 #endif
4550 
4551 #ifndef HAVE_HOST_CONTROLLER_API
4552 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4553 void hci_set_bd_addr(bd_addr_t addr){
4554     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4555     hci_stack->custom_bd_addr_set = 1;
4556 }
4557 #endif
4558 
4559 // State-Module-Driver overview
4560 // state                    module  low-level
4561 // HCI_STATE_OFF             off      close
4562 // HCI_STATE_INITIALIZING,   on       open
4563 // HCI_STATE_WORKING,        on       open
4564 // HCI_STATE_HALTING,        on       open
4565 // HCI_STATE_SLEEPING,    off/sleep   close
4566 // HCI_STATE_FALLING_ASLEEP  on       open
4567 
4568 static int hci_power_control_on(void){
4569 
4570     // power on
4571     int err = 0;
4572     if (hci_stack->control && hci_stack->control->on){
4573         err = (*hci_stack->control->on)();
4574     }
4575     if (err){
4576         log_error( "POWER_ON failed");
4577         hci_emit_hci_open_failed();
4578         return err;
4579     }
4580 
4581     // int chipset driver
4582     if (hci_stack->chipset && hci_stack->chipset->init){
4583         hci_stack->chipset->init(hci_stack->config);
4584     }
4585 
4586     // init transport
4587     if (hci_stack->hci_transport->init){
4588         hci_stack->hci_transport->init(hci_stack->config);
4589     }
4590 
4591     // open transport
4592     err = hci_stack->hci_transport->open();
4593     if (err){
4594         log_error( "HCI_INIT failed, turning Bluetooth off again");
4595         if (hci_stack->control && hci_stack->control->off){
4596             (*hci_stack->control->off)();
4597         }
4598         hci_emit_hci_open_failed();
4599         return err;
4600     }
4601     return 0;
4602 }
4603 
4604 static void hci_power_control_off(void){
4605 
4606     log_info("hci_power_control_off");
4607 
4608     // close low-level device
4609     hci_stack->hci_transport->close();
4610 
4611     log_info("hci_power_control_off - hci_transport closed");
4612 
4613     // power off
4614     if (hci_stack->control && hci_stack->control->off){
4615         (*hci_stack->control->off)();
4616     }
4617 
4618     log_info("hci_power_control_off - control closed");
4619 
4620     hci_stack->state = HCI_STATE_OFF;
4621 }
4622 
4623 static void hci_power_control_sleep(void){
4624 
4625     log_info("hci_power_control_sleep");
4626 
4627 #if 0
4628     // don't close serial port during sleep
4629 
4630     // close low-level device
4631     hci_stack->hci_transport->close(hci_stack->config);
4632 #endif
4633 
4634     // sleep mode
4635     if (hci_stack->control && hci_stack->control->sleep){
4636         (*hci_stack->control->sleep)();
4637     }
4638 
4639     hci_stack->state = HCI_STATE_SLEEPING;
4640 }
4641 
4642 static int hci_power_control_wake(void){
4643 
4644     log_info("hci_power_control_wake");
4645 
4646     // wake on
4647     if (hci_stack->control && hci_stack->control->wake){
4648         (*hci_stack->control->wake)();
4649     }
4650 
4651 #if 0
4652     // open low-level device
4653     int err = hci_stack->hci_transport->open(hci_stack->config);
4654     if (err){
4655         log_error( "HCI_INIT failed, turning Bluetooth off again");
4656         if (hci_stack->control && hci_stack->control->off){
4657             (*hci_stack->control->off)();
4658         }
4659         hci_emit_hci_open_failed();
4660         return err;
4661     }
4662 #endif
4663 
4664     return 0;
4665 }
4666 
4667 static void hci_power_enter_initializing_state(void){
4668     // set up state machine
4669     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
4670     hci_stack->hci_packet_buffer_reserved = false;
4671     hci_stack->state = HCI_STATE_INITIALIZING;
4672     hci_stack->substate = HCI_INIT_SEND_RESET;
4673 }
4674 
4675 static void hci_power_enter_halting_state(void){
4676 #ifdef ENABLE_BLE
4677     hci_whitelist_free();
4678 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4679     hci_periodic_advertiser_list_free();
4680 #endif
4681 #endif
4682     // see hci_run
4683     hci_stack->state = HCI_STATE_HALTING;
4684     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
4685     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
4686     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
4687     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4688     btstack_run_loop_add_timer(&hci_stack->timeout);
4689 }
4690 
4691 // returns error
4692 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
4693     int err;
4694     switch (power_mode){
4695         case HCI_POWER_ON:
4696             err = hci_power_control_on();
4697             if (err != 0) {
4698                 log_error("hci_power_control_on() error %d", err);
4699                 return err;
4700             }
4701             hci_power_enter_initializing_state();
4702             break;
4703         case HCI_POWER_OFF:
4704             // do nothing
4705             break;
4706         case HCI_POWER_SLEEP:
4707             // do nothing (with SLEEP == OFF)
4708             break;
4709         default:
4710             btstack_assert(false);
4711             break;
4712     }
4713     return ERROR_CODE_SUCCESS;
4714 }
4715 
4716 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
4717     switch (power_mode){
4718         case HCI_POWER_ON:
4719             // do nothing
4720             break;
4721         case HCI_POWER_OFF:
4722             // no connections yet, just turn it off
4723             hci_power_control_off();
4724             break;
4725         case HCI_POWER_SLEEP:
4726             // no connections yet, just turn it off
4727             hci_power_control_sleep();
4728             break;
4729         default:
4730             btstack_assert(false);
4731             break;
4732     }
4733     return ERROR_CODE_SUCCESS;
4734 }
4735 
4736 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
4737     switch (power_mode){
4738         case HCI_POWER_ON:
4739             // do nothing
4740             break;
4741         case HCI_POWER_OFF:
4742             hci_power_enter_halting_state();
4743             break;
4744         case HCI_POWER_SLEEP:
4745             // see hci_run
4746             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4747             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4748             break;
4749         default:
4750             btstack_assert(false);
4751             break;
4752     }
4753     return ERROR_CODE_SUCCESS;
4754 }
4755 
4756 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
4757     switch (power_mode){
4758         case HCI_POWER_ON:
4759             hci_power_enter_initializing_state();
4760             break;
4761         case HCI_POWER_OFF:
4762             // do nothing
4763             break;
4764         case HCI_POWER_SLEEP:
4765             // see hci_run
4766             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4767             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4768             break;
4769         default:
4770             btstack_assert(false);
4771             break;
4772     }
4773     return ERROR_CODE_SUCCESS;
4774 }
4775 
4776 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
4777     switch (power_mode){
4778         case HCI_POWER_ON:
4779             hci_power_enter_initializing_state();
4780             break;
4781         case HCI_POWER_OFF:
4782             hci_power_enter_halting_state();
4783             break;
4784         case HCI_POWER_SLEEP:
4785             // do nothing
4786             break;
4787         default:
4788             btstack_assert(false);
4789             break;
4790     }
4791     return ERROR_CODE_SUCCESS;
4792 }
4793 
4794 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
4795     int err;
4796     switch (power_mode){
4797         case HCI_POWER_ON:
4798             err = hci_power_control_wake();
4799             if (err) return err;
4800             hci_power_enter_initializing_state();
4801             break;
4802         case HCI_POWER_OFF:
4803             hci_power_enter_halting_state();
4804             break;
4805         case HCI_POWER_SLEEP:
4806             // do nothing
4807             break;
4808         default:
4809             btstack_assert(false);
4810             break;
4811     }
4812     return ERROR_CODE_SUCCESS;
4813 }
4814 
4815 int hci_power_control(HCI_POWER_MODE power_mode){
4816     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
4817     int err = 0;
4818     switch (hci_stack->state){
4819         case HCI_STATE_OFF:
4820             err = hci_power_control_state_off(power_mode);
4821             break;
4822         case HCI_STATE_INITIALIZING:
4823             err = hci_power_control_state_initializing(power_mode);
4824             break;
4825         case HCI_STATE_WORKING:
4826             err = hci_power_control_state_working(power_mode);
4827             break;
4828         case HCI_STATE_HALTING:
4829             err = hci_power_control_state_halting(power_mode);
4830             break;
4831         case HCI_STATE_FALLING_ASLEEP:
4832             err = hci_power_control_state_falling_asleep(power_mode);
4833             break;
4834         case HCI_STATE_SLEEPING:
4835             err = hci_power_control_state_sleeping(power_mode);
4836             break;
4837         default:
4838             btstack_assert(false);
4839             break;
4840     }
4841     if (err != 0){
4842         return err;
4843     }
4844 
4845     // create internal event
4846 	hci_emit_state();
4847 
4848 	// trigger next/first action
4849 	hci_run();
4850 
4851     return 0;
4852 }
4853 
4854 
4855 static void hci_halting_run(void) {
4856 
4857     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4858 
4859     hci_connection_t *connection;
4860 #ifdef ENABLE_BLE
4861 #ifdef ENABLE_LE_PERIPHERAL
4862     bool stop_advertismenets;
4863 #endif
4864 #endif
4865 
4866     switch (hci_stack->substate) {
4867         case HCI_HALTING_CLASSIC_STOP:
4868 #ifdef ENABLE_CLASSIC
4869             if (!hci_can_send_command_packet_now()) return;
4870 
4871             if (hci_stack->connectable || hci_stack->discoverable){
4872                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4873                 hci_send_cmd(&hci_write_scan_enable, 0);
4874                 return;
4875             }
4876 #endif
4877             /* fall through */
4878 
4879         case HCI_HALTING_LE_ADV_STOP:
4880             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4881 
4882 #ifdef ENABLE_BLE
4883 #ifdef ENABLE_LE_PERIPHERAL
4884             if (!hci_can_send_command_packet_now()) return;
4885 
4886             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
4887 
4888 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4889             if (hci_extended_advertising_supported()){
4890 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4891                 btstack_linked_list_iterator_t it;
4892                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4893                 // stop all periodic advertisements and check if an extended set is active
4894                 while (btstack_linked_list_iterator_has_next(&it)){
4895                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4896                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
4897                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
4898                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
4899                         return;
4900                     }
4901                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
4902                         stop_advertismenets = true;
4903                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4904                     }
4905                 }
4906 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
4907                 if (stop_advertismenets){
4908                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4909                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
4910                     return;
4911                 }
4912             }
4913             else
4914 #else /* ENABLE_LE_PERIPHERAL */
4915             {
4916                 if (stop_advertismenets) {
4917                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4918                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
4919                     return;
4920                 }
4921             }
4922 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
4923 #endif  /* ENABLE_LE_PERIPHERAL */
4924 #endif  /* ENABLE_BLE */
4925 
4926             /* fall through */
4927 
4928         case HCI_HALTING_LE_SCAN_STOP:
4929             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
4930             if (!hci_can_send_command_packet_now()) return;
4931 
4932 #ifdef ENABLE_BLE
4933 #ifdef ENABLE_LE_CENTRAL
4934             if (hci_stack->le_scanning_active){
4935                 hci_le_scan_stop();
4936                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4937                 return;
4938             }
4939 #endif
4940 #endif
4941 
4942             /* fall through */
4943 
4944         case HCI_HALTING_DISCONNECT_ALL:
4945             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4946             if (!hci_can_send_command_packet_now()) return;
4947 
4948             // close all open connections
4949             connection = (hci_connection_t *) hci_stack->connections;
4950             if (connection) {
4951                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4952 
4953                 // check state
4954                 if (connection->state == SENT_DISCONNECT) return;
4955                 connection->state = SENT_DISCONNECT;
4956 
4957                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4958 
4959                 // finally, send the disconnect command
4960                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4961                 return;
4962             }
4963 
4964 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4965             // stop BIGs and BIG Syncs
4966             if (hci_stack->le_audio_bigs != NULL){
4967                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
4968                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
4969                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
4970                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
4971                 return;
4972             }
4973             if (hci_stack->le_audio_big_syncs != NULL){
4974                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
4975                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
4976                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
4977                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
4978                 return;
4979             }
4980 #endif
4981 
4982             btstack_run_loop_remove_timer(&hci_stack->timeout);
4983 
4984             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4985             log_info("HCI_STATE_HALTING: wait 50 ms");
4986             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
4987             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
4988             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4989             btstack_run_loop_add_timer(&hci_stack->timeout);
4990             break;
4991 
4992         case HCI_HALTING_CLOSE:
4993             // close left over connections (that had not been properly closed before)
4994             hci_discard_connections();
4995 
4996             log_info("HCI_STATE_HALTING, calling off");
4997 
4998             // switch mode
4999             hci_power_control_off();
5000 
5001             log_info("HCI_STATE_HALTING, emitting state");
5002             hci_emit_state();
5003             log_info("HCI_STATE_HALTING, done");
5004             break;
5005 
5006         case HCI_HALTING_W4_CLOSE_TIMER:
5007             // keep waiting
5008 
5009             break;
5010         default:
5011             break;
5012     }
5013 };
5014 
5015 static void hci_falling_asleep_run(void){
5016     hci_connection_t * connection;
5017     switch(hci_stack->substate) {
5018         case HCI_FALLING_ASLEEP_DISCONNECT:
5019             log_info("HCI_STATE_FALLING_ASLEEP");
5020             // close all open connections
5021             connection =  (hci_connection_t *) hci_stack->connections;
5022             if (connection){
5023 
5024                 // send disconnect
5025                 if (!hci_can_send_command_packet_now()) return;
5026 
5027                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5028                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5029 
5030                 // send disconnected event right away - causes higher layer connections to get closed, too.
5031                 hci_shutdown_connection(connection);
5032                 return;
5033             }
5034 
5035             if (hci_classic_supported()){
5036                 // disable page and inquiry scan
5037                 if (!hci_can_send_command_packet_now()) return;
5038 
5039                 log_info("HCI_STATE_HALTING, disabling inq scans");
5040                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5041 
5042                 // continue in next sub state
5043                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5044                 break;
5045             }
5046 
5047             /* fall through */
5048 
5049             case HCI_FALLING_ASLEEP_COMPLETE:
5050                 log_info("HCI_STATE_HALTING, calling sleep");
5051                 // switch mode
5052                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5053                 hci_emit_state();
5054                 break;
5055 
5056                 default:
5057                     break;
5058     }
5059 }
5060 
5061 #ifdef ENABLE_CLASSIC
5062 
5063 static void hci_update_scan_enable(void){
5064     // 2 = page scan, 1 = inq scan
5065     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5066     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5067     hci_run();
5068 }
5069 
5070 void gap_discoverable_control(uint8_t enable){
5071     if (enable) enable = 1; // normalize argument
5072 
5073     if (hci_stack->discoverable == enable){
5074         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5075         return;
5076     }
5077 
5078     hci_stack->discoverable = enable;
5079     hci_update_scan_enable();
5080 }
5081 
5082 void gap_connectable_control(uint8_t enable){
5083     if (enable) enable = 1; // normalize argument
5084 
5085     // don't emit event
5086     if (hci_stack->connectable == enable) return;
5087 
5088     hci_stack->connectable = enable;
5089     hci_update_scan_enable();
5090 }
5091 #endif
5092 
5093 void gap_local_bd_addr(bd_addr_t address_buffer){
5094     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5095 }
5096 
5097 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5098 static void hci_host_num_completed_packets(void){
5099 
5100     // create packet manually as arrays are not supported and num_commands should not get reduced
5101     hci_reserve_packet_buffer();
5102     uint8_t * packet = hci_get_outgoing_packet_buffer();
5103 
5104     uint16_t size = 0;
5105     uint16_t num_handles = 0;
5106     packet[size++] = 0x35;
5107     packet[size++] = 0x0c;
5108     size++;  // skip param len
5109     size++;  // skip num handles
5110 
5111     // add { handle, packets } entries
5112     btstack_linked_item_t * it;
5113     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5114         hci_connection_t * connection = (hci_connection_t *) it;
5115         if (connection->num_packets_completed){
5116             little_endian_store_16(packet, size, connection->con_handle);
5117             size += 2;
5118             little_endian_store_16(packet, size, connection->num_packets_completed);
5119             size += 2;
5120             //
5121             num_handles++;
5122             connection->num_packets_completed = 0;
5123         }
5124     }
5125 
5126     packet[2] = size - 3;
5127     packet[3] = num_handles;
5128 
5129     hci_stack->host_completed_packets = 0;
5130 
5131     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5132     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5133 
5134     // release packet buffer for synchronous transport implementations
5135     if (hci_transport_synchronous()){
5136         hci_release_packet_buffer();
5137         hci_emit_transport_packet_sent();
5138     }
5139 }
5140 #endif
5141 
5142 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5143     UNUSED(ds);
5144     hci_stack->substate = HCI_HALTING_CLOSE;
5145     // allow packet handlers to defer final shutdown
5146     hci_emit_state();
5147     hci_run();
5148 }
5149 
5150 static bool hci_run_acl_fragments(void){
5151     if (hci_stack->acl_fragmentation_total_size > 0u) {
5152         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5153         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5154         if (connection) {
5155             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5156                 hci_send_acl_packet_fragments(connection);
5157                 return true;
5158             }
5159         } else {
5160             // connection gone -> discard further fragments
5161             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5162             hci_stack->acl_fragmentation_total_size = 0;
5163             hci_stack->acl_fragmentation_pos = 0;
5164         }
5165     }
5166     return false;
5167 }
5168 
5169 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5170 static bool hci_run_iso_fragments(void){
5171     if (hci_stack->iso_fragmentation_total_size > 0u) {
5172         // TODO: flow control
5173         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5174             hci_send_iso_packet_fragments();
5175             return true;
5176         }
5177     }
5178     return false;
5179 }
5180 #endif
5181 
5182 #ifdef ENABLE_CLASSIC
5183 
5184 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5185 static bool hci_classic_operation_active(void) {
5186     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5187         return true;
5188     }
5189     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5190         return true;
5191     }
5192     btstack_linked_item_t * it;
5193     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5194         hci_connection_t *connection = (hci_connection_t *) it;
5195         switch (connection->state) {
5196             case SENT_CREATE_CONNECTION:
5197             case SENT_CANCEL_CONNECTION:
5198             case SENT_DISCONNECT:
5199                 return true;
5200             default:
5201                 break;
5202         }
5203     }
5204     return false;
5205 }
5206 #endif
5207 
5208 static bool hci_run_general_gap_classic(void){
5209 
5210     // assert stack is working and classic is active
5211     if (hci_classic_supported() == false)      return false;
5212     if (hci_stack->state != HCI_STATE_WORKING) return false;
5213 
5214     // decline incoming connections
5215     if (hci_stack->decline_reason){
5216         uint8_t reason = hci_stack->decline_reason;
5217         hci_stack->decline_reason = 0;
5218         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5219         return true;
5220     }
5221 
5222     if (hci_stack->gap_tasks_classic != 0){
5223         hci_run_gap_tasks_classic();
5224         return true;
5225     }
5226 
5227     // start/stop inquiry
5228     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5229 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5230         if (hci_classic_operation_active() == false)
5231 #endif
5232         {
5233             uint8_t duration = hci_stack->inquiry_state;
5234             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5235             if (hci_stack->inquiry_max_period_length != 0){
5236                 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);
5237             } else {
5238                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5239             }
5240             return true;
5241         }
5242     }
5243     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5244         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5245         hci_send_cmd(&hci_inquiry_cancel);
5246         return true;
5247     }
5248 
5249     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5250         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5251         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5252         return true;
5253     }
5254 
5255     // remote name request
5256     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5257 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5258         if (hci_classic_operation_active() == false)
5259 #endif
5260         {
5261             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5262             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5263                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5264             return true;
5265         }
5266     }
5267 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5268     // Local OOB data
5269     if (hci_stack->classic_read_local_oob_data){
5270         hci_stack->classic_read_local_oob_data = false;
5271         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5272             hci_send_cmd(&hci_read_local_extended_oob_data);
5273         } else {
5274             hci_send_cmd(&hci_read_local_oob_data);
5275         }
5276     }
5277 #endif
5278     // pairing
5279     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5280         uint8_t state = hci_stack->gap_pairing_state;
5281         uint8_t pin_code[16];
5282         switch (state){
5283             case GAP_PAIRING_STATE_SEND_PIN:
5284                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5285                 memset(pin_code, 0, 16);
5286                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5287                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5288                 break;
5289             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5290                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5291                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5292                 break;
5293             case GAP_PAIRING_STATE_SEND_PASSKEY:
5294                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5295                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5296                 break;
5297             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5298                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5299                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5300                 break;
5301             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5302                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5303                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5304                 break;
5305             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5306                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5307                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5308                 break;
5309             default:
5310                 break;
5311         }
5312         return true;
5313     }
5314     return false;
5315 }
5316 #endif
5317 
5318 #ifdef ENABLE_BLE
5319 
5320 #ifdef ENABLE_LE_CENTRAL
5321 static void hci_le_scan_stop(void){
5322 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5323     if (hci_extended_advertising_supported()) {
5324             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5325         } else
5326 #endif
5327     {
5328         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5329     }
5330 }
5331 #endif
5332 
5333 #ifdef ENABLE_LE_PERIPHERAL
5334 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5335 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
5336     uint8_t  operation = 0;
5337     if (pos == 0){
5338         // first fragment or complete data
5339         operation |= 1;
5340     }
5341     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
5342         // last fragment or complete data
5343         operation |= 2;
5344     }
5345     return operation;
5346 }
5347 #endif
5348 #endif
5349 
5350 static bool hci_run_general_gap_le(void){
5351 
5352     btstack_linked_list_iterator_t lit;
5353 
5354     // Phase 1: collect what to stop
5355 
5356 #ifdef ENABLE_LE_CENTRAL
5357     bool scanning_stop = false;
5358     bool connecting_stop = false;
5359 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5360 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5361     bool periodic_sync_stop = false;
5362 #endif
5363 #endif
5364 #endif
5365 
5366 #ifdef ENABLE_LE_PERIPHERAL
5367     bool advertising_stop = false;
5368 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5369     le_advertising_set_t * advertising_stop_set = NULL;
5370 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5371     bool periodic_advertising_stop = false;
5372 #endif
5373 #endif
5374 #endif
5375 
5376     // check if own address changes
5377     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5378 
5379     // check if whitelist needs modification
5380     bool whitelist_modification_pending = false;
5381     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5382     while (btstack_linked_list_iterator_has_next(&lit)){
5383         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5384         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
5385             whitelist_modification_pending = true;
5386             break;
5387         }
5388     }
5389 
5390     // check if resolving list needs modification
5391     bool resolving_list_modification_pending = false;
5392 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5393     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
5394 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
5395         resolving_list_modification_pending = true;
5396     }
5397 #endif
5398 
5399 #ifdef ENABLE_LE_CENTRAL
5400 
5401 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5402     // check if periodic advertiser list needs modification
5403     bool periodic_list_modification_pending = false;
5404     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5405     while (btstack_linked_list_iterator_has_next(&lit)){
5406         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5407         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
5408             periodic_list_modification_pending = true;
5409             break;
5410         }
5411     }
5412 #endif
5413 
5414     // scanning control
5415     if (hci_stack->le_scanning_active) {
5416         // stop if:
5417         // - parameter change required
5418         // - it's disabled
5419         // - whitelist change required but used for scanning
5420         // - resolving list modified
5421         // - own address changes
5422         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
5423         if ((hci_stack->le_scanning_param_update) ||
5424             !hci_stack->le_scanning_enabled ||
5425             (scanning_uses_whitelist && whitelist_modification_pending) ||
5426             resolving_list_modification_pending ||
5427             random_address_change){
5428 
5429             scanning_stop = true;
5430         }
5431     }
5432 
5433     // connecting control
5434     bool connecting_with_whitelist;
5435     switch (hci_stack->le_connecting_state){
5436         case LE_CONNECTING_DIRECT:
5437         case LE_CONNECTING_WHITELIST:
5438             // stop connecting if:
5439             // - connecting uses white and whitelist modification pending
5440             // - if it got disabled
5441             // - resolving list modified
5442             // - own address changes
5443             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
5444             if ((connecting_with_whitelist && whitelist_modification_pending) ||
5445                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
5446                 resolving_list_modification_pending ||
5447                 random_address_change) {
5448 
5449                 connecting_stop = true;
5450             }
5451             break;
5452         default:
5453             break;
5454     }
5455 
5456 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5457 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5458     // periodic sync control
5459     bool sync_with_advertiser_list;
5460     switch(hci_stack->le_periodic_sync_state){
5461         case LE_CONNECTING_DIRECT:
5462         case LE_CONNECTING_WHITELIST:
5463             // stop sync if:
5464             // - sync with advertiser list and advertiser list modification pending
5465             // - if it got disabled
5466             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
5467             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
5468                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
5469                 periodic_sync_stop = true;
5470             }
5471             break;
5472         default:
5473             break;
5474     }
5475 #endif
5476 #endif
5477 
5478 #endif /* ENABLE_LE_CENTRAL */
5479 
5480 #ifdef ENABLE_LE_PERIPHERAL
5481     // le advertisement control
5482     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
5483         // stop if:
5484         // - parameter change required
5485         // - random address used in advertising and changes
5486         // - it's disabled
5487         // - whitelist change required but used for advertisement filter policy
5488         // - resolving list modified
5489         // - own address changes
5490         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
5491         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
5492         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
5493         if (advertising_change ||
5494             (advertising_uses_random_address && random_address_change) ||
5495             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
5496             (advertising_uses_whitelist && whitelist_modification_pending) ||
5497             resolving_list_modification_pending ||
5498             random_address_change) {
5499 
5500             advertising_stop = true;
5501         }
5502     }
5503 
5504 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5505     if (hci_extended_advertising_supported() && (advertising_stop == false)){
5506         btstack_linked_list_iterator_t it;
5507         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5508         while (btstack_linked_list_iterator_has_next(&it)){
5509             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5510             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5511                 // stop if:
5512                 // - parameter change required
5513                 // - random address used in connectable advertising and changes
5514                 // - it's disabled
5515                 // - whitelist change required but used for advertisement filter policy
5516                 // - resolving list modified
5517                 // - own address changes
5518                 // - advertisement set will be removed
5519                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
5520                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
5521                 bool advertising_uses_random_address =
5522                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
5523                         advertising_connectable;
5524                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
5525                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
5526                 bool advertising_set_random_address_change =
5527                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5528                 bool advertising_set_will_be_removed =
5529                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
5530                 if (advertising_parameter_change ||
5531                     (advertising_uses_random_address && advertising_set_random_address_change) ||
5532                     (advertising_enabled == false) ||
5533                     (advertising_uses_whitelist && whitelist_modification_pending) ||
5534                     resolving_list_modification_pending ||
5535                     advertising_set_will_be_removed) {
5536 
5537                     advertising_stop = true;
5538                     advertising_stop_set = advertising_set;
5539                     break;
5540                 }
5541             }
5542 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5543             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5544                 // stop if:
5545                 // - it's disabled
5546                 // - parameter change required
5547                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
5548                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
5549                 if ((periodic_enabled == false) || periodic_parameter_change){
5550                     periodic_advertising_stop = true;
5551                     advertising_stop_set = advertising_set;
5552                 }
5553             }
5554 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5555         }
5556     }
5557 #endif
5558 
5559 #endif
5560 
5561 
5562     // Phase 2: stop everything that should be off during modifications
5563 
5564 
5565     // 2.1 Outgoing connection
5566 #ifdef ENABLE_LE_CENTRAL
5567     if (connecting_stop){
5568         hci_send_cmd(&hci_le_create_connection_cancel);
5569         return true;
5570     }
5571 #endif
5572 
5573     // 2.2 Scanning
5574 #ifdef ENABLE_LE_CENTRAL
5575     if (scanning_stop){
5576         hci_stack->le_scanning_active = false;
5577         hci_le_scan_stop();
5578         return true;
5579     }
5580 
5581     // 2.3 Periodic Sync
5582 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5583     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
5584         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
5585         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
5586         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
5587         return true;
5588     }
5589 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5590     if (periodic_sync_stop){
5591         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
5592         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
5593         return true;
5594     }
5595 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5596 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5597 #endif /* ENABLE_LE_CENTRAL */
5598 
5599     // 2.4 Advertising: legacy, extended, periodic
5600 #ifdef ENABLE_LE_PERIPHERAL
5601     if (advertising_stop){
5602 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5603         if (hci_extended_advertising_supported()) {
5604             uint8_t advertising_stop_handle;
5605             if (advertising_stop_set != NULL){
5606                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5607                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5608             } else {
5609                 advertising_stop_handle = 0;
5610                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5611             }
5612             const uint8_t advertising_handles[] = { advertising_stop_handle };
5613             const uint16_t durations[] = { 0 };
5614             const uint16_t max_events[] = { 0 };
5615             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5616         } else
5617 #endif
5618         {
5619             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5620             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5621         }
5622         return true;
5623     }
5624 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5625 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5626     if (periodic_advertising_stop){
5627         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5628         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
5629         return true;
5630     }
5631 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5632 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5633 #endif /* ENABLE_LE_PERIPHERAL */
5634 
5635 
5636     // Phase 3: modify
5637 
5638     if (random_address_change){
5639         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5640 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5641         if (hci_extended_advertising_supported()) {
5642             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5643         }
5644 #endif
5645         {
5646             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5647         }
5648         return true;
5649     }
5650 
5651 #ifdef ENABLE_LE_CENTRAL
5652     if (hci_stack->le_scanning_param_update){
5653         hci_stack->le_scanning_param_update = false;
5654 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5655         if (hci_extended_advertising_supported()){
5656             // prepare arrays for all PHYs
5657             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
5658             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
5659             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
5660             uint8_t  scanning_phys     = 1;  // LE 1M PHY
5661             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
5662                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
5663         } else
5664 #endif
5665         {
5666             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5667                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
5668         }
5669         return true;
5670     }
5671 #endif
5672 
5673 #ifdef ENABLE_LE_PERIPHERAL
5674     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
5675         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5676         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5677 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5678         if (hci_extended_advertising_supported()){
5679             // map advertisment type to advertising event properties
5680             uint16_t adv_event_properties = 0;
5681             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5682             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5683                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5684             }
5685             hci_stack->le_advertising_set_in_current_command = 0;
5686             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5687                          0,
5688                          adv_event_properties,
5689                          hci_stack->le_advertisements_interval_min,
5690                          hci_stack->le_advertisements_interval_max,
5691                          hci_stack->le_advertisements_channel_map,
5692                          hci_stack->le_advertisements_own_addr_type,
5693                          hci_stack->le_advertisements_direct_address_type,
5694                          hci_stack->le_advertisements_direct_address,
5695                          hci_stack->le_advertisements_filter_policy,
5696                          0x7f,  // tx power: no preference
5697                          0x01,  // primary adv phy: LE 1M
5698                          0,     // secondary adv max skip
5699                          0,     // secondary adv phy
5700                          0,     // adv sid
5701                          0      // scan request notification
5702                          );
5703         }
5704 #endif
5705         {
5706             hci_send_cmd(&hci_le_set_advertising_parameters,
5707                          hci_stack->le_advertisements_interval_min,
5708                          hci_stack->le_advertisements_interval_max,
5709                          hci_stack->le_advertisements_type,
5710                          hci_stack->le_advertisements_own_addr_type,
5711                          hci_stack->le_advertisements_direct_address_type,
5712                          hci_stack->le_advertisements_direct_address,
5713                          hci_stack->le_advertisements_channel_map,
5714                          hci_stack->le_advertisements_filter_policy);
5715         }
5716         return true;
5717     }
5718 
5719     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
5720         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5721         uint8_t adv_data_clean[31];
5722         memset(adv_data_clean, 0, sizeof(adv_data_clean));
5723         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
5724                      hci_stack->le_advertisements_data_len);
5725         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
5726 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5727         if (hci_extended_advertising_supported()){
5728             hci_stack->le_advertising_set_in_current_command = 0;
5729             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
5730         } else
5731 #endif
5732         {
5733             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
5734         }
5735         return true;
5736     }
5737 
5738     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
5739         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5740         uint8_t scan_data_clean[31];
5741         memset(scan_data_clean, 0, sizeof(scan_data_clean));
5742         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
5743                      hci_stack->le_scan_response_data_len);
5744         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
5745 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5746         if (hci_extended_advertising_supported()){
5747             hci_stack->le_advertising_set_in_current_command = 0;
5748             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
5749         } else
5750 #endif
5751         {
5752             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
5753         }
5754         return true;
5755     }
5756 
5757 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5758     if (hci_extended_advertising_supported()) {
5759         btstack_linked_list_iterator_t it;
5760         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5761         while (btstack_linked_list_iterator_has_next(&it)){
5762             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5763             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
5764                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
5765                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5766                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
5767                 return true;
5768             }
5769             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
5770                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5771                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
5772                 return true;
5773             }
5774             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
5775                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5776                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5777                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5778                              advertising_set->advertising_handle,
5779                              advertising_set->extended_params.advertising_event_properties,
5780                              advertising_set->extended_params.primary_advertising_interval_min,
5781                              advertising_set->extended_params.primary_advertising_interval_max,
5782                              advertising_set->extended_params.primary_advertising_channel_map,
5783                              advertising_set->extended_params.own_address_type,
5784                              advertising_set->extended_params.peer_address_type,
5785                              advertising_set->extended_params.peer_address,
5786                              advertising_set->extended_params.advertising_filter_policy,
5787                              advertising_set->extended_params.advertising_tx_power,
5788                              advertising_set->extended_params.primary_advertising_phy,
5789                              advertising_set->extended_params.secondary_advertising_max_skip,
5790                              advertising_set->extended_params.secondary_advertising_phy,
5791                              advertising_set->extended_params.advertising_sid,
5792                              advertising_set->extended_params.scan_request_notification_enable
5793                 );
5794                 return true;
5795             }
5796             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
5797                 uint16_t pos = advertising_set->adv_data_pos;
5798                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
5799                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5800                 if ((operation & 0x02) != 0){
5801                     // last fragment or complete data
5802                     operation |= 2;
5803                     advertising_set->adv_data_pos = 0;
5804                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5805                 } else {
5806                     advertising_set->adv_data_pos += data_to_upload;
5807                 }
5808                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5809                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
5810                 return true;
5811             }
5812             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
5813                 uint16_t pos = advertising_set->scan_data_pos;
5814                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
5815                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5816                 if ((operation & 0x02) != 0){
5817                     advertising_set->scan_data_pos = 0;
5818                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5819                 } else {
5820                     advertising_set->scan_data_pos += data_to_upload;
5821                 }
5822                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5823                 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
5824                 return true;
5825             }
5826 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5827             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
5828                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
5829                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5830                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
5831                              advertising_set->advertising_handle,
5832                              advertising_set->periodic_params.periodic_advertising_interval_min,
5833                              advertising_set->periodic_params.periodic_advertising_interval_max,
5834                              advertising_set->periodic_params.periodic_advertising_properties);
5835                 return true;
5836             }
5837             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
5838                 uint16_t pos = advertising_set->periodic_data_pos;
5839                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
5840                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5841                 if ((operation & 0x02) != 0){
5842                     // last fragment or complete data
5843                     operation |= 2;
5844                     advertising_set->periodic_data_pos = 0;
5845                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
5846                 } else {
5847                     advertising_set->periodic_data_pos += data_to_upload;
5848                 }
5849                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5850                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
5851                 return true;
5852             }
5853 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5854         }
5855     }
5856 #endif
5857 
5858 #endif
5859 
5860 #ifdef ENABLE_LE_CENTRAL
5861     // if connect with whitelist was active and is not cancelled yet, wait until next time
5862     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
5863 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5864     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
5865     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
5866 #endif
5867 #endif
5868 
5869     // LE Whitelist Management
5870     if (whitelist_modification_pending){
5871         // add/remove entries
5872         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5873         while (btstack_linked_list_iterator_has_next(&lit)){
5874             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5875 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5876 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5877 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
5878 				return true;
5879 			}
5880             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
5881 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
5882                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
5883                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
5884                 return true;
5885             }
5886             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
5887 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5888 				btstack_memory_whitelist_entry_free(entry);
5889             }
5890         }
5891     }
5892 
5893 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5894     // LE Resolving List Management
5895     if (resolving_list_supported) {
5896 		uint16_t i;
5897 		switch (hci_stack->le_resolving_list_state) {
5898 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
5899 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
5900 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
5901 				return true;
5902 			case LE_RESOLVING_LIST_READ_SIZE:
5903 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
5904 				hci_send_cmd(&hci_le_read_resolving_list_size);
5905 				return true;
5906 			case LE_RESOLVING_LIST_SEND_CLEAR:
5907 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
5908 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
5909 							  sizeof(hci_stack->le_resolving_list_add_entries));
5910 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
5911 							  sizeof(hci_stack->le_resolving_list_remove_entries));
5912 				hci_send_cmd(&hci_le_clear_resolving_list);
5913 				return true;
5914 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
5915 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5916 					uint8_t offset = i >> 3;
5917 					uint8_t mask = 1 << (i & 7);
5918 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
5919 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
5920 					bd_addr_t peer_identity_addreses;
5921 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5922 					sm_key_t peer_irk;
5923 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5924 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5925 
5926 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
5927 					// trigger whitelist entry 'update' (work around for controller bug)
5928 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5929 					while (btstack_linked_list_iterator_has_next(&lit)) {
5930 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
5931 						if (entry->address_type != peer_identity_addr_type) continue;
5932 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
5933 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
5934 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
5935 					}
5936 #endif
5937 
5938 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
5939 								 peer_identity_addreses);
5940 					return true;
5941 				}
5942 
5943 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
5944 
5945 				/* fall through */
5946 
5947 			case LE_RESOLVING_LIST_ADD_ENTRIES:
5948 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5949 					uint8_t offset = i >> 3;
5950 					uint8_t mask = 1 << (i & 7);
5951 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
5952 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
5953 					bd_addr_t peer_identity_addreses;
5954 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5955 					sm_key_t peer_irk;
5956 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5957 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5958 					const uint8_t *local_irk = gap_get_persistent_irk();
5959 					// command uses format specifier 'P' that stores 16-byte value without flip
5960 					uint8_t local_irk_flipped[16];
5961 					uint8_t peer_irk_flipped[16];
5962 					reverse_128(local_irk, local_irk_flipped);
5963 					reverse_128(peer_irk, peer_irk_flipped);
5964 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
5965 								 peer_irk_flipped, local_irk_flipped);
5966 					return true;
5967 				}
5968 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5969 				break;
5970 
5971 			default:
5972 				break;
5973 		}
5974 	}
5975     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5976 #endif
5977 
5978 #ifdef ENABLE_LE_CENTRAL
5979 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5980     // LE Whitelist Management
5981     if (periodic_list_modification_pending){
5982         // add/remove entries
5983         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5984         while (btstack_linked_list_iterator_has_next(&lit)){
5985             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5986             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
5987                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5988                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
5989                 return true;
5990             }
5991             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
5992                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5993                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
5994                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
5995                 return true;
5996             }
5997             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
5998                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
5999                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6000             }
6001         }
6002     }
6003 #endif
6004 #endif
6005 
6006     // post-pone all actions until stack is fully working
6007     if (hci_stack->state != HCI_STATE_WORKING) return false;
6008 
6009     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6010     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6011 
6012     // Phase 4: restore state
6013 
6014 #ifdef ENABLE_LE_CENTRAL
6015     // re-start scanning
6016     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6017         hci_stack->le_scanning_active = true;
6018 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6019         if (hci_extended_advertising_supported()){
6020             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0);
6021         } else
6022 #endif
6023         {
6024             hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
6025         }
6026         return true;
6027     }
6028 #endif
6029 
6030 #ifdef ENABLE_LE_CENTRAL
6031     // re-start connecting
6032     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6033         bd_addr_t null_addr;
6034         memset(null_addr, 0, 6);
6035         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6036         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6037         hci_send_cmd(&hci_le_create_connection,
6038                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
6039                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
6040                      1,         // use whitelist
6041                      0,         // peer address type
6042                      null_addr, // peer bd addr
6043                      hci_stack->le_connection_own_addr_type,   // our addr type:
6044                      hci_stack->le_connection_interval_min,    // conn interval min
6045                      hci_stack->le_connection_interval_max,    // conn interval max
6046                      hci_stack->le_connection_latency,         // conn latency
6047                      hci_stack->le_supervision_timeout,        // conn latency
6048                      hci_stack->le_minimum_ce_length,          // min ce length
6049                      hci_stack->le_maximum_ce_length           // max ce length
6050         );
6051         return true;
6052     }
6053 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6054     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6055         switch(hci_stack->le_periodic_sync_request){
6056             case LE_CONNECTING_DIRECT:
6057             case LE_CONNECTING_WHITELIST:
6058                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6059                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6060                              hci_stack->le_periodic_sync_options,
6061                              hci_stack->le_periodic_sync_advertising_sid,
6062                              hci_stack->le_periodic_sync_advertiser_address_type,
6063                              hci_stack->le_periodic_sync_advertiser_address,
6064                              hci_stack->le_periodic_sync_skip,
6065                              hci_stack->le_periodic_sync_timeout,
6066                              hci_stack->le_periodic_sync_cte_type);
6067                 return true;
6068             default:
6069                 break;
6070         }
6071     }
6072 #endif
6073 #endif
6074 
6075 #ifdef ENABLE_LE_PERIPHERAL
6076     // re-start advertising
6077     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6078         // check if advertisements should be enabled given
6079         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6080         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6081 
6082 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6083         if (hci_extended_advertising_supported()){
6084             const uint8_t advertising_handles[] = { 0 };
6085             const uint16_t durations[] = { 0 };
6086             const uint16_t max_events[] = { 0 };
6087             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6088         } else
6089 #endif
6090         {
6091             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6092         }
6093         return true;
6094     }
6095 
6096 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6097     if (hci_extended_advertising_supported()) {
6098         btstack_linked_list_iterator_t it;
6099         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6100         while (btstack_linked_list_iterator_has_next(&it)) {
6101             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6102             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6103                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6104                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6105                 const uint16_t durations[] = { advertising_set->enable_timeout };
6106                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6107                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6108                 return true;
6109             }
6110 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6111             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6112                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6113                 uint8_t enable = 1;
6114                 if (advertising_set->periodic_include_adi){
6115                     enable |= 2;
6116                 }
6117                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6118                 return true;
6119             }
6120 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6121         }
6122     }
6123 #endif
6124 #endif
6125 
6126     return false;
6127 }
6128 
6129 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6130 static bool hci_run_iso_tasks(void){
6131     btstack_linked_list_iterator_t it;
6132 
6133     // BIG
6134     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6135     while (btstack_linked_list_iterator_has_next(&it)){
6136         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6137         switch (big->state){
6138             case LE_AUDIO_BIG_STATE_CREATE:
6139                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6140                 hci_send_cmd(&hci_le_create_big,
6141                              big->params->big_handle,
6142                              big->params->advertising_handle,
6143                              big->params->num_bis,
6144                              big->params->sdu_interval_us,
6145                              big->params->max_sdu,
6146                              big->params->max_transport_latency_ms,
6147                              big->params->rtn,
6148                              big->params->phy,
6149                              big->params->packing,
6150                              big->params->framing,
6151                              big->params->encryption,
6152                              big->params->broadcast_code);
6153                 return true;
6154             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6155                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6156                 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);
6157                 return true;
6158             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6159                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6160                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6161                 break;
6162             case LE_AUDIO_BIG_STATE_TERMINATE:
6163                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6164                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6165                 return true;
6166             default:
6167                 break;
6168         }
6169     }
6170 
6171     // BIG Sync
6172     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6173     while (btstack_linked_list_iterator_has_next(&it)){
6174         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6175         switch (big_sync->state){
6176             case LE_AUDIO_BIG_STATE_CREATE:
6177                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6178                 hci_send_cmd(&hci_le_big_create_sync,
6179                              big_sync->params->big_handle,
6180                              big_sync->params->sync_handle,
6181                              big_sync->params->encryption,
6182                              big_sync->params->broadcast_code,
6183                              big_sync->params->mse,
6184                              big_sync->params->big_sync_timeout_10ms,
6185                              big_sync->params->num_bis,
6186                              big_sync->params->bis_indices);
6187                 return true;
6188             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6189                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6190                 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);
6191                 return true;
6192             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6193                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6194                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6195                 break;
6196             case LE_AUDIO_BIG_STATE_TERMINATE:
6197                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6198                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6199                 return true;
6200             default:
6201                 break;
6202         }
6203     }
6204 
6205     return false;
6206 }
6207 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6208 #endif
6209 
6210 static bool hci_run_general_pending_commands(void){
6211     btstack_linked_item_t * it;
6212     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6213         hci_connection_t * connection = (hci_connection_t *) it;
6214 
6215         switch(connection->state){
6216             case SEND_CREATE_CONNECTION:
6217                 switch(connection->address_type){
6218 #ifdef ENABLE_CLASSIC
6219                     case BD_ADDR_TYPE_ACL:
6220                         log_info("sending hci_create_connection");
6221                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
6222                         break;
6223 #endif
6224                     default:
6225 #ifdef ENABLE_BLE
6226 #ifdef ENABLE_LE_CENTRAL
6227                         log_info("sending hci_le_create_connection");
6228                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6229                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6230 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6231                         if (hci_extended_advertising_supported()) {
6232                             uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval };
6233                             uint16_t le_connection_scan_window[1]   = { hci_stack->le_connection_scan_window };
6234                             uint16_t le_connection_interval_min[1]  = { hci_stack->le_connection_interval_min };
6235                             uint16_t le_connection_interval_max[1]  = { hci_stack->le_connection_interval_max };
6236                             uint16_t le_connection_latency[1]       = { hci_stack->le_connection_latency };
6237                             uint16_t le_supervision_timeout[1]      = { hci_stack->le_supervision_timeout };
6238                             uint16_t le_minimum_ce_length[1]        = { hci_stack->le_minimum_ce_length };
6239                             uint16_t le_maximum_ce_length[1]        = { hci_stack->le_maximum_ce_length };
6240                             hci_send_cmd(&hci_le_extended_create_connection,
6241                                          0,         // don't use whitelist
6242                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6243                                          connection->address_type,      // peer address type
6244                                          connection->address,           // peer bd addr
6245                                          1,                             // initiating PHY - 1M
6246                                          le_connection_scan_interval,   // conn scan interval
6247                                          le_connection_scan_window,     // conn scan windows
6248                                          le_connection_interval_min,    // conn interval min
6249                                          le_connection_interval_max,    // conn interval max
6250                                          le_connection_latency,         // conn latency
6251                                          le_supervision_timeout,        // conn latency
6252                                          le_minimum_ce_length,          // min ce length
6253                                          le_maximum_ce_length           // max ce length
6254                             );                        }
6255                         else
6256 #endif
6257                         {
6258                             hci_send_cmd(&hci_le_create_connection,
6259                                          hci_stack->le_connection_scan_interval,    // conn scan interval
6260                                          hci_stack->le_connection_scan_window,      // conn scan windows
6261                                          0,         // don't use whitelist
6262                                          connection->address_type, // peer address type
6263                                          connection->address,      // peer bd addr
6264                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6265                                          hci_stack->le_connection_interval_min,    // conn interval min
6266                                          hci_stack->le_connection_interval_max,    // conn interval max
6267                                          hci_stack->le_connection_latency,         // conn latency
6268                                          hci_stack->le_supervision_timeout,        // conn latency
6269                                          hci_stack->le_minimum_ce_length,          // min ce length
6270                                          hci_stack->le_maximum_ce_length          // max ce length
6271                             );
6272                         }
6273                         connection->state = SENT_CREATE_CONNECTION;
6274 #endif
6275 #endif
6276                         break;
6277                 }
6278                 return true;
6279 
6280 #ifdef ENABLE_CLASSIC
6281             case RECEIVED_CONNECTION_REQUEST:
6282                 connection->role  = HCI_ROLE_SLAVE;
6283                 if (connection->address_type == BD_ADDR_TYPE_ACL){
6284                     log_info("sending hci_accept_connection_request");
6285                     connection->state = ACCEPTED_CONNECTION_REQUEST;
6286                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
6287                     return true;
6288                 }
6289                 break;
6290 #endif
6291 
6292 #ifdef ENABLE_BLE
6293 #ifdef ENABLE_LE_CENTRAL
6294             case SEND_CANCEL_CONNECTION:
6295                 connection->state = SENT_CANCEL_CONNECTION;
6296                 hci_send_cmd(&hci_le_create_connection_cancel);
6297                 return true;
6298 #endif
6299 #endif
6300             case SEND_DISCONNECT:
6301                 connection->state = SENT_DISCONNECT;
6302                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6303                 return true;
6304 
6305             default:
6306                 break;
6307         }
6308 
6309         // no further commands if connection is about to get shut down
6310         if (connection->state == SENT_DISCONNECT) continue;
6311 
6312 #ifdef ENABLE_CLASSIC
6313 
6314         // Handling link key request requires remote supported features
6315         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
6316             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
6317             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
6318 
6319             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
6320             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
6321             if (have_link_key && security_level_sufficient){
6322                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
6323             } else {
6324                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
6325             }
6326             return true;
6327         }
6328 
6329         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
6330             log_info("denying to pin request");
6331             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
6332             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
6333             return true;
6334         }
6335 
6336         // security assessment requires remote features
6337         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
6338             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
6339             hci_ssp_assess_security_on_io_cap_request(connection);
6340             // 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
6341         }
6342 
6343         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
6344             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6345             // set authentication requirements:
6346             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
6347             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
6348             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
6349             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
6350                 authreq |= 1;
6351             }
6352             bool bonding = hci_stack->bondable;
6353             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
6354                 // if we have received IO Cap Response, we're in responder role
6355                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6356                 if (bonding && !remote_bonding){
6357                     log_info("Remote not bonding, dropping local flag");
6358                     bonding = false;
6359                 }
6360             }
6361             if (bonding){
6362                 if (connection->bonding_flags & BONDING_DEDICATED){
6363                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6364                 } else {
6365                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
6366                 }
6367             }
6368             uint8_t have_oob_data = 0;
6369 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6370             if (connection->classic_oob_c_192 != NULL){
6371                     have_oob_data |= 1;
6372             }
6373             if (connection->classic_oob_c_256 != NULL){
6374                 have_oob_data |= 2;
6375             }
6376 #endif
6377             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
6378             return true;
6379         }
6380 
6381         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
6382             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6383             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
6384             return true;
6385         }
6386 
6387 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6388         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
6389             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
6390             const uint8_t zero[16] = { 0 };
6391             const uint8_t * r_192 = zero;
6392             const uint8_t * c_192 = zero;
6393             const uint8_t * r_256 = zero;
6394             const uint8_t * c_256 = zero;
6395             // verify P-256 OOB
6396             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
6397                 c_256 = connection->classic_oob_c_256;
6398                 if (connection->classic_oob_r_256 != NULL) {
6399                     r_256 = connection->classic_oob_r_256;
6400                 }
6401             }
6402             // verify P-192 OOB
6403             if ((connection->classic_oob_c_192 != NULL)) {
6404                 c_192 = connection->classic_oob_c_192;
6405                 if (connection->classic_oob_r_192 != NULL) {
6406                     r_192 = connection->classic_oob_r_192;
6407                 }
6408             }
6409 
6410             // assess security
6411             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
6412             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
6413             if (need_level_4 && !can_reach_level_4){
6414                 log_info("Level 4 required, but not possible -> abort");
6415                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
6416                 // send oob negative reply
6417                 c_256 = NULL;
6418                 c_192 = NULL;
6419             }
6420 
6421             // Reply
6422             if (c_256 != zero) {
6423                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
6424             } else if (c_192 != zero){
6425                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
6426             } else {
6427                 hci_stack->classic_oob_con_handle = connection->con_handle;
6428                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
6429             }
6430             return true;
6431         }
6432 #endif
6433 
6434         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
6435             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
6436             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
6437             return true;
6438         }
6439 
6440         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
6441             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
6442             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
6443             return true;
6444         }
6445 
6446         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
6447             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
6448             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
6449             return true;
6450         }
6451 
6452         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
6453             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
6454             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
6455             connection->state = SENT_DISCONNECT;
6456             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6457             return true;
6458         }
6459 
6460         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
6461             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
6462             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
6463             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
6464             return true;
6465         }
6466 
6467         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
6468             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
6469             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
6470             return true;
6471         }
6472 
6473         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
6474             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
6475             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
6476             return true;
6477         }
6478 
6479         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
6480             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6481             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
6482             return true;
6483         }
6484 
6485         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
6486             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
6487             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
6488             return true;
6489         }
6490 
6491         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
6492             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
6493             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
6494             return true;
6495         }
6496 #endif
6497 
6498         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
6499             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
6500 #ifdef ENABLE_CLASSIC
6501             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
6502 #endif
6503             if (connection->state != SENT_DISCONNECT){
6504                 connection->state = SENT_DISCONNECT;
6505                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
6506                 return true;
6507             }
6508         }
6509 
6510 #ifdef ENABLE_CLASSIC
6511         uint16_t sniff_min_interval;
6512         switch (connection->sniff_min_interval){
6513             case 0:
6514                 break;
6515             case 0xffff:
6516                 connection->sniff_min_interval = 0;
6517                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
6518                 return true;
6519             default:
6520                 sniff_min_interval = connection->sniff_min_interval;
6521                 connection->sniff_min_interval = 0;
6522                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
6523                 return true;
6524         }
6525 
6526         if (connection->sniff_subrating_max_latency != 0xffff){
6527             uint16_t max_latency = connection->sniff_subrating_max_latency;
6528             connection->sniff_subrating_max_latency = 0;
6529             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
6530             return true;
6531         }
6532 
6533         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
6534             uint8_t service_type = (uint8_t) connection->qos_service_type;
6535             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
6536             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);
6537             return true;
6538         }
6539 
6540         if (connection->request_role != HCI_ROLE_INVALID){
6541             hci_role_t role = connection->request_role;
6542             connection->request_role = HCI_ROLE_INVALID;
6543             hci_send_cmd(&hci_switch_role_command, connection->address, role);
6544             return true;
6545         }
6546 #endif
6547 
6548         if (connection->gap_connection_tasks != 0){
6549 #ifdef ENABLE_CLASSIC
6550             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
6551                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
6552                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
6553                 return true;
6554             }
6555             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
6556                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
6557                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
6558                 return true;
6559             }
6560 #endif
6561             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
6562                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
6563                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
6564                 return true;
6565             }
6566         }
6567 
6568 #ifdef ENABLE_BLE
6569         switch (connection->le_con_parameter_update_state){
6570             // response to L2CAP CON PARAMETER UPDATE REQUEST
6571             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
6572                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6573                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
6574                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6575                              0x0000, 0xffff);
6576                 return true;
6577             case CON_PARAMETER_UPDATE_REPLY:
6578                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6579                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
6580                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6581                              0x0000, 0xffff);
6582                 return true;
6583             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
6584                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6585                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
6586                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
6587                 return true;
6588             default:
6589                 break;
6590         }
6591         if (connection->le_phy_update_all_phys != 0xffu){
6592             uint8_t all_phys = connection->le_phy_update_all_phys;
6593             connection->le_phy_update_all_phys = 0xff;
6594             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);
6595             return true;
6596         }
6597 #endif
6598     }
6599     return false;
6600 }
6601 
6602 static void hci_run(void){
6603 
6604     // stack state sub statemachines
6605     switch (hci_stack->state) {
6606         case HCI_STATE_INITIALIZING:
6607             hci_initializing_run();
6608             break;
6609         case HCI_STATE_HALTING:
6610             hci_halting_run();
6611             break;
6612         case HCI_STATE_FALLING_ASLEEP:
6613             hci_falling_asleep_run();
6614             break;
6615         default:
6616             break;
6617     }
6618 
6619     // allow to run after initialization to working transition
6620     if (hci_stack->state != HCI_STATE_WORKING){
6621         return;
6622     }
6623 
6624     bool done;
6625 
6626     // send continuation fragments first, as they block the prepared packet buffer
6627     done = hci_run_acl_fragments();
6628     if (done) return;
6629 
6630 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6631     done = hci_run_iso_fragments();
6632     if (done) return;
6633 #endif
6634 
6635 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
6636     // send host num completed packets next as they don't require num_cmd_packets > 0
6637     if (!hci_can_send_comand_packet_transport()) return;
6638     if (hci_stack->host_completed_packets){
6639         hci_host_num_completed_packets();
6640         return;
6641     }
6642 #endif
6643 
6644     if (!hci_can_send_command_packet_now()) return;
6645 
6646     // global/non-connection oriented commands
6647 
6648 
6649 #ifdef ENABLE_CLASSIC
6650     // general gap classic
6651     done = hci_run_general_gap_classic();
6652     if (done) return;
6653 #endif
6654 
6655 #ifdef ENABLE_BLE
6656     // general gap le
6657     done = hci_run_general_gap_le();
6658     if (done) return;
6659 
6660 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6661     // ISO related tasks, e.g. BIG create/terminate/sync
6662     done = hci_run_iso_tasks();
6663     if (done) return;
6664 #endif
6665 #endif
6666 
6667     // send pending HCI commands
6668     hci_run_general_pending_commands();
6669 }
6670 
6671 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
6672     // house-keeping
6673 
6674 #ifdef ENABLE_CLASSIC
6675     bd_addr_t addr;
6676     hci_connection_t * conn;
6677 #endif
6678 #ifdef ENABLE_LE_CENTRAL
6679     uint8_t initiator_filter_policy;
6680 #endif
6681 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6682     uint8_t i;
6683     uint8_t num_cis;
6684     hci_con_handle_t cis_handle;
6685     uint8_t status;
6686 #endif
6687 
6688     uint16_t opcode = little_endian_read_16(packet, 0);
6689     switch (opcode) {
6690         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
6691             hci_stack->loopback_mode = packet[3];
6692             break;
6693 
6694 #ifdef ENABLE_CLASSIC
6695         case HCI_OPCODE_HCI_CREATE_CONNECTION:
6696             reverse_bd_addr(&packet[3], addr);
6697             log_info("Create_connection to %s", bd_addr_to_str(addr));
6698 
6699             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
6700             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
6701                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
6702                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
6703             }
6704 
6705             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6706             if (!conn) {
6707                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6708                 if (!conn) {
6709                     // notify client that alloc failed
6710                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6711                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
6712                 }
6713                 conn->state = SEND_CREATE_CONNECTION;
6714                 conn->role  = HCI_ROLE_MASTER;
6715             }
6716 
6717             log_info("conn state %u", conn->state);
6718             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
6719             switch (conn->state) {
6720                 // if connection active exists
6721                 case OPEN:
6722                     // and OPEN, emit connection complete command
6723                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
6724                     // packet not sent to controller
6725                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6726                 case RECEIVED_DISCONNECTION_COMPLETE:
6727                     // create connection triggered in disconnect complete event, let's do it now
6728                     break;
6729                 case SEND_CREATE_CONNECTION:
6730 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
6731                     if (hci_classic_operation_active()){
6732                         return ERROR_CODE_SUCCESS;
6733                     }
6734 #endif
6735                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
6736                     break;
6737                 default:
6738                     // otherwise, just ignore as it is already in the open process
6739                     // packet not sent to controller
6740                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6741             }
6742             conn->state = SENT_CREATE_CONNECTION;
6743 
6744             // track outgoing connection
6745             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
6746             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
6747             break;
6748 
6749 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
6750         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
6751             // setup_synchronous_connection? Voice setting at offset 22
6752             // TODO: compare to current setting if sco connection already active
6753             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
6754             break;
6755         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
6756             // accept_synchronous_connection? Voice setting at offset 18
6757             // TODO: compare to current setting if sco connection already active
6758             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
6759             // track outgoing connection
6760             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
6761             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
6762             break;
6763 #endif
6764 #endif
6765 
6766 #ifdef ENABLE_BLE
6767 #ifdef ENABLE_LE_CENTRAL
6768         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
6769             // white list used?
6770             initiator_filter_policy = packet[7];
6771             switch (initiator_filter_policy) {
6772                 case 0:
6773                     // whitelist not used
6774                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
6775                     break;
6776                 case 1:
6777                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
6778                     break;
6779                 default:
6780                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
6781                     break;
6782             }
6783             // track outgoing connection
6784             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
6785             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
6786             break;
6787         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
6788             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
6789             break;
6790 #endif
6791 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6792 #ifdef ENABLE_LE_CENTRAL
6793         case HCI_OPCODE_HCI_LE_CREATE_CIS:
6794             status = ERROR_CODE_SUCCESS;
6795             num_cis = packet[3];
6796             // setup hci_iso_streams
6797             for (i=0;i<num_cis;i++){
6798                 cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 4 + (4 * i));
6799                 status = hci_iso_stream_create(cis_handle, 0xff);
6800                 if (status != ERROR_CODE_SUCCESS) {
6801                     break;
6802                 }
6803             }
6804             // free structs on error
6805             if (status != ERROR_CODE_SUCCESS){
6806                 hci_iso_stream_requested_finalize(0xff);
6807                 return status;
6808             }
6809             break;
6810 #endif /* ENABLE_LE_CENTRAL */
6811 #ifdef ENABLE_LE_PERIPHERAL
6812         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
6813             cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 3);
6814             status = hci_iso_stream_create(cis_handle, 0xff);
6815             if (status != ERROR_CODE_SUCCESS){
6816                 return status;
6817             }
6818             break;
6819 #endif /* ENABLE_LE_PERIPHERAL */
6820 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6821 #endif /* ENABLE_BLE */
6822         default:
6823             break;
6824     }
6825 
6826     hci_stack->num_cmd_packets--;
6827 
6828     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
6829     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
6830     if (err != 0){
6831         return ERROR_CODE_HARDWARE_FAILURE;
6832     }
6833     return ERROR_CODE_SUCCESS;
6834 }
6835 
6836 // disconnect because of security block
6837 void hci_disconnect_security_block(hci_con_handle_t con_handle){
6838     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6839     if (!connection) return;
6840     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
6841 }
6842 
6843 
6844 // Configure Secure Simple Pairing
6845 
6846 #ifdef ENABLE_CLASSIC
6847 
6848 // enable will enable SSP during init
6849 void gap_ssp_set_enable(int enable){
6850     hci_stack->ssp_enable = enable;
6851 }
6852 
6853 static int hci_local_ssp_activated(void){
6854     return gap_ssp_supported() && hci_stack->ssp_enable;
6855 }
6856 
6857 // if set, BTstack will respond to io capability request using authentication requirement
6858 void gap_ssp_set_io_capability(int io_capability){
6859     hci_stack->ssp_io_capability = io_capability;
6860 }
6861 void gap_ssp_set_authentication_requirement(int authentication_requirement){
6862     hci_stack->ssp_authentication_requirement = authentication_requirement;
6863 }
6864 
6865 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
6866 void gap_ssp_set_auto_accept(int auto_accept){
6867     hci_stack->ssp_auto_accept = auto_accept;
6868 }
6869 
6870 void gap_secure_connections_enable(bool enable){
6871     hci_stack->secure_connections_enable = enable;
6872 }
6873 bool gap_secure_connections_active(void){
6874     return hci_stack->secure_connections_active;
6875 }
6876 
6877 #endif
6878 
6879 // va_list part of hci_send_cmd
6880 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
6881     if (!hci_can_send_command_packet_now()){
6882         log_error("hci_send_cmd called but cannot send packet now");
6883         return ERROR_CODE_COMMAND_DISALLOWED;
6884     }
6885 
6886     // for HCI INITIALIZATION
6887     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
6888     hci_stack->last_cmd_opcode = cmd->opcode;
6889 
6890     hci_reserve_packet_buffer();
6891     uint8_t * packet = hci_stack->hci_packet_buffer;
6892     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
6893     uint8_t status = hci_send_cmd_packet(packet, size);
6894 
6895     // release packet buffer on error or for synchronous transport implementations
6896     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
6897         hci_release_packet_buffer();
6898         hci_emit_transport_packet_sent();
6899     }
6900 
6901     return status;
6902 }
6903 
6904 /**
6905  * pre: numcmds >= 0 - it's allowed to send a command to the controller
6906  */
6907 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
6908     va_list argptr;
6909     va_start(argptr, cmd);
6910     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
6911     va_end(argptr);
6912     return status;
6913 }
6914 
6915 // Create various non-HCI events.
6916 // TODO: generalize, use table similar to hci_create_command
6917 
6918 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
6919     // dump packet
6920     if (dump) {
6921         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
6922     }
6923 
6924     // dispatch to all event handlers
6925     btstack_linked_list_iterator_t it;
6926     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
6927     while (btstack_linked_list_iterator_has_next(&it)){
6928         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
6929         entry->callback(HCI_EVENT_PACKET, 0, event, size);
6930     }
6931 }
6932 
6933 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
6934     if (!hci_stack->acl_packet_handler) return;
6935     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
6936 }
6937 
6938 #ifdef ENABLE_CLASSIC
6939 static void hci_notify_if_sco_can_send_now(void){
6940     // notify SCO sender if waiting
6941     if (!hci_stack->sco_waiting_for_can_send_now) return;
6942     if (hci_can_send_sco_packet_now()){
6943         hci_stack->sco_waiting_for_can_send_now = 0;
6944         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
6945         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
6946         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
6947     }
6948 }
6949 
6950 // parsing end emitting has been merged to reduce code size
6951 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
6952     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
6953 
6954     uint8_t * eir_data;
6955     ad_context_t context;
6956     const uint8_t * name;
6957     uint8_t         name_len;
6958 
6959     if (size < 3) return;
6960 
6961     int event_type = hci_event_packet_get_type(packet);
6962     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
6963     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
6964 
6965     switch (event_type){
6966         case HCI_EVENT_INQUIRY_RESULT:
6967         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6968             if (size != (3 + (num_responses * 14))) return;
6969             break;
6970         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6971             if (size != 257) return;
6972             if (num_responses != 1) return;
6973             break;
6974         default:
6975             return;
6976     }
6977 
6978     // event[1] is set at the end
6979     int i;
6980     for (i=0; i<num_responses;i++){
6981         memset(event, 0, sizeof(event));
6982         event[0] = GAP_EVENT_INQUIRY_RESULT;
6983         uint8_t event_size = 27;    // if name is not set by EIR
6984 
6985         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
6986         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
6987         (void)memcpy(&event[9],
6988                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
6989                      3); // class of device
6990         (void)memcpy(&event[12],
6991                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
6992                      2); // clock offset
6993 
6994         switch (event_type){
6995             case HCI_EVENT_INQUIRY_RESULT:
6996                 // 14,15,16,17 = 0, size 18
6997                 break;
6998             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6999                 event[14] = 1;
7000                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7001                 // 16,17 = 0, size 18
7002                 break;
7003             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7004                 event[14] = 1;
7005                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7006                 // EIR packets only contain a single inquiry response
7007                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
7008                 name = NULL;
7009                 // Iterate over EIR data
7010                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
7011                     uint8_t data_type    = ad_iterator_get_data_type(&context);
7012                     uint8_t data_size    = ad_iterator_get_data_len(&context);
7013                     const uint8_t * data = ad_iterator_get_data(&context);
7014                     // Prefer Complete Local Name over Shortened Local Name
7015                     switch (data_type){
7016                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
7017                             if (name) continue;
7018                             /* fall through */
7019                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
7020                             name = data;
7021                             name_len = data_size;
7022                             break;
7023                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
7024                             if (data_size != 8) break;
7025                             event[16] = 1;
7026                             memcpy(&event[17], data, 8);
7027                             break;
7028                         default:
7029                             break;
7030                     }
7031                 }
7032                 if (name){
7033                     event[25] = 1;
7034                     // truncate name if needed
7035                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
7036                     event[26] = len;
7037                     (void)memcpy(&event[27], name, len);
7038                     event_size += len;
7039                 }
7040                 break;
7041             default:
7042                 return;
7043         }
7044         event[1] = event_size - 2;
7045         hci_emit_event(event, event_size, 1);
7046     }
7047 }
7048 #endif
7049 
7050 void hci_emit_state(void){
7051     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
7052     uint8_t event[3];
7053     event[0] = BTSTACK_EVENT_STATE;
7054     event[1] = sizeof(event) - 2u;
7055     event[2] = hci_stack->state;
7056     hci_emit_event(event, sizeof(event), 1);
7057 }
7058 
7059 #ifdef ENABLE_CLASSIC
7060 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
7061     uint8_t event[13];
7062     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
7063     event[1] = sizeof(event) - 2;
7064     event[2] = status;
7065     little_endian_store_16(event, 3, con_handle);
7066     reverse_bd_addr(address, &event[5]);
7067     event[11] = 1; // ACL connection
7068     event[12] = 0; // encryption disabled
7069     hci_emit_event(event, sizeof(event), 1);
7070 }
7071 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
7072     if (disable_l2cap_timeouts) return;
7073     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
7074     uint8_t event[4];
7075     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
7076     event[1] = sizeof(event) - 2;
7077     little_endian_store_16(event, 2, conn->con_handle);
7078     hci_emit_event(event, sizeof(event), 1);
7079 }
7080 #endif
7081 
7082 #ifdef ENABLE_BLE
7083 #ifdef ENABLE_LE_CENTRAL
7084 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){
7085     uint8_t event[21];
7086     event[0] = HCI_EVENT_LE_META;
7087     event[1] = sizeof(event) - 2u;
7088     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
7089     event[3] = status;
7090     little_endian_store_16(event, 4, con_handle);
7091     event[6] = 0; // TODO: role
7092     event[7] = address_type;
7093     reverse_bd_addr(address, &event[8]);
7094     little_endian_store_16(event, 14, 0); // interval
7095     little_endian_store_16(event, 16, 0); // latency
7096     little_endian_store_16(event, 18, 0); // supervision timeout
7097     event[20] = 0; // master clock accuracy
7098     hci_emit_event(event, sizeof(event), 1);
7099 }
7100 #endif
7101 #endif
7102 
7103 static void hci_emit_transport_packet_sent(void){
7104     // notify upper stack that it might be possible to send again
7105     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
7106     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
7107 }
7108 
7109 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
7110     uint8_t event[6];
7111     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
7112     event[1] = sizeof(event) - 2u;
7113     event[2] = 0; // status = OK
7114     little_endian_store_16(event, 3, con_handle);
7115     event[5] = reason;
7116     hci_emit_event(event, sizeof(event), 1);
7117 }
7118 
7119 static void hci_emit_nr_connections_changed(void){
7120     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
7121     uint8_t event[3];
7122     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
7123     event[1] = sizeof(event) - 2u;
7124     event[2] = nr_hci_connections();
7125     hci_emit_event(event, sizeof(event), 1);
7126 }
7127 
7128 static void hci_emit_hci_open_failed(void){
7129     log_info("BTSTACK_EVENT_POWERON_FAILED");
7130     uint8_t event[2];
7131     event[0] = BTSTACK_EVENT_POWERON_FAILED;
7132     event[1] = sizeof(event) - 2u;
7133     hci_emit_event(event, sizeof(event), 1);
7134 }
7135 
7136 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
7137     log_info("hci_emit_dedicated_bonding_result %u ", status);
7138     uint8_t event[9];
7139     int pos = 0;
7140     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
7141     event[pos++] = sizeof(event) - 2u;
7142     event[pos++] = status;
7143     reverse_bd_addr(address, &event[pos]);
7144     hci_emit_event(event, sizeof(event), 1);
7145 }
7146 
7147 
7148 #ifdef ENABLE_CLASSIC
7149 
7150 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
7151     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
7152     uint8_t event[5];
7153     int pos = 0;
7154     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
7155     event[pos++] = sizeof(event) - 2;
7156     little_endian_store_16(event, 2, con_handle);
7157     pos += 2;
7158     event[pos++] = level;
7159     hci_emit_event(event, sizeof(event), 1);
7160 }
7161 
7162 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
7163     if (!connection) return LEVEL_0;
7164     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
7165     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
7166     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
7167     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
7168     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
7169     // LEVEL 4 always requires 128 bit encrytion key size
7170     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
7171         security_level = LEVEL_3;
7172     }
7173     return security_level;
7174 }
7175 
7176 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
7177     uint8_t event[4];
7178     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
7179     event[1] = sizeof(event) - 2;
7180     event[2] = discoverable;
7181     event[3] = connectable;
7182     hci_emit_event(event, sizeof(event), 1);
7183 }
7184 
7185 // query if remote side supports eSCO
7186 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
7187     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7188     if (!connection) return false;
7189     return (connection->remote_supported_features[0] & 1) != 0;
7190 }
7191 
7192 static bool hci_ssp_supported(hci_connection_t * connection){
7193     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
7194     return (connection->bonding_flags & mask) == mask;
7195 }
7196 
7197 // query if remote side supports SSP
7198 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
7199     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7200     if (!connection) return false;
7201     return hci_ssp_supported(connection) ? 1 : 0;
7202 }
7203 
7204 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
7205     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
7206 }
7207 
7208 /**
7209  * Check if remote supported features query has completed
7210  */
7211 bool hci_remote_features_available(hci_con_handle_t handle){
7212     hci_connection_t * connection = hci_connection_for_handle(handle);
7213     if (!connection) return false;
7214     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
7215 }
7216 
7217 /**
7218  * Trigger remote supported features query
7219  */
7220 
7221 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
7222     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
7223         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7224     }
7225 }
7226 
7227 void hci_remote_features_query(hci_con_handle_t con_handle){
7228     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7229     if (!connection) return;
7230     hci_trigger_remote_features_for_connection(connection);
7231     hci_run();
7232 }
7233 
7234 // GAP API
7235 /**
7236  * @bbrief enable/disable bonding. default is enabled
7237  * @praram enabled
7238  */
7239 void gap_set_bondable_mode(int enable){
7240     hci_stack->bondable = enable ? 1 : 0;
7241 }
7242 /**
7243  * @brief Get bondable mode.
7244  * @return 1 if bondable
7245  */
7246 int gap_get_bondable_mode(void){
7247     return hci_stack->bondable;
7248 }
7249 
7250 /**
7251  * @brief map link keys to security levels
7252  */
7253 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
7254     switch (link_key_type){
7255         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7256             return LEVEL_4;
7257         case COMBINATION_KEY:
7258         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7259             return LEVEL_3;
7260         default:
7261             return LEVEL_2;
7262     }
7263 }
7264 
7265 /**
7266  * @brief map link keys to secure connection yes/no
7267  */
7268 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
7269     switch (link_key_type){
7270         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7271         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7272             return true;
7273         default:
7274             return false;
7275     }
7276 }
7277 
7278 /**
7279  * @brief map link keys to authenticated
7280  */
7281 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
7282     switch (link_key_type){
7283         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7284         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7285             return true;
7286         default:
7287             return false;
7288     }
7289 }
7290 
7291 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
7292     log_info("gap_mitm_protection_required_for_security_level %u", level);
7293     return level > LEVEL_2;
7294 }
7295 
7296 /**
7297  * @brief get current security level
7298  */
7299 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
7300     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7301     if (!connection) return LEVEL_0;
7302     return gap_security_level_for_connection(connection);
7303 }
7304 
7305 /**
7306  * @brief request connection to device to
7307  * @result GAP_AUTHENTICATION_RESULT
7308  */
7309 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
7310     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7311     if (!connection){
7312         hci_emit_security_level(con_handle, LEVEL_0);
7313         return;
7314     }
7315 
7316     btstack_assert(hci_is_le_connection(connection) == false);
7317 
7318     // 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)
7319     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
7320     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
7321         requested_level = LEVEL_4;
7322     }
7323 
7324     gap_security_level_t current_level = gap_security_level(con_handle);
7325     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
7326         requested_level, connection->requested_security_level, current_level);
7327 
7328     // authentication active if authentication request was sent or planned level > 0
7329     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
7330     if (authentication_active){
7331         // authentication already active
7332         if (connection->requested_security_level < requested_level){
7333             // increase requested level as new level is higher
7334             // TODO: handle re-authentication when done
7335             connection->requested_security_level = requested_level;
7336         }
7337     } else {
7338         // no request active, notify if security sufficient
7339         if (requested_level <= current_level){
7340             hci_emit_security_level(con_handle, current_level);
7341             return;
7342         }
7343 
7344         // store request
7345         connection->requested_security_level = requested_level;
7346 
7347         // start to authenticate connection
7348         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
7349 
7350         // request remote features if not already active, also trigger hci_run
7351         hci_remote_features_query(con_handle);
7352     }
7353 }
7354 
7355 /**
7356  * @brief start dedicated bonding with device. disconnect after bonding
7357  * @param device
7358  * @param request MITM protection
7359  * @result GAP_DEDICATED_BONDING_COMPLETE
7360  */
7361 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
7362 
7363     // create connection state machine
7364     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
7365 
7366     if (!connection){
7367         return BTSTACK_MEMORY_ALLOC_FAILED;
7368     }
7369 
7370     // delete linkn key
7371     gap_drop_link_key_for_bd_addr(device);
7372 
7373     // configure LEVEL_2/3, dedicated bonding
7374     connection->state = SEND_CREATE_CONNECTION;
7375     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
7376     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
7377     connection->bonding_flags = BONDING_DEDICATED;
7378 
7379     // wait for GAP Security Result and send GAP Dedicated Bonding complete
7380 
7381     // handle: connnection failure (connection complete != ok)
7382     // handle: authentication failure
7383     // handle: disconnect on done
7384 
7385     hci_run();
7386 
7387     return 0;
7388 }
7389 
7390 void gap_set_local_name(const char * local_name){
7391     hci_stack->local_name = local_name;
7392     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
7393     // also update EIR if not set by user
7394     if (hci_stack->eir_data == NULL){
7395         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7396     }
7397     hci_run();
7398 }
7399 #endif
7400 
7401 
7402 #ifdef ENABLE_BLE
7403 
7404 #ifdef ENABLE_LE_CENTRAL
7405 void gap_start_scan(void){
7406     hci_stack->le_scanning_enabled = true;
7407     hci_run();
7408 }
7409 
7410 void gap_stop_scan(void){
7411     hci_stack->le_scanning_enabled = false;
7412     hci_run();
7413 }
7414 
7415 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
7416     hci_stack->le_scan_type          = scan_type;
7417     hci_stack->le_scan_filter_policy = scanning_filter_policy;
7418     hci_stack->le_scan_interval      = scan_interval;
7419     hci_stack->le_scan_window        = scan_window;
7420     hci_stack->le_scanning_param_update = true;
7421     hci_run();
7422 }
7423 
7424 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
7425     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
7426 }
7427 
7428 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
7429     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
7430     if (!conn){
7431         // disallow if le connection is already outgoing
7432         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7433             log_error("le connection already active");
7434             return ERROR_CODE_COMMAND_DISALLOWED;
7435         }
7436 
7437         log_info("gap_connect: no connection exists yet, creating context");
7438         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
7439         if (!conn){
7440             // notify client that alloc failed
7441             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7442             log_info("gap_connect: failed to alloc hci_connection_t");
7443             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
7444         }
7445 
7446         // set le connecting state
7447         if (hci_is_le_connection_type(addr_type)){
7448             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
7449         }
7450 
7451         conn->state = SEND_CREATE_CONNECTION;
7452         log_info("gap_connect: send create connection next");
7453         hci_run();
7454         return ERROR_CODE_SUCCESS;
7455     }
7456 
7457     if (!hci_is_le_connection(conn) ||
7458         (conn->state == SEND_CREATE_CONNECTION) ||
7459         (conn->state == SENT_CREATE_CONNECTION)) {
7460         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
7461         log_error("gap_connect: classic connection or connect is already being created");
7462         return GATT_CLIENT_IN_WRONG_STATE;
7463     }
7464 
7465     // check if connection was just disconnected
7466     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7467         log_info("gap_connect: send create connection (again)");
7468         conn->state = SEND_CREATE_CONNECTION;
7469         hci_run();
7470         return ERROR_CODE_SUCCESS;
7471     }
7472 
7473     log_info("gap_connect: context exists with state %u", conn->state);
7474     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
7475     hci_run();
7476     return ERROR_CODE_SUCCESS;
7477 }
7478 
7479 // @assumption: only a single outgoing LE Connection exists
7480 static hci_connection_t * gap_get_outgoing_connection(void){
7481     btstack_linked_item_t *it;
7482     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7483         hci_connection_t * conn = (hci_connection_t *) it;
7484         if (!hci_is_le_connection(conn)) continue;
7485         switch (conn->state){
7486             case SEND_CREATE_CONNECTION:
7487             case SENT_CREATE_CONNECTION:
7488             case SENT_CANCEL_CONNECTION:
7489                 return conn;
7490             default:
7491                 break;
7492         };
7493     }
7494     return NULL;
7495 }
7496 
7497 uint8_t gap_connect_cancel(void){
7498     hci_connection_t * conn;
7499     switch (hci_stack->le_connecting_request){
7500         case LE_CONNECTING_IDLE:
7501             break;
7502         case LE_CONNECTING_WHITELIST:
7503             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7504             hci_run();
7505             break;
7506         case LE_CONNECTING_DIRECT:
7507             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7508             conn = gap_get_outgoing_connection();
7509             if (conn == NULL){
7510                 hci_run();
7511             } else {
7512                 switch (conn->state){
7513                     case SEND_CREATE_CONNECTION:
7514                         // skip sending create connection and emit event instead
7515                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
7516                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
7517                         btstack_memory_hci_connection_free( conn );
7518                         break;
7519                     case SENT_CREATE_CONNECTION:
7520                         // request to send cancel connection
7521                         conn->state = SEND_CANCEL_CONNECTION;
7522                         hci_run();
7523                         break;
7524                     default:
7525                         break;
7526                 }
7527             }
7528             break;
7529         default:
7530             btstack_unreachable();
7531             break;
7532     }
7533     return ERROR_CODE_SUCCESS;
7534 }
7535 
7536 /**
7537  * @brief Set connection parameters for outgoing connections
7538  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
7539  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
7540  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
7541  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
7542  * @param conn_latency, default: 4
7543  * @param supervision_timeout (unit: 10ms), default: 720 ms
7544  * @param min_ce_length (unit: 0.625ms), default: 10 ms
7545  * @param max_ce_length (unit: 0.625ms), default: 30 ms
7546  */
7547 
7548 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
7549     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
7550     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
7551     hci_stack->le_connection_scan_interval = conn_scan_interval;
7552     hci_stack->le_connection_scan_window = conn_scan_window;
7553     hci_stack->le_connection_interval_min = conn_interval_min;
7554     hci_stack->le_connection_interval_max = conn_interval_max;
7555     hci_stack->le_connection_latency = conn_latency;
7556     hci_stack->le_supervision_timeout = supervision_timeout;
7557     hci_stack->le_minimum_ce_length = min_ce_length;
7558     hci_stack->le_maximum_ce_length = max_ce_length;
7559 }
7560 #endif
7561 
7562 /**
7563  * @brief Updates the connection parameters for a given LE connection
7564  * @param handle
7565  * @param conn_interval_min (unit: 1.25ms)
7566  * @param conn_interval_max (unit: 1.25ms)
7567  * @param conn_latency
7568  * @param supervision_timeout (unit: 10ms)
7569  * @return 0 if ok
7570  */
7571 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7572     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7573     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7574     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7575     connection->le_conn_interval_min = conn_interval_min;
7576     connection->le_conn_interval_max = conn_interval_max;
7577     connection->le_conn_latency = conn_latency;
7578     connection->le_supervision_timeout = supervision_timeout;
7579     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
7580     hci_run();
7581     return 0;
7582 }
7583 
7584 /**
7585  * @brief Request an update of the connection parameter for a given LE connection
7586  * @param handle
7587  * @param conn_interval_min (unit: 1.25ms)
7588  * @param conn_interval_max (unit: 1.25ms)
7589  * @param conn_latency
7590  * @param supervision_timeout (unit: 10ms)
7591  * @return 0 if ok
7592  */
7593 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7594     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7595     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7596     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7597     connection->le_conn_interval_min = conn_interval_min;
7598     connection->le_conn_interval_max = conn_interval_max;
7599     connection->le_conn_latency = conn_latency;
7600     connection->le_supervision_timeout = supervision_timeout;
7601     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
7602     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
7603     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
7604     return 0;
7605 }
7606 
7607 #ifdef ENABLE_LE_PERIPHERAL
7608 
7609 /**
7610  * @brief Set Advertisement Data
7611  * @param advertising_data_length
7612  * @param advertising_data (max 31 octets)
7613  * @note data is not copied, pointer has to stay valid
7614  */
7615 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
7616     hci_stack->le_advertisements_data_len = advertising_data_length;
7617     hci_stack->le_advertisements_data = advertising_data;
7618     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7619     hci_run();
7620 }
7621 
7622 /**
7623  * @brief Set Scan Response Data
7624  * @param advertising_data_length
7625  * @param advertising_data (max 31 octets)
7626  * @note data is not copied, pointer has to stay valid
7627  */
7628 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
7629     hci_stack->le_scan_response_data_len = scan_response_data_length;
7630     hci_stack->le_scan_response_data = scan_response_data;
7631     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7632     hci_run();
7633 }
7634 
7635 /**
7636  * @brief Set Advertisement Parameters
7637  * @param adv_int_min
7638  * @param adv_int_max
7639  * @param adv_type
7640  * @param direct_address_type
7641  * @param direct_address
7642  * @param channel_map
7643  * @param filter_policy
7644  *
7645  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
7646  */
7647  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
7648     uint8_t direct_address_typ, bd_addr_t direct_address,
7649     uint8_t channel_map, uint8_t filter_policy) {
7650 
7651     hci_stack->le_advertisements_interval_min = adv_int_min;
7652     hci_stack->le_advertisements_interval_max = adv_int_max;
7653     hci_stack->le_advertisements_type = adv_type;
7654     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
7655     hci_stack->le_advertisements_channel_map = channel_map;
7656     hci_stack->le_advertisements_filter_policy = filter_policy;
7657     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
7658                  6);
7659 
7660     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7661     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
7662     hci_run();
7663  }
7664 
7665 /**
7666  * @brief Enable/Disable Advertisements
7667  * @param enabled
7668  */
7669 void gap_advertisements_enable(int enabled){
7670     if (enabled == 0){
7671         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7672     } else {
7673         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
7674     }
7675     hci_update_advertisements_enabled_for_current_roles();
7676     hci_run();
7677 }
7678 
7679 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7680 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
7681     btstack_linked_list_iterator_t it;
7682     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
7683     while (btstack_linked_list_iterator_has_next(&it)){
7684         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
7685         if ( item->advertising_handle == advertising_handle ) {
7686             return item;
7687         }
7688     }
7689     return NULL;
7690 }
7691 
7692 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
7693     // find free advertisement handle
7694     uint8_t advertisement_handle;
7695     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
7696         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
7697     }
7698     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7699     // clear
7700     memset(storage, 0, sizeof(le_advertising_set_t));
7701     // copy params
7702     storage->advertising_handle = advertisement_handle;
7703     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7704     // add to list
7705     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
7706     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7707     *out_advertising_handle = advertisement_handle;
7708     // set tasks and start
7709     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7710     hci_run();
7711     return ERROR_CODE_SUCCESS;
7712 }
7713 
7714 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
7715     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7716     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7717     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7718     // set tasks and start
7719     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7720     hci_run();
7721     return ERROR_CODE_SUCCESS;
7722 }
7723 
7724 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
7725     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7726     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7727     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
7728     return ERROR_CODE_SUCCESS;
7729 }
7730 
7731 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
7732     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7733     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7734     memcpy(advertising_set->random_address, random_address, 6);
7735     // set tasks and start
7736     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7737     hci_run();
7738     return ERROR_CODE_SUCCESS;
7739 }
7740 
7741 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
7742     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7743     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7744     advertising_set->adv_data = advertising_data;
7745     advertising_set->adv_data_len = advertising_data_length;
7746     // set tasks and start
7747     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7748     hci_run();
7749     return ERROR_CODE_SUCCESS;
7750 }
7751 
7752 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){
7753     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7754     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7755     advertising_set->scan_data = scan_response_data;
7756     advertising_set->scan_data_len = scan_response_data_length;
7757     // set tasks and start
7758     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7759     hci_run();
7760     return ERROR_CODE_SUCCESS;
7761 }
7762 
7763 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
7764     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7765     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7766     advertising_set->enable_timeout = timeout;
7767     advertising_set->enable_max_scan_events = num_extended_advertising_events;
7768     // set tasks and start
7769     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
7770     hci_run();
7771     return ERROR_CODE_SUCCESS;
7772 }
7773 
7774 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
7775     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7776     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7777     // set tasks and start
7778     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7779     hci_run();
7780     return ERROR_CODE_SUCCESS;
7781 }
7782 
7783 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
7784     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7785     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7786     // set tasks and start
7787     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
7788     hci_run();
7789     return ERROR_CODE_SUCCESS;
7790 }
7791 
7792 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7793 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
7794     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7795     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7796     // periodic advertising requires neither connectable, scannable, legacy or anonymous
7797     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7798     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
7799     // set tasks and start
7800     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
7801     hci_run();
7802     return ERROR_CODE_SUCCESS;
7803 }
7804 
7805 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
7806     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7807     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7808     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
7809     return ERROR_CODE_SUCCESS;
7810 }
7811 
7812 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
7813     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7814     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7815     advertising_set->periodic_data = periodic_data;
7816     advertising_set->periodic_data_len = periodic_data_length;
7817     // set tasks and start
7818     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
7819     hci_run();
7820     return ERROR_CODE_SUCCESS;
7821 }
7822 
7823 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
7824     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7825     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7826     // set tasks and start
7827     advertising_set->periodic_include_adi = include_adi;
7828     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7829     hci_run();
7830     return ERROR_CODE_SUCCESS;
7831 }
7832 
7833 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
7834     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7835     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7836     // set tasks and start
7837     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7838     hci_run();
7839     return ERROR_CODE_SUCCESS;
7840 }
7841 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
7842 
7843 #endif
7844 
7845 #endif
7846 
7847 void hci_le_set_own_address_type(uint8_t own_address_type){
7848     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
7849     if (own_address_type == hci_stack->le_own_addr_type) return;
7850     hci_stack->le_own_addr_type = own_address_type;
7851 
7852 #ifdef ENABLE_LE_PERIPHERAL
7853     // update advertisement parameters, too
7854     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7855     hci_run();
7856 #endif
7857 #ifdef ENABLE_LE_CENTRAL
7858     // note: we don't update scan parameters or modify ongoing connection attempts
7859 #endif
7860 }
7861 
7862 void hci_le_random_address_set(const bd_addr_t random_address){
7863     memcpy(hci_stack->le_random_address, random_address, 6);
7864     hci_stack->le_random_address_set = true;
7865     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7866     hci_run();
7867 }
7868 
7869 #endif
7870 
7871 uint8_t gap_disconnect(hci_con_handle_t handle){
7872     hci_connection_t * conn = hci_connection_for_handle(handle);
7873     if (!conn){
7874         hci_emit_disconnection_complete(handle, 0);
7875         return 0;
7876     }
7877     // ignore if already disconnected
7878     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7879         return 0;
7880     }
7881     conn->state = SEND_DISCONNECT;
7882     hci_run();
7883     return 0;
7884 }
7885 
7886 int gap_read_rssi(hci_con_handle_t con_handle){
7887     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7888     if (hci_connection == NULL) return 0;
7889     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
7890     hci_run();
7891     return 1;
7892 }
7893 
7894 /**
7895  * @brief Get connection type
7896  * @param con_handle
7897  * @result connection_type
7898  */
7899 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
7900     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7901     if (!conn) return GAP_CONNECTION_INVALID;
7902     switch (conn->address_type){
7903         case BD_ADDR_TYPE_LE_PUBLIC:
7904         case BD_ADDR_TYPE_LE_RANDOM:
7905             return GAP_CONNECTION_LE;
7906         case BD_ADDR_TYPE_SCO:
7907             return GAP_CONNECTION_SCO;
7908         case BD_ADDR_TYPE_ACL:
7909             return GAP_CONNECTION_ACL;
7910         default:
7911             return GAP_CONNECTION_INVALID;
7912     }
7913 }
7914 
7915 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
7916     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7917     if (!conn) return HCI_ROLE_INVALID;
7918     return (hci_role_t) conn->role;
7919 }
7920 
7921 
7922 #ifdef ENABLE_CLASSIC
7923 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
7924     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7925     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7926     conn->request_role = role;
7927     hci_run();
7928     return ERROR_CODE_SUCCESS;
7929 }
7930 #endif
7931 
7932 #ifdef ENABLE_BLE
7933 
7934 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){
7935     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7936     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7937 
7938     conn->le_phy_update_all_phys    = all_phys;
7939     conn->le_phy_update_tx_phys     = tx_phys;
7940     conn->le_phy_update_rx_phys     = rx_phys;
7941     conn->le_phy_update_phy_options = phy_options;
7942 
7943     hci_run();
7944 
7945     return 0;
7946 }
7947 
7948 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
7949     // check if already in list
7950     btstack_linked_list_iterator_t it;
7951     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7952     while (btstack_linked_list_iterator_has_next(&it)) {
7953         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
7954         if (entry->address_type != address_type) {
7955             continue;
7956         }
7957         if (memcmp(entry->address, address, 6) != 0) {
7958             continue;
7959         }
7960 		// disallow if already scheduled to add
7961 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
7962 			return ERROR_CODE_COMMAND_DISALLOWED;
7963 		}
7964 		// still on controller, but scheduled to remove -> re-add
7965 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
7966 		return ERROR_CODE_SUCCESS;
7967     }
7968     // alloc and add to list
7969     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
7970     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
7971     entry->address_type = address_type;
7972     (void)memcpy(entry->address, address, 6);
7973     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
7974     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
7975     return ERROR_CODE_SUCCESS;
7976 }
7977 
7978 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7979     btstack_linked_list_iterator_t it;
7980     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7981     while (btstack_linked_list_iterator_has_next(&it)){
7982         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7983         if (entry->address_type != address_type) {
7984             continue;
7985         }
7986         if (memcmp(entry->address, address, 6) != 0) {
7987             continue;
7988         }
7989         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7990             // remove from controller if already present
7991             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7992         }  else {
7993             // directly remove entry from whitelist
7994             btstack_linked_list_iterator_remove(&it);
7995             btstack_memory_whitelist_entry_free(entry);
7996         }
7997         return ERROR_CODE_SUCCESS;
7998     }
7999     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8000 }
8001 
8002 static void hci_whitelist_clear(void){
8003     btstack_linked_list_iterator_t it;
8004     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8005     while (btstack_linked_list_iterator_has_next(&it)){
8006         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8007         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8008             // remove from controller if already present
8009             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8010             continue;
8011         }
8012         // directly remove entry from whitelist
8013         btstack_linked_list_iterator_remove(&it);
8014         btstack_memory_whitelist_entry_free(entry);
8015     }
8016 }
8017 
8018 // free all entries unconditionally
8019 static void hci_whitelist_free(void){
8020     btstack_linked_list_iterator_t lit;
8021     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
8022     while (btstack_linked_list_iterator_has_next(&lit)){
8023         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
8024         btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
8025         btstack_memory_whitelist_entry_free(entry);
8026     }
8027 }
8028 
8029 /**
8030  * @brief Clear Whitelist
8031  * @return 0 if ok
8032  */
8033 uint8_t gap_whitelist_clear(void){
8034     hci_whitelist_clear();
8035     hci_run();
8036     return ERROR_CODE_SUCCESS;
8037 }
8038 
8039 /**
8040  * @brief Add Device to Whitelist
8041  * @param address_typ
8042  * @param address
8043  * @return 0 if ok
8044  */
8045 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8046     uint8_t status = hci_whitelist_add(address_type, address);
8047     if (status){
8048         return status;
8049     }
8050     hci_run();
8051     return ERROR_CODE_SUCCESS;
8052 }
8053 
8054 /**
8055  * @brief Remove Device from Whitelist
8056  * @param address_typ
8057  * @param address
8058  * @return 0 if ok
8059  */
8060 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8061     uint8_t status = hci_whitelist_remove(address_type, address);
8062     if (status){
8063         return status;
8064     }
8065     hci_run();
8066     return ERROR_CODE_SUCCESS;
8067 }
8068 
8069 #ifdef ENABLE_LE_CENTRAL
8070 /**
8071  * @brief Connect with Whitelist
8072  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
8073  * @return - if ok
8074  */
8075 uint8_t gap_connect_with_whitelist(void){
8076     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8077         return ERROR_CODE_COMMAND_DISALLOWED;
8078     }
8079     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8080     hci_run();
8081     return ERROR_CODE_SUCCESS;
8082 }
8083 
8084 /**
8085  * @brief Auto Connection Establishment - Start Connecting to device
8086  * @param address_typ
8087  * @param address
8088  * @return 0 if ok
8089  */
8090 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
8091     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8092         return ERROR_CODE_COMMAND_DISALLOWED;
8093     }
8094 
8095     uint8_t status = hci_whitelist_add(address_type, address);
8096     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
8097         return status;
8098     }
8099 
8100     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8101 
8102     hci_run();
8103     return ERROR_CODE_SUCCESS;
8104 }
8105 
8106 /**
8107  * @brief Auto Connection Establishment - Stop Connecting to device
8108  * @param address_typ
8109  * @param address
8110  * @return 0 if ok
8111  */
8112 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
8113     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8114         return ERROR_CODE_COMMAND_DISALLOWED;
8115     }
8116 
8117     hci_whitelist_remove(address_type, address);
8118     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
8119         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8120     }
8121     hci_run();
8122     return 0;
8123 }
8124 
8125 /**
8126  * @brief Auto Connection Establishment - Stop everything
8127  * @note  Convenience function to stop all active auto connection attempts
8128  */
8129 uint8_t gap_auto_connection_stop_all(void){
8130     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
8131         return ERROR_CODE_COMMAND_DISALLOWED;
8132     }
8133     hci_whitelist_clear();
8134     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8135     hci_run();
8136     return ERROR_CODE_SUCCESS;
8137 }
8138 
8139 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
8140     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8141     if (!conn) return 0;
8142     return conn->le_connection_interval;
8143 }
8144 #endif
8145 #endif
8146 
8147 #ifdef ENABLE_CLASSIC
8148 /**
8149  * @brief Set Extended Inquiry Response data
8150  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
8151  * @note has to be done before stack starts up
8152  */
8153 void gap_set_extended_inquiry_response(const uint8_t * data){
8154     hci_stack->eir_data = data;
8155     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
8156     hci_run();
8157 }
8158 
8159 /**
8160  * @brief Start GAP Classic Inquiry
8161  * @param duration in 1.28s units
8162  * @return 0 if ok
8163  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
8164  */
8165 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
8166     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
8167     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8168     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
8169         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8170     }
8171     hci_stack->inquiry_state = duration_in_1280ms_units;
8172     hci_stack->inquiry_max_period_length = 0;
8173     hci_stack->inquiry_min_period_length = 0;
8174     hci_run();
8175     return 0;
8176 }
8177 
8178 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
8179     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
8180     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
8181     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8182     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8183     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8184     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8185 
8186     hci_stack->inquiry_state = duration;
8187     hci_stack->inquiry_max_period_length = max_period_length;
8188     hci_stack->inquiry_min_period_length = min_period_length;
8189     hci_run();
8190     return 0;
8191 }
8192 
8193 /**
8194  * @brief Stop GAP Classic Inquiry
8195  * @return 0 if ok
8196  */
8197 int gap_inquiry_stop(void){
8198     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
8199         // emit inquiry complete event, before it even started
8200         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
8201         hci_emit_event(event, sizeof(event), 1);
8202         return 0;
8203     }
8204     switch (hci_stack->inquiry_state){
8205         case GAP_INQUIRY_STATE_ACTIVE:
8206             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
8207             hci_run();
8208             return ERROR_CODE_SUCCESS;
8209         case GAP_INQUIRY_STATE_PERIODIC:
8210             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
8211             hci_run();
8212             return ERROR_CODE_SUCCESS;
8213         default:
8214             return ERROR_CODE_COMMAND_DISALLOWED;
8215     }
8216 }
8217 
8218 void gap_inquiry_set_lap(uint32_t lap){
8219     hci_stack->inquiry_lap = lap;
8220 }
8221 
8222 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
8223     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
8224     hci_stack->inquiry_scan_window   = inquiry_scan_window;
8225     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
8226     hci_run();
8227 }
8228 
8229 
8230 /**
8231  * @brief Remote Name Request
8232  * @param addr
8233  * @param page_scan_repetition_mode
8234  * @param clock_offset only used when bit 15 is set
8235  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
8236  */
8237 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
8238     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8239     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
8240     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
8241     hci_stack->remote_name_clock_offset = clock_offset;
8242     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
8243     hci_run();
8244     return 0;
8245 }
8246 
8247 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
8248     hci_stack->gap_pairing_state = state;
8249     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
8250     hci_run();
8251     return 0;
8252 }
8253 
8254 /**
8255  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
8256  * @param addr
8257  * @param pin_data
8258  * @param pin_len
8259  * @return 0 if ok
8260  */
8261 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
8262     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8263     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
8264     hci_stack->gap_pairing_pin_len = pin_len;
8265     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
8266 }
8267 
8268 /**
8269  * @brief Legacy Pairing Pin Code Response
8270  * @param addr
8271  * @param pin
8272  * @return 0 if ok
8273  */
8274 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
8275     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
8276 }
8277 
8278 /**
8279  * @brief Abort Legacy Pairing
8280  * @param addr
8281  * @param pin
8282  * @return 0 if ok
8283  */
8284 int gap_pin_code_negative(bd_addr_t addr){
8285     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8286     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
8287 }
8288 
8289 /**
8290  * @brief SSP Passkey Response
8291  * @param addr
8292  * @param passkey
8293  * @return 0 if ok
8294  */
8295 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
8296     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8297     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
8298     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
8299 }
8300 
8301 /**
8302  * @brief Abort SSP Passkey Entry/Pairing
8303  * @param addr
8304  * @param pin
8305  * @return 0 if ok
8306  */
8307 int gap_ssp_passkey_negative(const bd_addr_t addr){
8308     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8309     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
8310 }
8311 
8312 /**
8313  * @brief Accept SSP Numeric Comparison
8314  * @param addr
8315  * @param passkey
8316  * @return 0 if ok
8317  */
8318 int gap_ssp_confirmation_response(const bd_addr_t addr){
8319     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8320     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
8321 }
8322 
8323 /**
8324  * @brief Abort SSP Numeric Comparison/Pairing
8325  * @param addr
8326  * @param pin
8327  * @return 0 if ok
8328  */
8329 int gap_ssp_confirmation_negative(const bd_addr_t addr){
8330     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8331     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
8332 }
8333 
8334 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
8335 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
8336     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8337     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8338     connectionSetAuthenticationFlags(conn, flag);
8339     hci_run();
8340     return ERROR_CODE_SUCCESS;
8341 }
8342 #endif
8343 
8344 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
8345 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
8346     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
8347 }
8348 
8349 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
8350     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
8351 }
8352 #endif
8353 
8354 #ifdef ENABLE_CLASSIC_PAIRING_OOB
8355 /**
8356  * @brief Report Remote OOB Data
8357  * @param bd_addr
8358  * @param c_192 Simple Pairing Hash C derived from P-192 public key
8359  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
8360  * @param c_256 Simple Pairing Hash C derived from P-256 public key
8361  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
8362  */
8363 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){
8364     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8365     if (connection == NULL) {
8366         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8367     }
8368     connection->classic_oob_c_192 = c_192;
8369     connection->classic_oob_r_192 = r_192;
8370 
8371     // ignore P-256 if not supported by us
8372     if (hci_stack->secure_connections_active){
8373         connection->classic_oob_c_256 = c_256;
8374         connection->classic_oob_r_256 = r_256;
8375     }
8376 
8377     return ERROR_CODE_SUCCESS;
8378 }
8379 /**
8380  * @brief Generate new OOB data
8381  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
8382  */
8383 void gap_ssp_generate_oob_data(void){
8384     hci_stack->classic_read_local_oob_data = true;
8385     hci_run();
8386 }
8387 
8388 #endif
8389 
8390 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
8391 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
8392     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8393     if (connection == NULL) {
8394         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8395     }
8396 
8397     memcpy(connection->link_key, link_key, sizeof(link_key_t));
8398     connection->link_key_type = type;
8399 
8400     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
8401 }
8402 
8403 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
8404 /**
8405  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
8406  * @param inquiry_mode see bluetooth_defines.h
8407  */
8408 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
8409     hci_stack->inquiry_mode = inquiry_mode;
8410 }
8411 
8412 /**
8413  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
8414  */
8415 void hci_set_sco_voice_setting(uint16_t voice_setting){
8416     hci_stack->sco_voice_setting = voice_setting;
8417 }
8418 
8419 /**
8420  * @brief Get SCO Voice Setting
8421  * @return current voice setting
8422  */
8423 uint16_t hci_get_sco_voice_setting(void){
8424     return hci_stack->sco_voice_setting;
8425 }
8426 
8427 static int hci_have_usb_transport(void){
8428     if (!hci_stack->hci_transport) return 0;
8429     const char * transport_name = hci_stack->hci_transport->name;
8430     if (!transport_name) return 0;
8431     return (transport_name[0] == 'H') && (transport_name[1] == '2');
8432 }
8433 
8434 /** @brief Get SCO packet length for current SCO Voice setting
8435  *  @note  Using SCO packets of the exact length is required for USB transfer
8436  *  @return Length of SCO packets in bytes (not audio frames)
8437  */
8438 uint16_t hci_get_sco_packet_length(void){
8439     uint16_t sco_packet_length = 0;
8440 
8441 #ifdef ENABLE_SCO_OVER_HCI
8442     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8443     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8444 
8445     if (hci_have_usb_transport()){
8446         // see Core Spec for H2 USB Transfer.
8447         // 3 byte SCO header + 24 bytes per connection
8448         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
8449         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
8450     } else {
8451         // 3 byte SCO header + SCO packet size over the air (60 bytes)
8452         sco_packet_length = 3 + 60 * multiplier;
8453         // assert that it still fits inside an SCO buffer
8454         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
8455             sco_packet_length = 3 + 60;
8456         }
8457     }
8458 #endif
8459 
8460 #ifdef HAVE_SCO_TRANSPORT
8461     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8462     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8463     sco_packet_length = 3 + 60 * multiplier;
8464 #endif
8465     return sco_packet_length;
8466 }
8467 
8468 /**
8469 * @brief Sets the master/slave policy
8470 * @param policy (0: attempt to become master, 1: let connecting device decide)
8471 */
8472 void hci_set_master_slave_policy(uint8_t policy){
8473     hci_stack->master_slave_policy = policy;
8474 }
8475 
8476 #endif
8477 
8478 HCI_STATE hci_get_state(void){
8479     return hci_stack->state;
8480 }
8481 
8482 #ifdef ENABLE_CLASSIC
8483 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
8484     hci_stack->gap_classic_accept_callback = accept_callback;
8485 }
8486 #endif
8487 
8488 /**
8489  * @brief Set callback for Bluetooth Hardware Error
8490  */
8491 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
8492     hci_stack->hardware_error_callback = fn;
8493 }
8494 
8495 void hci_disconnect_all(void){
8496     btstack_linked_list_iterator_t it;
8497     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
8498     while (btstack_linked_list_iterator_has_next(&it)){
8499         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
8500         if (con->state == SENT_DISCONNECT) continue;
8501         con->state = SEND_DISCONNECT;
8502     }
8503     hci_run();
8504 }
8505 
8506 uint16_t hci_get_manufacturer(void){
8507     return hci_stack->manufacturer;
8508 }
8509 
8510 #ifdef ENABLE_BLE
8511 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
8512     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
8513     if (!hci_con) return NULL;
8514     return &hci_con->sm_connection;
8515 }
8516 
8517 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
8518 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
8519 #endif
8520 
8521 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
8522     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8523     if (hci_connection == NULL) return 0;
8524     if (hci_is_le_connection(hci_connection)){
8525 #ifdef ENABLE_BLE
8526         sm_connection_t * sm_conn = &hci_connection->sm_connection;
8527         if (sm_conn->sm_connection_encrypted) {
8528             return sm_conn->sm_actual_encryption_key_size;
8529         }
8530 #endif
8531     } else {
8532 #ifdef ENABLE_CLASSIC
8533         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
8534             return hci_connection->encryption_key_size;
8535         }
8536 #endif
8537     }
8538     return 0;
8539 }
8540 
8541 bool gap_authenticated(hci_con_handle_t con_handle){
8542     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8543     if (hci_connection == NULL) return false;
8544 
8545     switch (hci_connection->address_type){
8546 #ifdef ENABLE_BLE
8547         case BD_ADDR_TYPE_LE_PUBLIC:
8548         case BD_ADDR_TYPE_LE_RANDOM:
8549             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
8550             return hci_connection->sm_connection.sm_connection_authenticated != 0;
8551 #endif
8552 #ifdef ENABLE_CLASSIC
8553         case BD_ADDR_TYPE_SCO:
8554         case BD_ADDR_TYPE_ACL:
8555             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
8556 #endif
8557         default:
8558             return false;
8559     }
8560 }
8561 
8562 bool gap_secure_connection(hci_con_handle_t con_handle){
8563     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8564     if (hci_connection == NULL) return 0;
8565 
8566     switch (hci_connection->address_type){
8567 #ifdef ENABLE_BLE
8568         case BD_ADDR_TYPE_LE_PUBLIC:
8569         case BD_ADDR_TYPE_LE_RANDOM:
8570             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
8571             return hci_connection->sm_connection.sm_connection_sc != 0;
8572 #endif
8573 #ifdef ENABLE_CLASSIC
8574         case BD_ADDR_TYPE_SCO:
8575         case BD_ADDR_TYPE_ACL:
8576             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
8577 #endif
8578         default:
8579             return false;
8580     }
8581 }
8582 
8583 bool gap_bonded(hci_con_handle_t con_handle){
8584 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8585 	if (hci_connection == NULL) return 0;
8586 
8587 #ifdef ENABLE_CLASSIC
8588 	link_key_t link_key;
8589 	link_key_type_t link_key_type;
8590 #endif
8591 	switch (hci_connection->address_type){
8592 #ifdef ENABLE_BLE
8593 		case BD_ADDR_TYPE_LE_PUBLIC:
8594 		case BD_ADDR_TYPE_LE_RANDOM:
8595 			return hci_connection->sm_connection.sm_le_db_index >= 0;
8596 #endif
8597 #ifdef ENABLE_CLASSIC
8598 		case BD_ADDR_TYPE_SCO:
8599 		case BD_ADDR_TYPE_ACL:
8600 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
8601 #endif
8602 		default:
8603 			return false;
8604 	}
8605 }
8606 
8607 #ifdef ENABLE_BLE
8608 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
8609     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
8610     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
8611     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
8612     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
8613     return sm_conn->sm_connection_authorization_state;
8614 }
8615 #endif
8616 
8617 #ifdef ENABLE_CLASSIC
8618 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){
8619     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8620     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8621     conn->sniff_min_interval = sniff_min_interval;
8622     conn->sniff_max_interval = sniff_max_interval;
8623     conn->sniff_attempt = sniff_attempt;
8624     conn->sniff_timeout = sniff_timeout;
8625     hci_run();
8626     return 0;
8627 }
8628 
8629 /**
8630  * @brief Exit Sniff mode
8631  * @param con_handle
8632  @ @return 0 if ok
8633  */
8634 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
8635     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8636     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8637     conn->sniff_min_interval = 0xffff;
8638     hci_run();
8639     return 0;
8640 }
8641 
8642 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){
8643     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8644     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8645     conn->sniff_subrating_max_latency = max_latency;
8646     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
8647     conn->sniff_subrating_min_local_timeout = min_local_timeout;
8648     hci_run();
8649     return ERROR_CODE_SUCCESS;
8650 }
8651 
8652 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){
8653     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8654     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8655     conn->qos_service_type = service_type;
8656     conn->qos_token_rate = token_rate;
8657     conn->qos_peak_bandwidth = peak_bandwidth;
8658     conn->qos_latency = latency;
8659     conn->qos_delay_variation = delay_variation;
8660     hci_run();
8661     return ERROR_CODE_SUCCESS;
8662 }
8663 
8664 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
8665     hci_stack->new_page_scan_interval = page_scan_interval;
8666     hci_stack->new_page_scan_window = page_scan_window;
8667     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
8668     hci_run();
8669 }
8670 
8671 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
8672     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
8673     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
8674     hci_run();
8675 }
8676 
8677 void gap_set_page_timeout(uint16_t page_timeout){
8678     hci_stack->page_timeout = page_timeout;
8679     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
8680     hci_run();
8681 }
8682 
8683 #endif
8684 
8685 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
8686 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
8687     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
8688     if (le_device_db_index >= le_device_db_max_count()) return;
8689     uint8_t offset = le_device_db_index >> 3;
8690     uint8_t mask = 1 << (le_device_db_index & 7);
8691     hci_stack->le_resolving_list_add_entries[offset] |= mask;
8692     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
8693     	// note: go back to remove entries, otherwise, a remove + add will skip the add
8694         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
8695     }
8696 }
8697 
8698 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
8699 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
8700 	if (le_device_db_index >= le_device_db_max_count()) return;
8701 	uint8_t offset = le_device_db_index >> 3;
8702 	uint8_t mask = 1 << (le_device_db_index & 7);
8703 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
8704 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
8705 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
8706 	}
8707 }
8708 
8709 uint8_t gap_load_resolving_list_from_le_device_db(void){
8710     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
8711 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
8712 	}
8713 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
8714 		// restart le resolving list update
8715 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
8716 	}
8717 	return ERROR_CODE_SUCCESS;
8718 }
8719 #endif
8720 
8721 #ifdef ENABLE_BLE
8722 #ifdef ENABLE_LE_CENTRAL
8723 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8724 
8725 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8726     // check if already in list
8727     btstack_linked_list_iterator_t it;
8728     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8729     while (btstack_linked_list_iterator_has_next(&it)) {
8730         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
8731         if (entry->sid != advertising_sid) {
8732             continue;
8733         }
8734         if (entry->address_type != address_type) {
8735             continue;
8736         }
8737         if (memcmp(entry->address, address, 6) != 0) {
8738             continue;
8739         }
8740         // disallow if already scheduled to add
8741         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
8742             return ERROR_CODE_COMMAND_DISALLOWED;
8743         }
8744         // still on controller, but scheduled to remove -> re-add
8745         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8746         return ERROR_CODE_SUCCESS;
8747     }
8748     // alloc and add to list
8749     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
8750     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8751     entry->sid = advertising_sid;
8752     entry->address_type = address_type;
8753     (void)memcpy(entry->address, address, 6);
8754     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8755     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
8756     return ERROR_CODE_SUCCESS;
8757 }
8758 
8759 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8760     btstack_linked_list_iterator_t it;
8761     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8762     while (btstack_linked_list_iterator_has_next(&it)){
8763         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8764         if (entry->sid != advertising_sid) {
8765             continue;
8766         }
8767         if (entry->address_type != address_type) {
8768             continue;
8769         }
8770         if (memcmp(entry->address, address, 6) != 0) {
8771             continue;
8772         }
8773         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8774             // remove from controller if already present
8775             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8776         }  else {
8777             // directly remove entry from whitelist
8778             btstack_linked_list_iterator_remove(&it);
8779             btstack_memory_periodic_advertiser_list_entry_free(entry);
8780         }
8781         return ERROR_CODE_SUCCESS;
8782     }
8783     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8784 }
8785 
8786 static void hci_periodic_advertiser_list_clear(void){
8787     btstack_linked_list_iterator_t it;
8788     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8789     while (btstack_linked_list_iterator_has_next(&it)){
8790         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8791         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8792             // remove from controller if already present
8793             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8794             continue;
8795         }
8796         // directly remove entry from whitelist
8797         btstack_linked_list_iterator_remove(&it);
8798         btstack_memory_periodic_advertiser_list_entry_free(entry);
8799     }
8800 }
8801 
8802 // free all entries unconditionally
8803 static void hci_periodic_advertiser_list_free(void){
8804     btstack_linked_list_iterator_t lit;
8805     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
8806     while (btstack_linked_list_iterator_has_next(&lit)){
8807         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
8808         btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
8809         btstack_memory_periodic_advertiser_list_entry_free(entry);
8810     }
8811 }
8812 
8813 uint8_t gap_periodic_advertiser_list_clear(void){
8814     hci_periodic_advertiser_list_clear();
8815     hci_run();
8816     return ERROR_CODE_SUCCESS;
8817 }
8818 
8819 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8820     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
8821     if (status){
8822         return status;
8823     }
8824     hci_run();
8825     return ERROR_CODE_SUCCESS;
8826 }
8827 
8828 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8829     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
8830     if (status){
8831         return status;
8832     }
8833     hci_run();
8834     return ERROR_CODE_SUCCESS;
8835 }
8836 
8837 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
8838                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
8839     // abort if already active
8840     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
8841         return ERROR_CODE_COMMAND_DISALLOWED;
8842     }
8843     // store request
8844     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
8845     hci_stack->le_periodic_sync_options = options;
8846     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
8847     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
8848     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
8849     hci_stack->le_periodic_sync_skip = skip;
8850     hci_stack->le_periodic_sync_timeout = sync_timeout;
8851     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
8852 
8853     hci_run();
8854     return ERROR_CODE_SUCCESS;
8855 }
8856 
8857 uint8_t gap_periodic_advertising_create_sync_cancel(void){
8858     // abort if not requested
8859     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
8860         return ERROR_CODE_COMMAND_DISALLOWED;
8861     }
8862     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
8863     hci_run();
8864     return ERROR_CODE_SUCCESS;
8865 }
8866 
8867 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
8868     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
8869         return ERROR_CODE_COMMAND_DISALLOWED;
8870     }
8871     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
8872     hci_run();
8873     return ERROR_CODE_SUCCESS;
8874 }
8875 
8876 #endif
8877 #endif
8878 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
8879 static uint8_t hci_iso_stream_create(hci_con_handle_t con_handle, uint8_t big_handle) {
8880     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
8881     if (iso_stream == NULL){
8882         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8883     } else {
8884         iso_stream->state = HCI_ISO_STREAM_STATE_REQUESTED;
8885         iso_stream->con_handle = con_handle;
8886         iso_stream->big_handle = big_handle;
8887         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
8888         return ERROR_CODE_SUCCESS;
8889     }
8890 }
8891 
8892 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
8893     btstack_linked_list_iterator_t it;
8894     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
8895     while (btstack_linked_list_iterator_has_next(&it)){
8896         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
8897         if (iso_stream->con_handle == con_handle ) {
8898             return iso_stream;
8899         }
8900     }
8901     return NULL;
8902 }
8903 
8904 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
8905     log_info("hci_iso_stream_finalize con_handle 0x%04x, big_handle 0x%02x", iso_stream->con_handle, iso_stream->big_handle);
8906     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
8907     btstack_memory_hci_iso_stream_free(iso_stream);
8908 }
8909 
8910 static void hci_iso_stream_requested_finalize(uint8_t big_handle) {
8911     btstack_linked_list_iterator_t it;
8912     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
8913     while (btstack_linked_list_iterator_has_next(&it)){
8914         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
8915         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
8916             (iso_stream->big_handle == big_handle)){
8917             btstack_linked_list_iterator_remove(&it);
8918             btstack_memory_hci_iso_stream_free(iso_stream);
8919         }
8920     }
8921 }
8922 static void hci_iso_stream_requested_confirm(uint8_t big_handle){
8923     btstack_linked_list_iterator_t it;
8924     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
8925     while (btstack_linked_list_iterator_has_next(&it)){
8926         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
8927         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
8928             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
8929         }
8930     }
8931 }
8932 
8933 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
8934     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
8935     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
8936     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
8937     return (sdu_len_offset + 2 + sdu_len) == size;
8938 }
8939 
8940 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){
8941     if (hci_stack->iso_packet_handler == NULL) {
8942         return;
8943     }
8944     if (size < 4) {
8945         return;
8946     }
8947 
8948     // parse header
8949     uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0);
8950     uint16_t iso_data_len = little_endian_read_16(packet, 2);
8951     hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff);
8952     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
8953     uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3;
8954 
8955     // assert packet is complete
8956     if ((iso_data_len + 4u) != size){
8957         return;
8958     }
8959 
8960     if ((pb_flag & 0x01) == 0){
8961         if (pb_flag == 0x02){
8962             // The ISO_Data_Load field contains a header and a complete SDU.
8963             if (hci_iso_sdu_complete(packet, size)) {
8964                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
8965             }
8966         } else {
8967             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
8968             if (iso_stream == NULL){
8969                 return;
8970             }
8971             if (size > HCI_ISO_PAYLOAD_SIZE){
8972                 return;
8973             }
8974             memcpy(iso_stream->reassembly_buffer, packet, size);
8975             // fix pb_flag
8976             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
8977             iso_stream->reassembly_pos = size;
8978         }
8979     } else {
8980         // iso_data_load contains continuation or last fragment of an SDU
8981         uint8_t  ts_flag = (conn_handle_and_flags >> 14) & 1;
8982         if (ts_flag != 0){
8983            return;
8984         }
8985         // append fragment
8986         if (iso_stream == NULL){
8987             return;
8988         }
8989         if (iso_stream->reassembly_pos == 0){
8990             return;
8991         }
8992         if ((iso_stream->reassembly_pos + iso_data_len) > size){
8993             // reset reassembly buffer
8994             iso_stream->reassembly_pos = 0;
8995             return;
8996         }
8997         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len);
8998         iso_stream->reassembly_pos += iso_data_len;
8999 
9000         // deliver if last fragment and SDU complete
9001         if (pb_flag == 0x03){
9002             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
9003                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
9004             }
9005             iso_stream->reassembly_pos = 0;
9006         }
9007     }
9008 }
9009 
9010 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
9011     uint8_t event [6 + (MAX_NR_BIS * 2)];
9012     uint16_t pos = 0;
9013     event[pos++] = HCI_EVENT_META_GAP;
9014     event[pos++] = 4 + (2 * big->num_bis);
9015     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
9016     event[pos++] = status;
9017     event[pos++] = big->big_handle;
9018     event[pos++] = big->num_bis;
9019     uint8_t i;
9020     for (i=0;i<big->num_bis;i++){
9021         little_endian_store_16(event, pos, big->bis_con_handles[i]);
9022         pos += 2;
9023     }
9024     hci_emit_event(event, pos, 0);
9025 }
9026 
9027 static void hci_emit_big_terminated(const le_audio_big_t * big){
9028     uint8_t event [4];
9029     uint16_t pos = 0;
9030     event[pos++] = HCI_EVENT_META_GAP;
9031     event[pos++] = 2;
9032     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
9033     event[pos++] = big->big_handle;
9034     hci_emit_event(event, pos, 0);
9035 }
9036 
9037 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
9038     uint8_t event [6 + (MAX_NR_BIS * 2)];
9039     uint16_t pos = 0;
9040     event[pos++] = HCI_EVENT_META_GAP;
9041     event[pos++] = 4;
9042     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
9043     event[pos++] = status;
9044     event[pos++] = big_sync->big_handle;
9045     event[pos++] = big_sync->num_bis;
9046     uint8_t i;
9047     for (i=0;i<big_sync->num_bis;i++){
9048         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
9049         pos += 2;
9050     }
9051     hci_emit_event(event, pos, 0);
9052 }
9053 
9054 static void hci_emit_big_sync_stopped(const le_audio_big_sync_t * big_sync){
9055     uint8_t event [4];
9056     uint16_t pos = 0;
9057     event[pos++] = HCI_EVENT_META_GAP;
9058     event[pos++] = 2;
9059     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
9060     event[pos++] = big_sync->big_handle;
9061     hci_emit_event(event, pos, 0);
9062 }
9063 
9064 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
9065     uint8_t event[6];
9066     uint16_t pos = 0;
9067     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
9068     event[pos++] = sizeof(event) - 2;
9069     event[pos++] = big->big_handle;
9070     event[pos++] = bis_index;
9071     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
9072     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
9073 }
9074 
9075 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
9076     btstack_linked_list_iterator_t it;
9077     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9078     while (btstack_linked_list_iterator_has_next(&it)){
9079         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9080         if ( big->big_handle == big_handle ) {
9081             return big;
9082         }
9083     }
9084     return NULL;
9085 }
9086 
9087 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
9088     btstack_linked_list_iterator_t it;
9089     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
9090     while (btstack_linked_list_iterator_has_next(&it)){
9091         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
9092         if ( big_sync->big_handle == big_handle ) {
9093             return big_sync;
9094         }
9095     }
9096     return NULL;
9097 }
9098 
9099 static void hci_iso_notify_can_send_now(void){
9100     btstack_linked_list_iterator_t it;
9101     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9102     while (btstack_linked_list_iterator_has_next(&it)){
9103         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9104         if (big->can_send_now_requested){
9105             // check if no outgoing iso packets pending and no can send now have to be emitted
9106             uint8_t i;
9107             bool can_send = true;
9108             for (i=0;i<big->num_bis;i++){
9109                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9110                 if ((iso_stream == NULL) || (iso_stream->num_packets_sent > 0) || (iso_stream->emit_ready_to_send)){
9111                     can_send = false;
9112                     break;
9113                 }
9114             }
9115             if (can_send){
9116                 // propagate can send now to individual streams
9117                 big->can_send_now_requested = false;
9118                 for (i=0;i<big->num_bis;i++){
9119                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9120                     iso_stream->emit_ready_to_send = true;
9121                 }
9122             }
9123         }
9124     }
9125 
9126     if (hci_stack->hci_packet_buffer_reserved) return;
9127 
9128     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9129     while (btstack_linked_list_iterator_has_next(&it)){
9130         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9131         // report bis ready
9132         uint8_t i;
9133         for (i=0;i<big->num_bis;i++){
9134             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9135             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
9136                 iso_stream->emit_ready_to_send = false;
9137                 hci_emit_bis_can_send_now(big, i);
9138                 break;
9139             }
9140         }
9141     }
9142 }
9143 
9144 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
9145     if (hci_big_for_handle(big_params->big_handle) != NULL){
9146         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9147     }
9148     if (big_params->num_bis == 0){
9149         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9150     }
9151     if (big_params->num_bis > MAX_NR_BIS){
9152         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9153     }
9154 
9155     // reserve ISO Streams
9156     uint8_t i;
9157     uint8_t status = ERROR_CODE_SUCCESS;
9158     for (i=0;i<big_params->num_bis;i++){
9159         status = hci_iso_stream_create(HCI_CON_HANDLE_INVALID, big_params->big_handle);
9160         if (status != ERROR_CODE_SUCCESS) {
9161             break;
9162         }
9163     }
9164 
9165     // free structs on error
9166     if (status != ERROR_CODE_SUCCESS){
9167         hci_iso_stream_requested_finalize(big_params->big_handle);
9168         return status;
9169     }
9170 
9171     le_audio_big_t * big = storage;
9172     big->big_handle = big_params->big_handle;
9173     big->params = big_params;
9174     big->state = LE_AUDIO_BIG_STATE_CREATE;
9175     big->num_bis = big_params->num_bis;
9176     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9177 
9178     hci_run();
9179 
9180     return ERROR_CODE_SUCCESS;
9181 }
9182 
9183 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
9184     if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){
9185         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9186     }
9187     if (big_sync_params->num_bis == 0){
9188         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9189     }
9190     if (big_sync_params->num_bis > MAX_NR_BIS){
9191         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9192     }
9193 
9194     le_audio_big_sync_t * big_sync = storage;
9195     big_sync->big_handle = big_sync_params->big_handle;
9196     big_sync->params = big_sync_params;
9197     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
9198     big_sync->num_bis = big_sync_params->num_bis;
9199     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9200 
9201     hci_run();
9202 
9203     return ERROR_CODE_SUCCESS;
9204 }
9205 
9206 uint8_t gap_big_terminate(uint8_t big_handle){
9207     le_audio_big_t * big = hci_big_for_handle(big_handle);
9208     if (big == NULL){
9209         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9210     }
9211     switch (big->state){
9212         case LE_AUDIO_BIG_STATE_CREATE:
9213             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9214             hci_emit_big_terminated(big);
9215             break;
9216         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9217             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9218             break;
9219         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9220         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9221         case LE_AUDIO_BIG_STATE_ACTIVE:
9222             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
9223             hci_run();
9224             break;
9225         default:
9226             return ERROR_CODE_COMMAND_DISALLOWED;
9227     }
9228     return ERROR_CODE_SUCCESS;
9229 }
9230 
9231 uint8_t gap_big_sync_terminate(uint8_t big_handle){
9232     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
9233     if (big_sync == NULL){
9234         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9235     }
9236     switch (big_sync->state){
9237         case LE_AUDIO_BIG_STATE_CREATE:
9238             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9239             hci_emit_big_sync_stopped(big_sync);
9240             break;
9241         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9242             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9243             break;
9244         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9245         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9246         case LE_AUDIO_BIG_STATE_ACTIVE:
9247             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
9248             hci_run();
9249             break;
9250         default:
9251             return ERROR_CODE_COMMAND_DISALLOWED;
9252     }
9253     return ERROR_CODE_SUCCESS;
9254 }
9255 
9256 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
9257     le_audio_big_t * big = hci_big_for_handle(big_handle);
9258     if (big == NULL){
9259         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9260     }
9261     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
9262         return ERROR_CODE_COMMAND_DISALLOWED;
9263     }
9264     big->can_send_now_requested = true;
9265     hci_iso_notify_can_send_now();
9266     return ERROR_CODE_SUCCESS;
9267 }
9268 #endif
9269 #endif /* ENABLE_BLE */
9270 
9271 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
9272 void hci_setup_test_connections_fuzz(void){
9273     hci_connection_t * conn;
9274 
9275     // default address: 66:55:44:33:00:01
9276     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
9277 
9278     // setup Controller info
9279     hci_stack->num_cmd_packets = 255;
9280     hci_stack->acl_packets_total_num = 255;
9281 
9282     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
9283     addr[5] = 0x01;
9284     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9285     conn->con_handle = addr[5];
9286     conn->role  = HCI_ROLE_SLAVE;
9287     conn->state = RECEIVED_CONNECTION_REQUEST;
9288     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9289 
9290     // setup incoming Classic SCO connection with con handle 0x0002
9291     addr[5] = 0x02;
9292     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
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 ready Classic ACL connection with con handle 0x0003
9299     addr[5] = 0x03;
9300     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9301     conn->con_handle = addr[5];
9302     conn->role  = HCI_ROLE_SLAVE;
9303     conn->state = OPEN;
9304     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9305 
9306     // setup ready Classic SCO connection with con handle 0x0004
9307     addr[5] = 0x04;
9308     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
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 LE ACL connection with con handle 0x005 and public address
9315     addr[5] = 0x05;
9316     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
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     conn->sm_connection.sm_connection_encrypted = 1;
9322 }
9323 
9324 void hci_free_connections_fuzz(void){
9325     btstack_linked_list_iterator_t it;
9326     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9327     while (btstack_linked_list_iterator_has_next(&it)){
9328         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9329         btstack_linked_list_iterator_remove(&it);
9330         btstack_memory_hci_connection_free(con);
9331     }
9332 }
9333 void hci_simulate_working_fuzz(void){
9334     hci_stack->le_scanning_param_update = false;
9335     hci_init_done();
9336     hci_stack->num_cmd_packets = 255;
9337 }
9338 #endif
9339