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