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