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