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