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