xref: /btstack/src/hci.c (revision c3d6a72ba353a6ffbaf78a484d6a4d9f509beeef)
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 		if (status == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
3350 		    // reset state
3351             hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3352 			// get outgoing connection conn struct for direct connect
3353             if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
3354                 conn = gap_get_outgoing_le_connection();
3355                 conn->state = SEND_CREATE_CONNECTION;
3356             }
3357 		}
3358 
3359 		// free connection if cancelled by user (request == IDLE)
3360 		if ((conn != NULL) && (hci_stack->le_connecting_request == LE_CONNECTING_IDLE)){
3361 			// remove entry
3362 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3363 			btstack_memory_hci_connection_free( conn );
3364 		}
3365 		return;
3366 	}
3367 #endif
3368 
3369 	// on success, both hosts receive connection complete event
3370     if (role == HCI_ROLE_MASTER){
3371 #ifdef ENABLE_LE_CENTRAL
3372 		// if we're master, it was an outgoing connection
3373 		// note: no hci_connection_t object exists yet for connect with whitelist
3374 
3375         // if a identity addresses was used without enhanced connection complete event,
3376         // the connection complete event contains the current random address of the peer device.
3377         // This random address is needed in the case of a re-pairing
3378         if (hci_event_le_meta_get_subevent_code(hci_event) == HCI_SUBEVENT_LE_CONNECTION_COMPLETE){
3379             conn = gap_get_outgoing_le_connection();
3380             // if outgoing connection object is available, check if identity address was used.
3381             // if yes, track resolved random address and provide rpa
3382             // note: we don't update hci le subevent connection complete
3383             if (conn != NULL){
3384                 if (hci_is_le_identity_address_type(conn->address_type)){
3385                     memcpy(&gap_event[20], &gap_event[8], 6);
3386                     gap_event[7] = conn->address_type;
3387                     reverse_bd_addr(conn->address, &gap_event[8]);
3388                 }
3389             }
3390         }
3391 
3392         // we're done with it
3393         hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
3394         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3395 #endif
3396 	} else {
3397 #ifdef ENABLE_LE_PERIPHERAL
3398 		// if we're slave, it was an incoming connection, advertisements have stopped
3399         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
3400 #endif
3401 	}
3402 
3403 	// LE connections are auto-accepted, so just create a connection if there isn't one already
3404 	if (!conn){
3405 		conn = create_connection_for_bd_addr_and_type(addr, addr_type, role);
3406 	}
3407 
3408 	// no memory, sorry.
3409 	if (!conn){
3410 		return;
3411 	}
3412 
3413 	conn->state = OPEN;
3414 	conn->con_handle             = gap_subevent_le_connection_complete_get_connection_handle(gap_event);
3415     conn->le_connection_interval = conn_interval;
3416 
3417 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3418     // workaround: PAST doesn't work without LE Read Remote Features on PacketCraft Controller with LMP 568B
3419     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_REMOTE_FEATURES)){
3420         conn->gap_connection_tasks = GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
3421     }
3422 #endif
3423 
3424 #ifdef ENABLE_LE_PERIPHERAL
3425 	if (role == HCI_ROLE_SLAVE){
3426 		hci_update_advertisements_enabled_for_current_roles();
3427 	}
3428 #endif
3429 
3430     // init unenhanced att bearer mtu
3431     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3432     conn->att_connection.mtu_exchanged = false;
3433 
3434     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
3435 
3436 	// restart timer
3437 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3438 	// btstack_run_loop_add_timer(&conn->timeout);
3439 
3440 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3441 
3442     // emit GAP_SUBEVENT_LE_CONNECTION_COMPLETE
3443     hci_emit_event(gap_event, sizeof(gap_event), 1);
3444 
3445     // emit BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3446 	hci_emit_nr_connections_changed();
3447 }
3448 #endif
3449 
3450 #ifdef ENABLE_CLASSIC
3451 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){
3452     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
3453     // LEVEL_4 is tested by l2cap
3454     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
3455     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
3456     if (level >= LEVEL_3){
3457         // MITM not possible without keyboard or display
3458         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3459         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3460 
3461         // MITM possible if one side has keyboard and the other has keyboard or display
3462         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3463         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3464 
3465         // MITM not possible if one side has only display and other side has no keyboard
3466         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3467         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3468     }
3469     // LEVEL 2 requires SSP, which is a given
3470     return true;
3471 }
3472 
3473 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
3474     // get requested security level
3475     gap_security_level_t requested_security_level = conn->requested_security_level;
3476     if (hci_stack->gap_secure_connections_only_mode){
3477         requested_security_level = LEVEL_4;
3478     }
3479 
3480     // assess security: LEVEL 4 requires SC
3481     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
3482     if ((requested_security_level == LEVEL_4) &&
3483         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
3484         !hci_remote_sc_enabled(conn)){
3485         log_info("Level 4 required, but SC not supported -> abort");
3486         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3487         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3488         return;
3489     }
3490 
3491     // assess bonding requirements: abort if remote in dedicated bonding mode but we are non-bonding
3492     // - GAP/MOD/NBON/BV-02-C
3493     // - GAP/DM/NBON/BV-01-C
3494     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3495         switch (conn->io_cap_response_auth_req){
3496             case SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING:
3497             case SSP_IO_AUTHREQ_MITM_PROTECTION_REQUIRED_DEDICATED_BONDING:
3498                 if (hci_stack->bondable == false){
3499                     log_info("Dedicated vs. non-bondable -> abort");
3500                     hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3501                     connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3502                     return;
3503                 }
3504             default:
3505                 break;
3506         }
3507     }
3508 
3509     // assess security based on io capabilities
3510     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3511         // responder: fully validate io caps of both sides as well as OOB data
3512         bool security_possible = false;
3513         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3514 
3515 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3516         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3517         // so we merge the OOB data availability
3518         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3519         if (conn->classic_oob_c_192 != NULL){
3520             have_oob_data |= 1;
3521         }
3522         if (conn->classic_oob_c_256 != NULL){
3523             have_oob_data |= 2;
3524         }
3525         // for up to Level 3, either P-192 as well as P-256 will do
3526         // 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
3527         // if remote does not SC, we should not receive P-256 data either
3528         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3529             security_possible = true;
3530         }
3531         // for Level 4, P-256 is needed
3532         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3533             security_possible = true;
3534         }
3535 #endif
3536 
3537         if (security_possible == false){
3538             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3539             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3540             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3541             return;
3542         }
3543     } else {
3544         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
3545 #ifndef ENABLE_CLASSIC_PAIRING_OOB
3546 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3547         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3548             log_info("Level 3+ required, but no input/output -> abort");
3549             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3550             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3551             return;
3552         }
3553 #endif
3554 #endif
3555     }
3556 
3557 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3558     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3559         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3560     } else {
3561         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3562     }
3563 #endif
3564 }
3565 
3566 #endif
3567 
3568 static void event_handler(uint8_t *packet, uint16_t size){
3569 
3570     uint16_t event_length = packet[1];
3571 
3572     // assert packet is complete
3573     if (size != (event_length + 2u)){
3574         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
3575         return;
3576     }
3577 
3578     hci_con_handle_t handle;
3579     hci_connection_t * conn;
3580     int i;
3581 
3582 #ifdef ENABLE_CLASSIC
3583     hci_link_type_t link_type;
3584     bd_addr_t addr;
3585     bd_addr_type_t addr_type;
3586 #endif
3587 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3588     hci_iso_stream_t * iso_stream;
3589     le_audio_big_t   * big;
3590     le_audio_big_sync_t * big_sync;
3591 #endif
3592 #if defined(ENABLE_LE_ISOCHRONOUS_STREAMS) || defined(ENABLE_LE_EXTENDED_ADVERTISING)
3593     btstack_linked_list_iterator_t it;
3594 #endif
3595 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3596     uint8_t advertising_handle;
3597 #endif
3598 
3599     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
3600 
3601     switch (hci_event_packet_get_type(packet)) {
3602 
3603         case HCI_EVENT_COMMAND_COMPLETE:
3604             handle_command_complete_event(packet, size);
3605             break;
3606 
3607         case HCI_EVENT_COMMAND_STATUS:
3608             handle_command_status_event(packet, size);
3609             break;
3610 
3611         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
3612             if (size < 3) return;
3613             uint16_t num_handles = packet[2];
3614             if (size != (3u + num_handles * 4u)) return;
3615 #ifdef ENABLE_CLASSIC
3616             bool notify_sco = false;
3617 #endif
3618 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3619             bool notify_iso = false;
3620 #endif
3621             uint16_t offset = 3;
3622             for (i=0; i<num_handles;i++){
3623                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
3624                 offset += 2u;
3625                 uint16_t num_packets = little_endian_read_16(packet, offset);
3626                 offset += 2u;
3627 
3628                 conn = hci_connection_for_handle(handle);
3629                 if (conn != NULL) {
3630 
3631                     if (conn->num_packets_sent >= num_packets) {
3632                         conn->num_packets_sent -= num_packets;
3633                     } else {
3634                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3635                         conn->num_packets_sent = 0;
3636                     }
3637                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3638 #ifdef ENABLE_CLASSIC
3639                     if (conn->address_type == BD_ADDR_TYPE_SCO){
3640                         notify_sco = true;
3641                     }
3642 #endif
3643                 }
3644 
3645 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
3646                 hci_controller_dump_packets();
3647 #endif
3648 
3649 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3650                 if (conn == NULL){
3651                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle);
3652                     if (iso_stream != NULL){
3653                         if (iso_stream->num_packets_sent >= num_packets) {
3654                             iso_stream->num_packets_sent -= num_packets;
3655                         } else {
3656                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3657                             iso_stream->num_packets_sent = 0;
3658                         }
3659                         if (iso_stream->iso_type == HCI_ISO_TYPE_BIS){
3660                             le_audio_big_t * big = hci_big_for_handle(iso_stream->group_id);
3661                             if (big != NULL){
3662                                 big->num_completed_timestamp_current_valid = true;
3663                                 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms();
3664                             }
3665                         }
3666                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3667                                  num_packets, handle, iso_stream->num_packets_sent);
3668                         notify_iso = true;
3669                     }
3670                 }
3671 #endif
3672             }
3673 
3674 #ifdef ENABLE_CLASSIC
3675             if (notify_sco){
3676                 hci_notify_if_sco_can_send_now();
3677             }
3678 #endif
3679 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3680             if (notify_iso){
3681                 hci_iso_notify_can_send_now();
3682             }
3683 #endif
3684             break;
3685         }
3686 
3687 #ifdef ENABLE_CLASSIC
3688         case HCI_EVENT_FLUSH_OCCURRED:
3689             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
3690             handle = hci_event_flush_occurred_get_handle(packet);
3691             conn = hci_connection_for_handle(handle);
3692             if (conn) {
3693                 log_info("Flush occurred, disconnect 0x%04x", handle);
3694                 conn->state = SEND_DISCONNECT;
3695             }
3696             break;
3697 
3698         case HCI_EVENT_INQUIRY_COMPLETE:
3699             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3700                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3701                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
3702                 hci_emit_event(event, sizeof(event), 1);
3703             }
3704             break;
3705         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3706             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3707                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3708             }
3709             break;
3710         case HCI_EVENT_CONNECTION_REQUEST:
3711             reverse_bd_addr(&packet[2], addr);
3712             link_type = (hci_link_type_t) packet[11];
3713 
3714             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
3715             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
3716                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
3717                 bd_addr_copy(hci_stack->decline_addr, addr);
3718                 break;
3719             }
3720 
3721             if (hci_stack->gap_classic_accept_callback != NULL){
3722                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3723                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
3724                     bd_addr_copy(hci_stack->decline_addr, addr);
3725                     break;
3726                 }
3727             }
3728 
3729             // TODO: eval COD 8-10
3730             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
3731             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
3732             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3733             if (!conn) {
3734                 conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_SLAVE);
3735             }
3736             if (!conn) {
3737                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
3738                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3739                 bd_addr_copy(hci_stack->decline_addr, addr);
3740                 hci_run();
3741                 // avoid event to higher layer
3742                 return;
3743             }
3744             conn->state = RECEIVED_CONNECTION_REQUEST;
3745             // store info about eSCO
3746             if (link_type == HCI_LINK_TYPE_ESCO){
3747                 conn->remote_supported_features[0] |= 1;
3748             }
3749             // propagate remote supported sco packet packets from existing ACL to new SCO connection
3750             if (addr_type == BD_ADDR_TYPE_SCO){
3751                 const hci_connection_t * acl_conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3752                 // ACL exists unless fuzzing
3753                 if (acl_conn != NULL) {
3754                     conn->remote_supported_sco_packets = acl_conn->remote_supported_sco_packets;
3755                 }
3756             }
3757             hci_run();
3758             break;
3759 
3760         case HCI_EVENT_CONNECTION_COMPLETE:
3761             // Connection management
3762             reverse_bd_addr(&packet[5], addr);
3763             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3764             addr_type = BD_ADDR_TYPE_ACL;
3765             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3766             if (conn) {
3767                 switch (conn->state){
3768                     // expected states
3769                     case ACCEPTED_CONNECTION_REQUEST:
3770                     case SENT_CREATE_CONNECTION:
3771                         break;
3772                     // unexpected state -> ignore
3773                     default:
3774                         // don't forward event to app
3775                         return;
3776                 }
3777                 if (!packet[2]){
3778                     conn->state = OPEN;
3779                     conn->con_handle = little_endian_read_16(packet, 3);
3780 
3781                     // trigger write supervision timeout if we're master
3782                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
3783                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
3784                     }
3785 
3786                     // trigger write automatic flush timeout
3787                     if (hci_stack->automatic_flush_timeout != 0){
3788                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
3789                     }
3790 
3791                     // restart timer
3792                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3793                     btstack_run_loop_add_timer(&conn->timeout);
3794 
3795                     // trigger remote features for dedicated bonding
3796                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3797                         hci_trigger_remote_features_for_connection(conn);
3798                     }
3799 
3800                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3801 
3802                     hci_emit_nr_connections_changed();
3803                 } else {
3804                     // connection failed
3805                     hci_handle_connection_failed(conn, packet[2]);
3806                 }
3807             }
3808             break;
3809 
3810         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3811             reverse_bd_addr(&packet[5], addr);
3812             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3813             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3814 
3815             // SCO exists unless fuzzer
3816             if (conn == NULL) break;
3817 
3818             if (packet[2] != ERROR_CODE_SUCCESS){
3819                 // connection failed, remove entry
3820                 hci_handle_connection_failed(conn, packet[2]);
3821                 break;
3822             }
3823 
3824             conn->state = OPEN;
3825             conn->con_handle = little_endian_read_16(packet, 3);
3826 
3827             // update sco payload length for eSCO connections
3828             if (hci_event_synchronous_connection_complete_get_tx_packet_length(packet) > 0){
3829                 conn->sco_payload_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet);
3830                 log_info("eSCO Complete, set payload len %u", conn->sco_payload_length);
3831             }
3832 
3833 #ifdef ENABLE_SCO_OVER_HCI
3834             // update SCO
3835             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3836                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3837             }
3838             // trigger can send now
3839             if (hci_have_usb_transport()){
3840                 hci_stack->sco_can_send_now = true;
3841             }
3842 
3843             // setup implict sco flow control
3844             conn->sco_tx_ready = 0;
3845             conn->sco_tx_active  = 0;
3846             conn->sco_established_ms = btstack_run_loop_get_time_ms();
3847 
3848 #endif
3849 #ifdef HAVE_SCO_TRANSPORT
3850             // configure sco transport
3851             if (hci_stack->sco_transport != NULL){
3852                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3853                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3854             }
3855 #endif
3856             break;
3857 
3858         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3859             handle = little_endian_read_16(packet, 3);
3860             conn = hci_connection_for_handle(handle);
3861             if (!conn) break;
3862             if (!packet[2]){
3863                 const uint8_t * features = &packet[5];
3864                 hci_handle_remote_features_page_0(conn, features);
3865 
3866                 // read extended features if possible
3867                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
3868                 && ((conn->remote_supported_features[0] & 2) != 0)) {
3869                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
3870                     break;
3871                 }
3872             }
3873             hci_handle_remote_features_received(conn);
3874             break;
3875 
3876         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3877             handle = little_endian_read_16(packet, 3);
3878             conn = hci_connection_for_handle(handle);
3879             if (!conn) break;
3880             // status = ok, page = 1
3881             if (!packet[2]) {
3882                 uint8_t page_number = packet[5];
3883                 uint8_t maximum_page_number = packet[6];
3884                 const uint8_t * features = &packet[7];
3885                 bool done = false;
3886                 switch (page_number){
3887                     case 1:
3888                         hci_handle_remote_features_page_1(conn, features);
3889                         if (maximum_page_number >= 2){
3890                             // get Secure Connections (Controller) from Page 2 if available
3891                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
3892                         } else {
3893                             // otherwise, assume SC (Controller) == SC (Host)
3894                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
3895                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
3896                             }
3897                             done = true;
3898                         }
3899                         break;
3900                     case 2:
3901                         hci_handle_remote_features_page_2(conn, features);
3902                         done = true;
3903                         break;
3904                     default:
3905                         break;
3906                 }
3907                 if (!done) break;
3908             }
3909             hci_handle_remote_features_received(conn);
3910             break;
3911 
3912         case HCI_EVENT_LINK_KEY_REQUEST:
3913 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
3914             hci_event_link_key_request_get_bd_addr(packet, addr);
3915             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3916             if (!conn) break;
3917 
3918             // lookup link key in db if not cached
3919             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
3920                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
3921             }
3922 
3923             // response sent by hci_run()
3924             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
3925 #endif
3926             break;
3927 
3928         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
3929             hci_event_link_key_request_get_bd_addr(packet, addr);
3930             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3931             if (!conn) break;
3932 
3933             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
3934 
3935             // CVE-2020-26555: ignore NULL link key
3936             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
3937             if (btstack_is_null(&packet[8], 16)) break;
3938 
3939             link_key_type_t link_key_type = (link_key_type_t)packet[24];
3940             // Change Connection Encryption keeps link key type
3941             if (link_key_type != CHANGED_COMBINATION_KEY){
3942                 conn->link_key_type = link_key_type;
3943             }
3944 
3945             // cache link key. link keys stored in little-endian format for legacy reasons
3946             memcpy(&conn->link_key, &packet[8], 16);
3947 
3948             // only store link key:
3949             // - if bondable enabled
3950             if (hci_stack->bondable == false) break;
3951             // - if security level sufficient
3952             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
3953             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
3954             break;
3955         }
3956 
3957         case HCI_EVENT_PIN_CODE_REQUEST:
3958             hci_event_pin_code_request_get_bd_addr(packet, addr);
3959             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3960             if (!conn) break;
3961 
3962             hci_pairing_started(conn, false);
3963             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
3964             if (!hci_stack->bondable ){
3965                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3966                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3967                 hci_run();
3968                 return;
3969             }
3970             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3971             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3972                 log_info("Level 4 required, but SC not supported -> abort");
3973                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3974                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3975                 hci_run();
3976                 return;
3977             }
3978             break;
3979 
3980         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
3981             hci_event_io_capability_response_get_bd_addr(packet, addr);
3982             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3983             if (!conn) break;
3984 
3985             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
3986             hci_pairing_started(conn, true);
3987             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3988             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3989 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3990             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3991 #endif
3992             break;
3993 
3994         case HCI_EVENT_IO_CAPABILITY_REQUEST:
3995             hci_event_io_capability_response_get_bd_addr(packet, addr);
3996             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3997             if (!conn) break;
3998 
3999             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
4000             hci_connection_timestamp(conn);
4001             hci_pairing_started(conn, true);
4002             break;
4003 
4004 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4005         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
4006             hci_event_remote_oob_data_request_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_connection_timestamp(conn);
4011 
4012             hci_pairing_started(conn, true);
4013 
4014             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
4015             break;
4016 #endif
4017 
4018         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
4019             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
4020             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4021             if (!conn) break;
4022             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
4023                 if (hci_stack->ssp_auto_accept){
4024                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4025                 };
4026             } else {
4027                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
4028                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4029                 // don't forward event to app
4030                 hci_run();
4031                 return;
4032             }
4033             break;
4034 
4035         case HCI_EVENT_USER_PASSKEY_REQUEST:
4036             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
4037             if (hci_stack->ssp_auto_accept){
4038                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4039             };
4040             break;
4041 
4042         case HCI_EVENT_MODE_CHANGE:
4043             handle = hci_event_mode_change_get_handle(packet);
4044             conn = hci_connection_for_handle(handle);
4045             if (!conn) break;
4046             conn->connection_mode = hci_event_mode_change_get_mode(packet);
4047             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
4048             break;
4049 #endif
4050 
4051         case HCI_EVENT_ENCRYPTION_CHANGE:
4052         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
4053             handle = hci_event_encryption_change_get_connection_handle(packet);
4054             conn = hci_connection_for_handle(handle);
4055             if (!conn) break;
4056             if (hci_event_encryption_change_get_status(packet) == ERROR_CODE_SUCCESS) {
4057                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
4058                 if (encryption_enabled){
4059                     if (hci_is_le_connection(conn)){
4060                         // For LE, we accept connection as encrypted
4061                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
4062                     }
4063 #ifdef ENABLE_CLASSIC
4064                     else {
4065 
4066                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
4067                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
4068                         bool connected_uses_aes_ccm = encryption_enabled == 2;
4069                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
4070 #ifdef ENABLE_TESTING_SUPPORT
4071                             // The following tests require to reject L2CAP connection as SC has been disabled on the remote
4072                             // - GAP/SEC/SEM/BI-31-C
4073                             // - GAP/SEC/SEM/BI-32-C
4074                             // - GAP/SEC/SEM/BI-33-C
4075 
4076                             // Our release code (aggressively) disconnects the HCI connection, without a chance to respond to PTS
4077                             // To pass the tests, we only downgrade the link key type instead of the more secure disconnect
4078                             link_key_type_t new_link_key_type = UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
4079                             if (conn->link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256){
4080                                 new_link_key_type = AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
4081                             }
4082                             log_info("SC during pairing, but only E0 now -> downgrade link key type from %u to %u",
4083                                      conn->link_key_type, new_link_key_type);
4084                             conn->link_key_type = new_link_key_type;
4085 #else
4086                             log_info("SC during pairing, but only E0 now -> abort");
4087                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
4088                             break;
4089 #endif
4090                         }
4091 
4092 #ifdef ENABLE_MUTUAL_AUTHENTICATION_FOR_LEGACY_SECURE_CONNECTIONS
4093                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
4094                         if (connected_uses_aes_ccm){
4095                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4096                         }
4097 #else
4098                         // We consider even Legacy Secure Connections as authenticated as BTstack mandates encryption
4099                         // with encryption key size > hci_stack->gap_required_encyrption_key_size
4100                         // for all operations that require any security. See BIAS attacks.
4101                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4102 #endif
4103                         // validate encryption key size
4104                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
4105                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
4106                             // already got encryption key size
4107                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
4108                         } else {
4109                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
4110                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
4111                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4112                             } else {
4113                                 // if not, pretend everything is perfect
4114                                 hci_handle_read_encryption_key_size_complete(conn, 16);
4115                             }
4116                         }
4117                     }
4118 #endif
4119                 } else {
4120                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
4121                 }
4122             } else {
4123 #ifdef ENABLE_CLASSIC
4124                 if (!hci_is_le_connection(conn)){
4125                     uint8_t status = hci_event_encryption_change_get_status(packet);
4126                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
4127                         conn->bonding_flags &= ~BONDING_DEDICATED;
4128                         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
4129                         conn->bonding_status = status;
4130                     }
4131                     // trigger security update -> level 0
4132                     hci_handle_mutual_authentication_completed(conn);
4133                 }
4134 #endif
4135             }
4136 
4137             break;
4138 
4139 #ifdef ENABLE_CLASSIC
4140         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
4141             handle = hci_event_authentication_complete_get_connection_handle(packet);
4142             conn = hci_connection_for_handle(handle);
4143             if (!conn) break;
4144 
4145             // clear authentication active flag
4146             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
4147             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
4148 
4149             // authenticated only if auth status == 0
4150             if (hci_event_authentication_complete_get_status(packet) == 0){
4151                 // authenticated
4152                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4153 
4154                 // If not already encrypted, start encryption
4155                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
4156                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4157                     break;
4158                 }
4159             }
4160 
4161             // emit updated security level (will be 0 if not authenticated)
4162             hci_handle_mutual_authentication_completed(conn);
4163             break;
4164 
4165         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
4166             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
4167             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4168             if (!conn) break;
4169 
4170             // treat successfully paired connection as authenticated
4171             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
4172                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4173             }
4174 
4175             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
4176             break;
4177 #endif
4178 
4179         // HCI_EVENT_DISCONNECTION_COMPLETE
4180         // has been split, to first notify stack before shutting connection down
4181         // see end of function, too.
4182         case HCI_EVENT_DISCONNECTION_COMPLETE:
4183             if (packet[2]) break;   // status != 0
4184             handle = little_endian_read_16(packet, 3);
4185             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
4186             if (hci_stack->acl_fragmentation_total_size > 0u) {
4187                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4188                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
4189                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
4190                     hci_stack->acl_fragmentation_total_size = 0;
4191                     hci_stack->acl_fragmentation_pos = 0;
4192                     if (release_buffer){
4193                         hci_release_packet_buffer();
4194                     }
4195                 }
4196             }
4197 
4198 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4199             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
4200             if (hci_stack->iso_fragmentation_total_size > 0u) {
4201                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4202                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
4203                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
4204                     hci_stack->iso_fragmentation_total_size = 0;
4205                     hci_stack->iso_fragmentation_pos = 0;
4206                     if (release_buffer){
4207                         hci_release_packet_buffer();
4208                     }
4209                 }
4210             }
4211 
4212             // finalize iso stream for CIS handle
4213             iso_stream = hci_iso_stream_for_con_handle(handle);
4214             if (iso_stream != NULL){
4215                 hci_iso_stream_finalize(iso_stream);
4216                 break;
4217             }
4218 
4219             // finalize iso stream(s) for ACL handle
4220             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4221             while (btstack_linked_list_iterator_has_next(&it)){
4222                 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4223                 if (iso_stream->acl_handle == handle ) {
4224                     hci_iso_stream_finalize(iso_stream);
4225                 }
4226             }
4227 #endif
4228 
4229 #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
4230             if ((handle != HCI_CON_HANDLE_INVALID) && (handle == hci_stack->hci_command_con_handle)){
4231                 // we did not receive a HCI Command Complete or HCI Command Status event for the disconnected connection
4232                 // if needed, we could also track the hci command opcode and simulate a hci command complete with status
4233                 // but the connection has failed anyway, so for now, we only set the num hci commands back to 1
4234                 log_info("Disconnect for conn handle 0x%04x in pending HCI command, assume command failed", handle);
4235                 hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4236                 hci_stack->num_cmd_packets = 1;
4237             }
4238 #endif
4239 
4240             conn = hci_connection_for_handle(handle);
4241             if (!conn) break;
4242 #ifdef ENABLE_CLASSIC
4243             // pairing failed if it was ongoing
4244             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4245 #endif
4246 
4247             // emit dedicatd bonding event
4248             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
4249                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
4250             }
4251 
4252             // mark connection for shutdown, stop timers, reset state
4253             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
4254             hci_connection_stop_timer(conn);
4255             hci_connection_init(conn);
4256 
4257 #ifdef ENABLE_BLE
4258 #ifdef ENABLE_LE_PERIPHERAL
4259             // re-enable advertisements for le connections if active
4260             if (hci_is_le_connection(conn)){
4261                 hci_update_advertisements_enabled_for_current_roles();
4262             }
4263 #endif
4264 #endif
4265             break;
4266 
4267         case HCI_EVENT_HARDWARE_ERROR:
4268             log_error("Hardware Error: 0x%02x", packet[2]);
4269             if (hci_stack->hardware_error_callback){
4270                 (*hci_stack->hardware_error_callback)(packet[2]);
4271             } else {
4272                 // if no special requests, just reboot stack
4273                 hci_power_control_off();
4274                 hci_power_control_on();
4275             }
4276             break;
4277 
4278 #ifdef ENABLE_CLASSIC
4279         case HCI_EVENT_ROLE_CHANGE:
4280             if (packet[2]) break;   // status != 0
4281             reverse_bd_addr(&packet[3], addr);
4282             addr_type = BD_ADDR_TYPE_ACL;
4283             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4284             if (!conn) break;
4285             conn->role = (hci_role_t) packet[9];
4286             break;
4287 #endif
4288 
4289         case HCI_EVENT_TRANSPORT_PACKET_SENT:
4290             // release packet buffer only for asynchronous transport and if there are not further fragments
4291             if (hci_transport_synchronous()) {
4292                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
4293                 return; // instead of break: to avoid re-entering hci_run()
4294             }
4295             hci_stack->acl_fragmentation_tx_active = 0;
4296 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4297             hci_stack->iso_fragmentation_tx_active = 0;
4298             if (hci_stack->iso_fragmentation_total_size) break;
4299 #endif
4300             if (hci_stack->acl_fragmentation_total_size) break;
4301 
4302             // release packet buffer without HCI_EVENT_TRANSPORT_PACKET_SENT (as it will be later)
4303             btstack_assert(hci_stack->hci_packet_buffer_reserved);
4304             hci_stack->hci_packet_buffer_reserved = false;
4305 
4306 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4307             hci_iso_notify_can_send_now();
4308 #endif
4309             // L2CAP receives this event via the hci_emit_event below
4310 
4311 #ifdef ENABLE_CLASSIC
4312             // For SCO, we do the can_send_now_check here
4313             hci_notify_if_sco_can_send_now();
4314 #endif
4315             break;
4316 
4317 #ifdef ENABLE_CLASSIC
4318         case HCI_EVENT_SCO_CAN_SEND_NOW:
4319             // For SCO, we do the can_send_now_check here
4320             hci_stack->sco_can_send_now = true;
4321             hci_notify_if_sco_can_send_now();
4322             return;
4323 
4324         // explode inquriy results for easier consumption
4325         case HCI_EVENT_INQUIRY_RESULT:
4326         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4327         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4328             gap_inquiry_explode(packet, size);
4329             break;
4330 #endif
4331 
4332 #ifdef ENABLE_BLE
4333         case HCI_EVENT_LE_META:
4334             switch (packet[2]){
4335 #ifdef ENABLE_LE_CENTRAL
4336                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
4337                     if (!hci_stack->le_scanning_enabled) break;
4338                     le_handle_advertisement_report(packet, size);
4339                     break;
4340 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4341                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
4342                     if (!hci_stack->le_scanning_enabled) break;
4343                     le_handle_extended_advertisement_report(packet, size);
4344                     break;
4345                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
4346                     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
4347                     hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE;
4348                     break;
4349                 case HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED:
4350                     advertising_handle = hci_subevent_le_advertising_set_terminated_get_advertising_handle(packet);
4351                     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4352                     while (btstack_linked_list_iterator_has_next(&it)) {
4353                         le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
4354                         if (advertising_set->advertising_handle == advertising_handle){
4355                             advertising_set->state &= ~(LE_ADVERTISEMENT_STATE_ACTIVE | LE_ADVERTISEMENT_STATE_ENABLED);
4356                         }
4357                     }
4358                     break;
4359 #endif
4360 #endif
4361                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
4362                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
4363                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
4364                     hci_handle_le_connection_complete_event(packet);
4365                     break;
4366 
4367                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
4368                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
4369                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
4370                     conn = hci_connection_for_handle(handle);
4371                     if (!conn) break;
4372                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
4373                     break;
4374 
4375                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
4376                     // connection
4377                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
4378                     conn = hci_connection_for_handle(handle);
4379                     if (conn) {
4380                         // read arguments
4381                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
4382                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
4383                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
4384                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
4385 
4386                         // validate against current connection parameter range
4387                         le_connection_parameter_range_t existing_range;
4388                         gap_get_connection_parameter_range(&existing_range);
4389                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4390                         if (update_parameter){
4391                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
4392                             conn->le_conn_interval_min = le_conn_interval_min;
4393                             conn->le_conn_interval_max = le_conn_interval_max;
4394                             conn->le_conn_latency = le_conn_latency;
4395                             conn->le_supervision_timeout = le_supervision_timeout;
4396                         } else {
4397                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
4398                         }
4399                     }
4400                     break;
4401 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
4402                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
4403                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
4404                     conn = hci_connection_for_handle(handle);
4405                     if (conn) {
4406                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
4407                     }
4408                     break;
4409 #endif
4410 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4411                 case HCI_SUBEVENT_LE_CIS_REQUEST:
4412                     // incoming CIS request, allocate iso stream object and cache metadata
4413                     iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_ISO_STREAM_W4_USER,
4414                                                        hci_subevent_le_cis_request_get_cig_id(packet),
4415                                                        hci_subevent_le_cis_request_get_cis_id(packet));
4416                     // if there's no memory, gap_cis_accept/gap_cis_reject will fail
4417                     if (iso_stream != NULL){
4418                         iso_stream->cis_handle = hci_subevent_le_cis_request_get_cis_connection_handle(packet);
4419                         iso_stream->acl_handle = hci_subevent_le_cis_request_get_acl_connection_handle(packet);
4420                     }
4421                     break;
4422                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
4423                     if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
4424                         handle = hci_subevent_le_cis_established_get_connection_handle(packet);
4425                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
4426                         iso_stream = hci_iso_stream_for_con_handle(handle);
4427                         btstack_assert(iso_stream != NULL);
4428                         // track connection info
4429                         iso_stream->number_of_subevents  = hci_subevent_le_cis_established_get_nse(packet);
4430                         iso_stream->burst_number_c_to_p  = hci_subevent_le_cis_established_get_bn_c_to_p(packet);
4431                         iso_stream->burst_number_p_to_c  = hci_subevent_le_cis_established_get_bn_p_to_c(packet);
4432                         iso_stream->flush_timeout_c_to_p = hci_subevent_le_cis_established_get_ft_c_to_p(packet);
4433                         iso_stream->flush_timeout_p_to_c = hci_subevent_le_cis_established_get_ft_p_to_c(packet);
4434                         iso_stream->max_sdu_c_to_p       = hci_subevent_le_cis_established_get_max_pdu_c_to_p(packet);
4435                         iso_stream->max_sdu_p_to_c       = hci_subevent_le_cis_established_get_max_pdu_p_to_c(packet);
4436                         iso_stream->iso_interval_1250us  = hci_subevent_le_cis_established_get_iso_interval(packet);
4437                         if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
4438                             // CIS Accept by Peripheral
4439                             if (status == ERROR_CODE_SUCCESS){
4440                                 if (iso_stream->max_sdu_p_to_c > 0){
4441                                     // we're peripheral and we will send data
4442                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT;
4443                                 } else {
4444                                     // we're peripheral and we will only receive data
4445                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
4446                                 }
4447                             } else {
4448                                 hci_cis_handle_created(iso_stream, status);
4449                             }
4450                             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4451                         } else {
4452                             // CIG Setup by Central
4453                             le_audio_cig_t * cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
4454                             btstack_assert(cig != NULL);
4455                             // update iso stream state
4456                             if (status == ERROR_CODE_SUCCESS){
4457                                 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4458                             } else {
4459                                 iso_stream->state = HCI_ISO_STREAM_STATE_IDLE;
4460                             }
4461                             // update cig state
4462                             uint8_t i;
4463                             for (i=0;i<cig->num_cis;i++){
4464                                 if (cig->cis_con_handles[i] == handle){
4465                                     cig->cis_setup_active[i] = false;
4466                                     if (status == ERROR_CODE_SUCCESS){
4467                                         cig->cis_established[i] = true;
4468                                     } else {
4469                                         hci_cis_handle_created(iso_stream, status);
4470                                     }
4471                                 }
4472                             }
4473 
4474                             // trigger iso path setup if complete
4475                             bool cis_setup_active = false;
4476                             for (i=0;i<cig->num_cis;i++){
4477                                 cis_setup_active |= cig->cis_setup_active[i];
4478                             }
4479                             if (cis_setup_active == false){
4480                                 cig->state_vars.next_cis = 0;
4481                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
4482                                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4483                             }
4484                         }
4485                     }
4486                     break;
4487                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
4488                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4489                     big = hci_big_for_handle(packet[4]);
4490                     if (big != NULL){
4491                         uint8_t status = packet[3];
4492                         if (status == ERROR_CODE_SUCCESS){
4493                             // store bis_con_handles and trigger iso path setup
4494                             uint8_t num_bis = btstack_min(big->num_bis, packet[20]);
4495                             uint8_t i;
4496                             for (i=0;i<num_bis;i++){
4497                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4498                                 big->bis_con_handles[i] = bis_handle;
4499                                 // assign bis handle
4500                                 btstack_linked_list_iterator_t it;
4501                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4502                                 while (btstack_linked_list_iterator_has_next(&it)){
4503                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4504                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4505                                         (iso_stream->group_id == big->big_handle)){
4506                                         iso_stream->cis_handle = bis_handle;
4507                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4508                                         break;
4509                                     }
4510                                 }
4511                             }
4512                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4513                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4514                                 big->state_vars.next_bis = 0;
4515                             }
4516                         } else {
4517                             // create BIG failed or has been stopped by us
4518                             hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
4519                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4520                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
4521                                 hci_emit_big_created(big, status);
4522                             } else {
4523                                 hci_emit_big_terminated(big);
4524                             }
4525                         }
4526                     }
4527                     break;
4528                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4529                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4530                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
4531                     if (big != NULL){
4532                         // finalize associated ISO streams
4533                         btstack_linked_list_iterator_t it;
4534                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4535                         while (btstack_linked_list_iterator_has_next(&it)){
4536                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4537                             if (iso_stream->group_id == big->big_handle){
4538                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->cis_handle);
4539                                 btstack_linked_list_iterator_remove(&it);
4540                                 btstack_memory_hci_iso_stream_free(iso_stream);
4541                             }
4542                         }
4543                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4544                         switch (big->state){
4545                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
4546                                 hci_emit_big_created(big, big->state_vars.status);
4547                                 break;
4548                             default:
4549                                 hci_emit_big_terminated(big);
4550                                 break;
4551                         }
4552                     }
4553                     break;
4554                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4555                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4556                     big_sync = hci_big_sync_for_handle(packet[4]);
4557                     if (big_sync != NULL){
4558                         uint8_t status = packet[3];
4559                         if (status == ERROR_CODE_SUCCESS){
4560                             // store bis_con_handles and trigger iso path setup
4561                             uint8_t num_bis = btstack_min(big_sync->num_bis, packet[16]);
4562                             for (i=0;i<num_bis;i++){
4563                                 hci_con_handle_t bis_handle = little_endian_read_16(packet, 17 + (2 * i));
4564                                 big_sync->bis_con_handles[i] = bis_handle;
4565                                 // setup iso_stream_t
4566                                 btstack_linked_list_iterator_t it;
4567                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4568                                 while (btstack_linked_list_iterator_has_next(&it)){
4569                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4570                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4571                                         (iso_stream->group_id == big_sync->big_handle)){
4572                                         iso_stream->cis_handle = bis_handle;
4573                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4574                                         break;
4575                                     }
4576                                 }
4577                             }
4578                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4579                                 // trigger iso path setup
4580                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4581                                 big_sync->state_vars.next_bis = 0;
4582                             }
4583                         } else {
4584                             // create BIG Sync failed or has been stopped by us
4585                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4586                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4587                                 hci_emit_big_sync_created(big_sync, status);
4588                             } else {
4589                                 hci_emit_big_sync_stopped(big_handle);
4590                             }
4591                         }
4592                     }
4593                     break;
4594                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4595                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4596                     big_sync = hci_big_sync_for_handle(packet[4]);
4597                     if (big_sync != NULL){
4598                         uint8_t big_handle = packet[4];
4599                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4600                         hci_emit_big_sync_stopped(big_handle);
4601                     }
4602                     break;
4603 #endif
4604                 default:
4605                     break;
4606             }
4607             break;
4608 #endif
4609         case HCI_EVENT_VENDOR_SPECIFIC:
4610             // Vendor specific commands often create vendor specific event instead of num completed packets
4611             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
4612             switch (hci_stack->manufacturer){
4613                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
4614                     hci_stack->num_cmd_packets = 1;
4615                     break;
4616                 default:
4617                     break;
4618             }
4619             break;
4620         default:
4621             break;
4622     }
4623 
4624     handle_event_for_current_stack_state(packet, size);
4625 
4626     // notify upper stack
4627 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
4628 
4629     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4630     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4631 		handle = little_endian_read_16(packet, 3);
4632 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4633 		// discard connection if app did not trigger a reconnect in the event handler
4634 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
4635 			hci_shutdown_connection(aConn);
4636 		}
4637 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
4638         hci_controller_dump_packets();
4639 #endif
4640     }
4641 
4642 	// execute main loop
4643 	hci_run();
4644 }
4645 
4646 #ifdef ENABLE_CLASSIC
4647 
4648 static void sco_handler(uint8_t * packet, uint16_t size){
4649     // lookup connection struct
4650     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
4651     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
4652     if (!conn) return;
4653 
4654 #ifdef ENABLE_SCO_OVER_HCI
4655     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4656     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4657         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4658             packet[2] = 0x3c;
4659             memmove(&packet[3], &packet[23], 63);
4660             size = 63;
4661         }
4662     }
4663 
4664     if (hci_have_usb_transport()){
4665         // Nothing to do
4666     } else {
4667         // log_debug("sco flow %u, handle 0x%04x, packets sent %u, bytes send %u", hci_stack->synchronous_flow_control_enabled, (int) con_handle, conn->num_packets_sent, conn->num_sco_bytes_sent);
4668         if (hci_stack->synchronous_flow_control_enabled == 0){
4669             // ignore received SCO packets for the first 10 ms, then allow for max two HCI_SCO_2EV3_SIZE packets
4670             uint16_t max_sco_packets = btstack_min(2 * HCI_SCO_2EV3_SIZE / conn->sco_payload_length, hci_stack->sco_packets_total_num);
4671             if (conn->sco_tx_active == 0){
4672                 if (btstack_time_delta(btstack_run_loop_get_time_ms(), conn->sco_established_ms) > 10){
4673                     conn->sco_tx_active = 1;
4674                     conn->sco_tx_ready = max_sco_packets;
4675                     log_info("Start SCO sending, %u packets", conn->sco_tx_ready);
4676                     hci_notify_if_sco_can_send_now();
4677                 }
4678             } else {
4679                 if (conn->sco_tx_ready < max_sco_packets){
4680                     conn->sco_tx_ready++;
4681                 }
4682                 hci_notify_if_sco_can_send_now();
4683             }
4684         }
4685     }
4686 #endif
4687 
4688     // deliver to app
4689     if (hci_stack->sco_packet_handler) {
4690         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
4691     }
4692 
4693 #ifdef HAVE_SCO_TRANSPORT
4694     // We can send one packet for each received packet
4695     conn->sco_tx_ready++;
4696     hci_notify_if_sco_can_send_now();
4697 #endif
4698 
4699 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4700     conn->num_packets_completed++;
4701     hci_stack->host_completed_packets = 1;
4702     hci_run();
4703 #endif
4704 }
4705 #endif
4706 
4707 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
4708 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4709     // propagate ISO packets received as ACL
4710     hci_iso_stream_t * iso_stream = NULL;
4711     if ((packet_type == HCI_ACL_DATA_PACKET) && (size >= HCI_ACL_HEADER_SIZE)){
4712         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
4713         iso_stream = hci_iso_stream_for_con_handle(con_handle);
4714         if (iso_stream != NULL){
4715             packet_type = HCI_ISO_DATA_PACKET;
4716         }
4717     }
4718 #endif
4719 
4720     hci_dump_packet(packet_type, 1, packet, size);
4721     switch (packet_type) {
4722         case HCI_EVENT_PACKET:
4723             event_handler(packet, size);
4724             break;
4725         case HCI_ACL_DATA_PACKET:
4726             acl_handler(packet, size);
4727             break;
4728 #ifdef ENABLE_CLASSIC
4729         case HCI_SCO_DATA_PACKET:
4730             sco_handler(packet, size);
4731             break;
4732 #endif
4733 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4734         case HCI_ISO_DATA_PACKET:
4735             if ((iso_stream == NULL) && (size >= HCI_ISO_HEADER_SIZE)){
4736                 hci_con_handle_t con_handle = READ_ISO_CONNECTION_HANDLE(packet);
4737                 iso_stream = hci_iso_stream_for_con_handle(con_handle);
4738             }
4739             hci_iso_packet_handler(iso_stream, packet, size);
4740             break;
4741 #endif
4742         default:
4743             break;
4744     }
4745 }
4746 
4747 /**
4748  * @brief Add event packet handler.
4749  */
4750 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4751     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4752 }
4753 
4754 /**
4755  * @brief Remove event packet handler.
4756  */
4757 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
4758     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4759 }
4760 
4761 /** Register HCI packet handlers */
4762 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4763     hci_stack->acl_packet_handler = handler;
4764 }
4765 
4766 #ifdef ENABLE_CLASSIC
4767 /**
4768  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
4769  */
4770 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
4771     hci_stack->sco_packet_handler = handler;
4772 }
4773 #endif
4774 
4775 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4776 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
4777     hci_stack->iso_packet_handler = handler;
4778 }
4779 #endif
4780 
4781 static void hci_state_reset(void){
4782     // no connections yet
4783     hci_stack->connections = NULL;
4784 
4785     // keep discoverable/connectable as this has been requested by the client(s)
4786     // hci_stack->discoverable = 0;
4787     // hci_stack->connectable = 0;
4788     // hci_stack->bondable = 1;
4789     // hci_stack->own_addr_type = 0;
4790 
4791     // buffer is free
4792     hci_stack->hci_packet_buffer_reserved = false;
4793 
4794     // no pending cmds
4795     hci_stack->decline_reason = 0;
4796 
4797     hci_stack->secure_connections_active = false;
4798 
4799 #ifdef ENABLE_CLASSIC
4800     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
4801     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
4802 
4803     hci_stack->gap_tasks_classic =
4804             GAP_TASK_SET_DEFAULT_LINK_POLICY |
4805             GAP_TASK_SET_CLASS_OF_DEVICE |
4806             GAP_TASK_SET_LOCAL_NAME |
4807             GAP_TASK_SET_EIR_DATA |
4808             GAP_TASK_WRITE_SCAN_ENABLE |
4809             GAP_TASK_WRITE_PAGE_TIMEOUT;
4810 #endif
4811 
4812 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4813     hci_stack->classic_read_local_oob_data = false;
4814     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4815 #endif
4816 
4817     // LE
4818 #ifdef ENABLE_BLE
4819     memset(hci_stack->le_random_address, 0, 6);
4820     hci_stack->le_random_address_set = 0;
4821 #endif
4822 #ifdef ENABLE_LE_CENTRAL
4823     hci_stack->le_scanning_active  = false;
4824     hci_stack->le_scanning_param_update = true;
4825     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4826     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4827     hci_stack->le_whitelist_capacity = 0;
4828 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4829     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
4830 #endif
4831 #endif
4832 #ifdef ENABLE_LE_PERIPHERAL
4833     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4834     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4835         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4836     }
4837     if (hci_stack->le_advertisements_data != NULL){
4838         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4839     }
4840 #endif
4841 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4842     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION;
4843 #endif
4844 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4845     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4846     hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID;
4847 #endif
4848 #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
4849     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4850 #endif
4851 }
4852 
4853 #ifdef ENABLE_CLASSIC
4854 /**
4855  * @brief Configure Bluetooth hardware control. Has to be called before power on.
4856  */
4857 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
4858     // store and open remote device db
4859     hci_stack->link_key_db = link_key_db;
4860     if (hci_stack->link_key_db) {
4861         hci_stack->link_key_db->open();
4862     }
4863 }
4864 #endif
4865 
4866 void hci_init(const hci_transport_t *transport, const void *config){
4867 
4868 #ifdef HAVE_MALLOC
4869     if (!hci_stack) {
4870         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
4871     }
4872 #else
4873     hci_stack = &hci_stack_static;
4874 #endif
4875     memset(hci_stack, 0, sizeof(hci_stack_t));
4876 
4877     // reference to use transport layer implementation
4878     hci_stack->hci_transport = transport;
4879 
4880     // reference to used config
4881     hci_stack->config = config;
4882 
4883     // setup pointer for outgoing packet buffer
4884     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
4885 
4886     // max acl payload size defined in config.h
4887     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4888 
4889     // register packet handlers with transport
4890     transport->register_packet_handler(&packet_handler);
4891 
4892     hci_stack->state = HCI_STATE_OFF;
4893 
4894     // class of device
4895     hci_stack->class_of_device = 0x007a020c; // Smartphone
4896 
4897     // bondable by default
4898     hci_stack->bondable = 1;
4899 
4900 #ifdef ENABLE_CLASSIC
4901     // classic name
4902     hci_stack->local_name = default_classic_name;
4903 
4904     // Master slave policy
4905     hci_stack->master_slave_policy = 1;
4906 
4907     // Allow Role Switch
4908     hci_stack->allow_role_switch = 1;
4909 
4910     // Default / minimum security level = 2
4911     hci_stack->gap_security_level = LEVEL_2;
4912 
4913     // Default Security Mode 4
4914     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
4915 
4916     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4917     hci_stack->gap_required_encyrption_key_size = 7;
4918 
4919     // Link Supervision Timeout
4920     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4921 
4922     // All ACL packet types are enabledh
4923     hci_stack->enabled_packet_types_acl = ACL_PACKET_TYPES_ALL;
4924 #endif
4925 
4926     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
4927     hci_stack->ssp_enable = 1;
4928     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
4929     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4930     hci_stack->ssp_auto_accept = 1;
4931 
4932     // Secure Connections: enable (requires support from Controller)
4933     hci_stack->secure_connections_enable = true;
4934 
4935     // voice setting - signed 16 bit pcm data with CVSD over the air
4936     hci_stack->sco_voice_setting = 0x60;
4937 
4938 #ifdef ENABLE_BLE
4939     hci_stack->le_connection_scan_interval = 0x0060;   //    60 ms
4940     hci_stack->le_connection_scan_window   = 0x0030;    //   30 ms
4941     hci_stack->le_connection_interval_min  = 0x0008;    //   10 ms
4942     hci_stack->le_connection_interval_max  = 0x0018;    //   30 ms
4943     hci_stack->le_connection_latency       =      4;    //    4
4944     hci_stack->le_supervision_timeout      = 0x0048;    //  720 ms
4945     hci_stack->le_minimum_ce_length        =      0;    //    0 ms
4946     hci_stack->le_maximum_ce_length        =      0;    //    0 ms
4947 #endif
4948 
4949 #ifdef ENABLE_LE_CENTRAL
4950     hci_stack->le_connection_phys          =   0x01;    // LE 1M PHY
4951 
4952     // default LE Scanning
4953     hci_stack->le_scan_type     =  0x01; // active
4954     hci_stack->le_scan_interval = 0x1e0; // 300 ms
4955     hci_stack->le_scan_window   =  0x30; //  30 ms
4956     hci_stack->le_scan_phys     =  0x01; // LE 1M PHY
4957 #endif
4958 
4959 #ifdef ENABLE_LE_PERIPHERAL
4960     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4961 
4962     // default advertising parameters from Core v5.4 -- needed to use random address without prior adv setup
4963     hci_stack->le_advertisements_interval_min =                         0x0800;
4964     hci_stack->le_advertisements_interval_max =                         0x0800;
4965     hci_stack->le_advertisements_type =                                      0;
4966     hci_stack->le_own_addr_type =                       BD_ADDR_TYPE_LE_PUBLIC;
4967     hci_stack->le_advertisements_direct_address_type =  BD_ADDR_TYPE_LE_PUBLIC;
4968     hci_stack->le_advertisements_channel_map =                            0x07;
4969     hci_stack->le_advertisements_filter_policy =                             0;
4970 #endif
4971 
4972     // connection parameter range used to answer connection parameter update requests in l2cap
4973     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4974     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4975     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4976     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4977     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4978     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4979 
4980 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4981     hci_stack->iso_packets_to_queue = 1;
4982 #endif
4983 
4984 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4985     hci_stack->le_privacy_mode = LE_PRIVACY_MODE_DEVICE;
4986 #endif
4987 
4988     hci_state_reset();
4989 }
4990 
4991 void hci_deinit(void){
4992     btstack_run_loop_remove_timer(&hci_stack->timeout);
4993 #ifdef HAVE_MALLOC
4994     if (hci_stack) {
4995         free(hci_stack);
4996     }
4997 #endif
4998     hci_stack = NULL;
4999 
5000 #ifdef ENABLE_CLASSIC
5001     disable_l2cap_timeouts = 0;
5002 #endif
5003 }
5004 
5005 /**
5006  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
5007  */
5008 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
5009     hci_stack->chipset = chipset_driver;
5010 
5011     // reset chipset driver - init is also called on power_up
5012     if (hci_stack->chipset && hci_stack->chipset->init){
5013         hci_stack->chipset->init(hci_stack->config);
5014     }
5015 }
5016 
5017 void hci_enable_custom_pre_init(void){
5018     hci_stack->chipset_pre_init = true;
5019 }
5020 
5021 /**
5022  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
5023  */
5024 void hci_set_control(const btstack_control_t *hardware_control){
5025     // references to used control implementation
5026     hci_stack->control = hardware_control;
5027     // init with transport config
5028     hardware_control->init(hci_stack->config);
5029 }
5030 
5031 static void hci_discard_connections(void){
5032     btstack_linked_list_iterator_t it;
5033     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5034     while (btstack_linked_list_iterator_has_next(&it)){
5035         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
5036         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
5037         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
5038         hci_shutdown_connection(connection);
5039     }
5040 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5041     while (hci_stack->iso_streams != NULL){
5042         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
5043     }
5044 #endif
5045 }
5046 
5047 void hci_close(void){
5048 
5049 #ifdef ENABLE_CLASSIC
5050     // close remote device db
5051     if (hci_stack->link_key_db) {
5052         hci_stack->link_key_db->close();
5053     }
5054 #endif
5055 
5056     hci_discard_connections();
5057 
5058     hci_power_control(HCI_POWER_OFF);
5059 
5060 #ifdef HAVE_MALLOC
5061     free(hci_stack);
5062 #endif
5063     hci_stack = NULL;
5064 }
5065 
5066 #ifdef HAVE_SCO_TRANSPORT
5067 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
5068     hci_stack->sco_transport = sco_transport;
5069     sco_transport->register_packet_handler(&packet_handler);
5070 }
5071 #endif
5072 
5073 #ifdef ENABLE_CLASSIC
5074 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
5075     // validate ranage and set
5076     if (encryption_key_size < 7)  return;
5077     if (encryption_key_size > 16) return;
5078     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
5079 }
5080 
5081 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
5082     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
5083         hci_stack->gap_security_mode = security_mode;
5084         return ERROR_CODE_SUCCESS;
5085     } else {
5086         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
5087     }
5088 }
5089 
5090 gap_security_mode_t gap_get_security_mode(void){
5091     return hci_stack->gap_security_mode;
5092 }
5093 
5094 void gap_set_security_level(gap_security_level_t security_level){
5095     hci_stack->gap_security_level = security_level;
5096 }
5097 
5098 gap_security_level_t gap_get_security_level(void){
5099     if (hci_stack->gap_secure_connections_only_mode){
5100         return LEVEL_4;
5101     }
5102     return hci_stack->gap_security_level;
5103 }
5104 
5105 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
5106     hci_stack->gap_minimal_service_security_level = security_level;
5107 }
5108 
5109 void gap_set_secure_connections_only_mode(bool enable){
5110     hci_stack->gap_secure_connections_only_mode = enable;
5111 }
5112 
5113 bool gap_get_secure_connections_only_mode(void){
5114     return hci_stack->gap_secure_connections_only_mode;
5115 }
5116 #endif
5117 
5118 #ifdef ENABLE_CLASSIC
5119 void gap_set_class_of_device(uint32_t class_of_device){
5120     hci_stack->class_of_device = class_of_device;
5121     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
5122     hci_run();
5123 }
5124 
5125 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
5126     hci_stack->default_link_policy_settings = default_link_policy_settings;
5127     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
5128     hci_run();
5129 }
5130 
5131 void gap_set_allow_role_switch(bool allow_role_switch){
5132     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
5133 }
5134 
5135 uint8_t hci_get_allow_role_switch(void){
5136     return  hci_stack->allow_role_switch;
5137 }
5138 
5139 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
5140     hci_stack->link_supervision_timeout = link_supervision_timeout;
5141 }
5142 
5143 void gap_enable_link_watchdog(uint16_t timeout_ms){
5144     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
5145 }
5146 
5147 uint16_t hci_automatic_flush_timeout(void){
5148     return hci_stack->automatic_flush_timeout;
5149 }
5150 
5151 void hci_disable_l2cap_timeout_check(void){
5152     disable_l2cap_timeouts = 1;
5153 }
5154 #endif
5155 
5156 #ifndef HAVE_HOST_CONTROLLER_API
5157 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
5158 void hci_set_bd_addr(bd_addr_t addr){
5159     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
5160     hci_stack->custom_bd_addr_set = 1;
5161 }
5162 #endif
5163 
5164 // State-Module-Driver overview
5165 // state                    module  low-level
5166 // HCI_STATE_OFF             off      close
5167 // HCI_STATE_INITIALIZING,   on       open
5168 // HCI_STATE_WORKING,        on       open
5169 // HCI_STATE_HALTING,        on       open
5170 // HCI_STATE_SLEEPING,    off/sleep   close
5171 // HCI_STATE_FALLING_ASLEEP  on       open
5172 
5173 static int hci_power_control_on(void){
5174 
5175     // power on
5176     int err = 0;
5177     if (hci_stack->control && hci_stack->control->on){
5178         err = (*hci_stack->control->on)();
5179     }
5180     if (err){
5181         log_error( "POWER_ON failed");
5182         hci_emit_hci_open_failed();
5183         return err;
5184     }
5185 
5186     // int chipset driver
5187     if (hci_stack->chipset && hci_stack->chipset->init){
5188         hci_stack->chipset->init(hci_stack->config);
5189     }
5190 
5191     // init transport
5192     if (hci_stack->hci_transport->init){
5193         hci_stack->hci_transport->init(hci_stack->config);
5194     }
5195 
5196     // open transport
5197     err = hci_stack->hci_transport->open();
5198     if (err){
5199         log_error( "HCI_INIT failed, turning Bluetooth off again");
5200         if (hci_stack->control && hci_stack->control->off){
5201             (*hci_stack->control->off)();
5202         }
5203         hci_emit_hci_open_failed();
5204         return err;
5205     }
5206     return 0;
5207 }
5208 
5209 static void hci_power_control_off(void){
5210 
5211     log_info("hci_power_control_off");
5212 
5213     // close low-level device
5214     hci_stack->hci_transport->close();
5215 
5216     log_info("hci_power_control_off - hci_transport closed");
5217 
5218     // power off
5219     if (hci_stack->control && hci_stack->control->off){
5220         (*hci_stack->control->off)();
5221     }
5222 
5223     log_info("hci_power_control_off - control closed");
5224 
5225     hci_stack->state = HCI_STATE_OFF;
5226 }
5227 
5228 static void hci_power_control_sleep(void){
5229 
5230     log_info("hci_power_control_sleep");
5231 
5232 #if 0
5233     // don't close serial port during sleep
5234 
5235     // close low-level device
5236     hci_stack->hci_transport->close(hci_stack->config);
5237 #endif
5238 
5239     // sleep mode
5240     if (hci_stack->control && hci_stack->control->sleep){
5241         (*hci_stack->control->sleep)();
5242     }
5243 
5244     hci_stack->state = HCI_STATE_SLEEPING;
5245 }
5246 
5247 static int hci_power_control_wake(void){
5248 
5249     log_info("hci_power_control_wake");
5250 
5251     // wake on
5252     if (hci_stack->control && hci_stack->control->wake){
5253         (*hci_stack->control->wake)();
5254     }
5255 
5256 #if 0
5257     // open low-level device
5258     int err = hci_stack->hci_transport->open(hci_stack->config);
5259     if (err){
5260         log_error( "HCI_INIT failed, turning Bluetooth off again");
5261         if (hci_stack->control && hci_stack->control->off){
5262             (*hci_stack->control->off)();
5263         }
5264         hci_emit_hci_open_failed();
5265         return err;
5266     }
5267 #endif
5268 
5269     return 0;
5270 }
5271 
5272 static void hci_power_enter_initializing_state(void){
5273     // set up state machine
5274     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
5275     hci_stack->hci_packet_buffer_reserved = false;
5276     hci_stack->state = HCI_STATE_INITIALIZING;
5277 
5278 #ifndef HAVE_HOST_CONTROLLER_API
5279     if (hci_stack->chipset_pre_init) {
5280         hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
5281     } else
5282 #endif
5283     {
5284         hci_stack->substate = HCI_INIT_SEND_RESET;
5285     }
5286 }
5287 
5288 static void hci_power_enter_halting_state(void){
5289 #ifdef ENABLE_BLE
5290     // drop entries scheduled for removal, mark others for re-adding
5291     btstack_linked_list_iterator_t it;
5292     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5293     while (btstack_linked_list_iterator_has_next(&it)){
5294         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5295         if ((entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)) == LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5296             btstack_linked_list_iterator_remove(&it);
5297             btstack_memory_whitelist_entry_free(entry);
5298         } else {
5299             entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5300         }
5301     }
5302 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5303     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
5304     const uint8_t mask = LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5305     while (btstack_linked_list_iterator_has_next(&it)){
5306         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
5307         if ((entry->state & mask) == LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER) {
5308             btstack_linked_list_iterator_remove(&it);
5309             btstack_memory_periodic_advertiser_list_entry_free(entry);
5310         } else {
5311             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5312             continue;
5313         }
5314     }
5315 #endif
5316 #endif
5317     // see hci_run
5318     hci_stack->state = HCI_STATE_HALTING;
5319     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
5320     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
5321     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
5322     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5323     btstack_run_loop_add_timer(&hci_stack->timeout);
5324 }
5325 
5326 // returns error
5327 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
5328     int err;
5329     switch (power_mode){
5330         case HCI_POWER_ON:
5331             err = hci_power_control_on();
5332             if (err != 0) {
5333                 log_error("hci_power_control_on() error %d", err);
5334                 return err;
5335             }
5336             hci_power_enter_initializing_state();
5337             break;
5338         case HCI_POWER_OFF:
5339             // do nothing
5340             break;
5341         case HCI_POWER_SLEEP:
5342             // do nothing (with SLEEP == OFF)
5343             break;
5344         default:
5345             btstack_assert(false);
5346             break;
5347     }
5348     return ERROR_CODE_SUCCESS;
5349 }
5350 
5351 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
5352     switch (power_mode){
5353         case HCI_POWER_ON:
5354             // do nothing
5355             break;
5356         case HCI_POWER_OFF:
5357             // no connections yet, just turn it off
5358             hci_power_control_off();
5359             break;
5360         case HCI_POWER_SLEEP:
5361             // no connections yet, just turn it off
5362             hci_power_control_sleep();
5363             break;
5364         default:
5365             btstack_assert(false);
5366             break;
5367     }
5368     return ERROR_CODE_SUCCESS;
5369 }
5370 
5371 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
5372     switch (power_mode){
5373         case HCI_POWER_ON:
5374             // do nothing
5375             break;
5376         case HCI_POWER_OFF:
5377             hci_power_enter_halting_state();
5378             break;
5379         case HCI_POWER_SLEEP:
5380             // see hci_run
5381             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5382             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5383             break;
5384         default:
5385             btstack_assert(false);
5386             break;
5387     }
5388     return ERROR_CODE_SUCCESS;
5389 }
5390 
5391 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
5392     switch (power_mode){
5393         case HCI_POWER_ON:
5394             hci_power_enter_initializing_state();
5395             break;
5396         case HCI_POWER_OFF:
5397             // do nothing
5398             break;
5399         case HCI_POWER_SLEEP:
5400             // see hci_run
5401             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5402             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5403             break;
5404         default:
5405             btstack_assert(false);
5406             break;
5407     }
5408     return ERROR_CODE_SUCCESS;
5409 }
5410 
5411 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
5412     switch (power_mode){
5413         case HCI_POWER_ON:
5414             hci_power_enter_initializing_state();
5415             break;
5416         case HCI_POWER_OFF:
5417             hci_power_enter_halting_state();
5418             break;
5419         case HCI_POWER_SLEEP:
5420             // do nothing
5421             break;
5422         default:
5423             btstack_assert(false);
5424             break;
5425     }
5426     return ERROR_CODE_SUCCESS;
5427 }
5428 
5429 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
5430     int err;
5431     switch (power_mode){
5432         case HCI_POWER_ON:
5433             err = hci_power_control_wake();
5434             if (err) return err;
5435             hci_power_enter_initializing_state();
5436             break;
5437         case HCI_POWER_OFF:
5438             hci_power_enter_halting_state();
5439             break;
5440         case HCI_POWER_SLEEP:
5441             // do nothing
5442             break;
5443         default:
5444             btstack_assert(false);
5445             break;
5446     }
5447     return ERROR_CODE_SUCCESS;
5448 }
5449 
5450 int hci_power_control(HCI_POWER_MODE power_mode){
5451     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
5452     btstack_run_loop_remove_timer(&hci_stack->timeout);
5453     int err = 0;
5454     switch (hci_stack->state){
5455         case HCI_STATE_OFF:
5456             err = hci_power_control_state_off(power_mode);
5457             break;
5458         case HCI_STATE_INITIALIZING:
5459             err = hci_power_control_state_initializing(power_mode);
5460             break;
5461         case HCI_STATE_WORKING:
5462             err = hci_power_control_state_working(power_mode);
5463             break;
5464         case HCI_STATE_HALTING:
5465             err = hci_power_control_state_halting(power_mode);
5466             break;
5467         case HCI_STATE_FALLING_ASLEEP:
5468             err = hci_power_control_state_falling_asleep(power_mode);
5469             break;
5470         case HCI_STATE_SLEEPING:
5471             err = hci_power_control_state_sleeping(power_mode);
5472             break;
5473         default:
5474             btstack_assert(false);
5475             break;
5476     }
5477     if (err != 0){
5478         return err;
5479     }
5480 
5481     // create internal event
5482 	hci_emit_state();
5483 
5484 	// trigger next/first action
5485 	hci_run();
5486 
5487     return 0;
5488 }
5489 
5490 
5491 static void hci_halting_run(void) {
5492 
5493     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5494 
5495     hci_connection_t *connection;
5496 #ifdef ENABLE_BLE
5497 #ifdef ENABLE_LE_PERIPHERAL
5498     bool stop_advertismenets;
5499 #endif
5500 #endif
5501 
5502     switch (hci_stack->substate) {
5503         case HCI_HALTING_CLASSIC_STOP:
5504 #ifdef ENABLE_CLASSIC
5505             if (!hci_can_send_command_packet_now()) return;
5506 
5507             if (hci_stack->connectable || hci_stack->discoverable){
5508                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5509                 hci_send_cmd(&hci_write_scan_enable, 0);
5510                 return;
5511             }
5512 #endif
5513             /* fall through */
5514 
5515         case HCI_HALTING_LE_ADV_STOP:
5516             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5517 
5518 #ifdef ENABLE_BLE
5519 #ifdef ENABLE_LE_PERIPHERAL
5520             if (!hci_can_send_command_packet_now()) return;
5521 
5522             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5523 
5524 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5525             if (hci_le_extended_advertising_supported()){
5526 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5527                 btstack_linked_list_iterator_t it;
5528                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5529                 // stop all periodic advertisements and check if an extended set is active
5530                 while (btstack_linked_list_iterator_has_next(&it)){
5531                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5532                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5533                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5534                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
5535                         return;
5536                     }
5537                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5538                         stop_advertismenets = true;
5539                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5540                     }
5541                 }
5542 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5543                 if (stop_advertismenets){
5544                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5545                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5546                     return;
5547                 }
5548             } else
5549 #else /* ENABLE_LE_PERIPHERAL */
5550             {
5551                 if (stop_advertismenets) {
5552                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5553                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5554                     return;
5555                 }
5556             }
5557 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5558 #endif  /* ENABLE_LE_PERIPHERAL */
5559 #endif  /* ENABLE_BLE */
5560 
5561             /* fall through */
5562 
5563         case HCI_HALTING_LE_SCAN_STOP:
5564             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5565             if (!hci_can_send_command_packet_now()) return;
5566 
5567 #ifdef ENABLE_BLE
5568 #ifdef ENABLE_LE_CENTRAL
5569             if (hci_stack->le_scanning_active){
5570                 hci_le_scan_stop();
5571                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5572                 return;
5573             }
5574 #endif
5575 #endif
5576 
5577             /* fall through */
5578 
5579         case HCI_HALTING_DISCONNECT_ALL:
5580             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5581             if (!hci_can_send_command_packet_now()) return;
5582 
5583             // close all open connections
5584             connection = (hci_connection_t *) hci_stack->connections;
5585             if (connection) {
5586                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5587 
5588                 log_info("HCI_STATE_HALTING, connection %p, handle %u, state %u", connection, con_handle, connection->state);
5589 
5590                 // check state
5591                 switch(connection->state) {
5592                     case SENT_DISCONNECT:
5593                     case RECEIVED_DISCONNECTION_COMPLETE:
5594                         // wait until connection is gone
5595                         return;
5596                     default:
5597                         break;
5598                 }
5599 
5600                 // finally, send the disconnect command
5601                 connection->state = SENT_DISCONNECT;
5602                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5603                 return;
5604             }
5605 
5606 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5607             // stop BIGs and BIG Syncs
5608             if (hci_stack->le_audio_bigs != NULL){
5609                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5610                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5611                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5612                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5613                 return;
5614             }
5615             if (hci_stack->le_audio_big_syncs != NULL){
5616                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5617                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5618                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5619                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5620                 return;
5621             }
5622 #endif
5623 
5624             btstack_run_loop_remove_timer(&hci_stack->timeout);
5625 
5626             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5627             log_info("HCI_STATE_HALTING: wait 50 ms");
5628             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5629             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5630             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5631             btstack_run_loop_add_timer(&hci_stack->timeout);
5632             break;
5633 
5634         case HCI_HALTING_W4_CLOSE_TIMER:
5635             // keep waiting
5636             break;
5637 
5638         case HCI_HALTING_CLOSE:
5639             // close left over connections (that had not been properly closed before)
5640             hci_stack->substate = HCI_HALTING_CLOSE_DISCARDING_CONNECTIONS;
5641             hci_discard_connections();
5642 
5643             log_info("HCI_STATE_HALTING, calling off");
5644 
5645             // switch mode
5646             hci_power_control_off();
5647 
5648             log_info("HCI_STATE_HALTING, emitting state");
5649             hci_emit_state();
5650             log_info("HCI_STATE_HALTING, done");
5651             break;
5652 
5653         default:
5654             break;
5655     }
5656 };
5657 
5658 static void hci_falling_asleep_run(void){
5659     hci_connection_t * connection;
5660     switch(hci_stack->substate) {
5661         case HCI_FALLING_ASLEEP_DISCONNECT:
5662             log_info("HCI_STATE_FALLING_ASLEEP");
5663             // close all open connections
5664             connection =  (hci_connection_t *) hci_stack->connections;
5665             if (connection){
5666 
5667                 // send disconnect
5668                 if (!hci_can_send_command_packet_now()) return;
5669 
5670                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5671                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5672 
5673                 // send disconnected event right away - causes higher layer connections to get closed, too.
5674                 hci_shutdown_connection(connection);
5675                 return;
5676             }
5677 
5678             if (hci_classic_supported()){
5679                 // disable page and inquiry scan
5680                 if (!hci_can_send_command_packet_now()) return;
5681 
5682                 log_info("HCI_STATE_HALTING, disabling inq scans");
5683                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5684 
5685                 // continue in next sub state
5686                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5687                 break;
5688             }
5689 
5690             /* fall through */
5691 
5692             case HCI_FALLING_ASLEEP_COMPLETE:
5693                 log_info("HCI_STATE_HALTING, calling sleep");
5694                 // switch mode
5695                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5696                 hci_emit_state();
5697                 break;
5698 
5699                 default:
5700                     break;
5701     }
5702 }
5703 
5704 #ifdef ENABLE_CLASSIC
5705 
5706 static void hci_update_scan_enable(void){
5707     // 2 = page scan, 1 = inq scan
5708     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5709     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5710     hci_run();
5711 }
5712 
5713 void gap_discoverable_control(uint8_t enable){
5714     if (enable) enable = 1; // normalize argument
5715 
5716     if (hci_stack->discoverable == enable){
5717         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5718         return;
5719     }
5720 
5721     hci_stack->discoverable = enable;
5722     hci_update_scan_enable();
5723 }
5724 
5725 void gap_connectable_control(uint8_t enable){
5726     if (enable) enable = 1; // normalize argument
5727 
5728     // don't emit event
5729     if (hci_stack->connectable == enable) return;
5730 
5731     hci_stack->connectable = enable;
5732     hci_update_scan_enable();
5733 }
5734 #endif
5735 
5736 void gap_local_bd_addr(bd_addr_t address_buffer){
5737     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5738 }
5739 
5740 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5741 static void hci_host_num_completed_packets(void){
5742 
5743     // create packet manually as arrays are not supported and num_commands should not get reduced
5744     hci_reserve_packet_buffer();
5745     uint8_t * packet = hci_get_outgoing_packet_buffer();
5746 
5747     uint16_t size = 0;
5748     uint16_t num_handles = 0;
5749     packet[size++] = 0x35;
5750     packet[size++] = 0x0c;
5751     size++;  // skip param len
5752     size++;  // skip num handles
5753 
5754     // add { handle, packets } entries
5755     btstack_linked_item_t * it;
5756     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5757         hci_connection_t * connection = (hci_connection_t *) it;
5758         if (connection->num_packets_completed){
5759             little_endian_store_16(packet, size, connection->con_handle);
5760             size += 2;
5761             little_endian_store_16(packet, size, connection->num_packets_completed);
5762             size += 2;
5763             //
5764             num_handles++;
5765             connection->num_packets_completed = 0;
5766         }
5767     }
5768 
5769     packet[2] = size - 3;
5770     packet[3] = num_handles;
5771 
5772     hci_stack->host_completed_packets = 0;
5773 
5774     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5775     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5776 
5777     // release packet buffer for synchronous transport implementations
5778     if (hci_transport_synchronous()){
5779         hci_release_packet_buffer();
5780         hci_emit_transport_packet_sent();
5781     }
5782 }
5783 #endif
5784 
5785 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5786     UNUSED(ds);
5787     hci_stack->substate = HCI_HALTING_CLOSE;
5788     hci_halting_run();
5789 }
5790 
5791 static bool hci_run_acl_fragments(void){
5792     if (hci_stack->acl_fragmentation_total_size > 0u) {
5793         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5794         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5795         if (connection) {
5796             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5797                 hci_send_acl_packet_fragments(connection);
5798                 return true;
5799             }
5800         } else {
5801             // connection gone -> discard further fragments
5802             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5803             hci_stack->acl_fragmentation_total_size = 0;
5804             hci_stack->acl_fragmentation_pos = 0;
5805         }
5806     }
5807     return false;
5808 }
5809 
5810 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5811 static bool hci_run_iso_fragments(void){
5812     if (hci_stack->iso_fragmentation_total_size > 0u) {
5813         // TODO: flow control
5814         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5815             hci_send_iso_packet_fragments();
5816             return true;
5817         }
5818     }
5819     return false;
5820 }
5821 #endif
5822 
5823 #ifdef ENABLE_CLASSIC
5824 
5825 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5826 static bool hci_classic_operation_active(void) {
5827     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5828         return true;
5829     }
5830     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5831         return true;
5832     }
5833     btstack_linked_item_t * it;
5834     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5835         hci_connection_t *connection = (hci_connection_t *) it;
5836         switch (connection->state) {
5837             case SENT_CREATE_CONNECTION:
5838             case SENT_CANCEL_CONNECTION:
5839             case SENT_DISCONNECT:
5840                 return true;
5841             default:
5842                 break;
5843         }
5844     }
5845     return false;
5846 }
5847 #endif
5848 
5849 static bool hci_run_general_gap_classic(void){
5850 
5851     // assert stack is working and classic is active
5852     if (hci_classic_supported() == false)      return false;
5853     if (hci_stack->state != HCI_STATE_WORKING) return false;
5854 
5855     // decline incoming connections
5856     if (hci_stack->decline_reason){
5857         uint8_t reason = hci_stack->decline_reason;
5858         hci_stack->decline_reason = 0;
5859         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5860         return true;
5861     }
5862 
5863     if (hci_stack->gap_tasks_classic != 0){
5864         hci_run_gap_tasks_classic();
5865         return true;
5866     }
5867 
5868     // start/stop inquiry
5869     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5870 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5871         if (hci_classic_operation_active() == false)
5872 #endif
5873         {
5874             uint8_t duration = hci_stack->inquiry_state;
5875             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5876             if (hci_stack->inquiry_max_period_length != 0){
5877                 hci_send_cmd(&hci_periodic_inquiry_mode, hci_stack->inquiry_max_period_length, hci_stack->inquiry_min_period_length, hci_stack->inquiry_lap, duration, 0);
5878             } else {
5879                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5880             }
5881             return true;
5882         }
5883     }
5884     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5885         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5886         hci_send_cmd(&hci_inquiry_cancel);
5887         return true;
5888     }
5889 
5890     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5891         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5892         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5893         return true;
5894     }
5895 
5896     // remote name request
5897     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5898 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5899         if (hci_classic_operation_active() == false)
5900 #endif
5901         {
5902             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5903             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5904                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5905             return true;
5906         }
5907     }
5908 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5909     // Local OOB data
5910     if (hci_stack->classic_read_local_oob_data){
5911         hci_stack->classic_read_local_oob_data = false;
5912         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5913             hci_send_cmd(&hci_read_local_extended_oob_data);
5914         } else {
5915             hci_send_cmd(&hci_read_local_oob_data);
5916         }
5917     }
5918 #endif
5919     // pairing
5920     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5921         uint8_t state = hci_stack->gap_pairing_state;
5922         uint8_t pin_code[PIN_CODE_LEN];
5923         switch (state){
5924             case GAP_PAIRING_STATE_SEND_PIN:
5925                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5926                 memset(pin_code, 0, 16);
5927                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5928                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5929                 break;
5930             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5931                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5932                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5933                 break;
5934             case GAP_PAIRING_STATE_SEND_PASSKEY:
5935                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5936                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5937                 break;
5938             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5939                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5940                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5941                 break;
5942             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5943                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5944                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5945                 break;
5946             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5947                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5948                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5949                 break;
5950             default:
5951                 break;
5952         }
5953         return true;
5954     }
5955     return false;
5956 }
5957 #endif
5958 
5959 #ifdef ENABLE_BLE
5960 
5961 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5962 static uint8_t hci_le_num_phys(uint8_t phys){
5963     const uint8_t num_bits_set[] = { 0, 1, 1, 2, 1, 2, 2, 3 };
5964     btstack_assert(phys);
5965     return num_bits_set[phys];
5966 }
5967 #endif
5968 
5969 #ifdef ENABLE_LE_CENTRAL
5970 static void hci_le_scan_stop(void){
5971 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5972     if (hci_le_extended_advertising_supported()) {
5973             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5974     } else
5975 #endif
5976     {
5977         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5978     }
5979 }
5980 
5981 static void
5982 hci_send_le_create_connection(uint8_t initiator_filter_policy, bd_addr_type_t address_type, uint8_t *address) {
5983 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5984     if (hci_le_extended_advertising_supported()) {
5985         // prepare arrays for all phys (LE Coded, LE 1M, LE 2M PHY)
5986         uint16_t le_connection_scan_interval[3];
5987         uint16_t le_connection_scan_window[3];
5988         uint16_t le_connection_interval_min[3];
5989         uint16_t le_connection_interval_max[3];
5990         uint16_t le_connection_latency[3];
5991         uint16_t le_supervision_timeout[3];
5992         uint16_t le_minimum_ce_length[3];
5993         uint16_t le_maximum_ce_length[3];
5994 
5995         uint8_t i;
5996         uint8_t num_phys = hci_le_num_phys(hci_stack->le_connection_phys);
5997         for (i=0;i<num_phys;i++){
5998             le_connection_scan_interval[i] = hci_stack->le_connection_scan_interval;
5999             le_connection_scan_window[i]   = hci_stack->le_connection_scan_window;
6000             le_connection_interval_min[i]  = hci_stack->le_connection_interval_min;
6001             le_connection_interval_max[i]  = hci_stack->le_connection_interval_max;
6002             le_connection_latency[i]       = hci_stack->le_connection_latency;
6003             le_supervision_timeout[i]      = hci_stack->le_supervision_timeout;
6004             le_minimum_ce_length[i]        = hci_stack->le_minimum_ce_length;
6005             le_maximum_ce_length[i]        = hci_stack->le_maximum_ce_length;
6006         }
6007         hci_send_cmd(&hci_le_extended_create_connection,
6008                      initiator_filter_policy,
6009                      hci_stack->le_connection_own_addr_type,   // our addr type:
6010                      address_type,                  // peer address type
6011                      address,                       // peer bd addr
6012                      hci_stack->le_connection_phys, // initiating PHY
6013                      le_connection_scan_interval,   // conn scan interval
6014                      le_connection_scan_window,     // conn scan windows
6015                      le_connection_interval_min,    // conn interval min
6016                      le_connection_interval_max,    // conn interval max
6017                      le_connection_latency,         // conn latency
6018                      le_supervision_timeout,        // conn latency
6019                      le_minimum_ce_length,          // min ce length
6020                      le_maximum_ce_length           // max ce length
6021         );
6022     } else
6023 #endif
6024     {
6025         hci_send_cmd(&hci_le_create_connection,
6026                      hci_stack->le_connection_scan_interval,  // conn scan interval
6027                      hci_stack->le_connection_scan_window,    // conn scan windows
6028                      initiator_filter_policy,                 // don't use whitelist
6029                      address_type,                            // peer address type
6030                      address,                                 // peer bd addr
6031                      hci_stack->le_connection_own_addr_type,  // our addr type:
6032                      hci_stack->le_connection_interval_min,   // conn interval min
6033                      hci_stack->le_connection_interval_max,   // conn interval max
6034                      hci_stack->le_connection_latency,        // conn latency
6035                      hci_stack->le_supervision_timeout,       // conn latency
6036                      hci_stack->le_minimum_ce_length,         // min ce length
6037                      hci_stack->le_maximum_ce_length          // max ce length
6038         );
6039     }
6040 }
6041 #endif
6042 
6043 #ifdef ENABLE_LE_PERIPHERAL
6044 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6045 static uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
6046     uint8_t  operation = 0;
6047     if (pos == 0){
6048         // first fragment or complete data
6049         operation |= 1;
6050     }
6051     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
6052         // last fragment or complete data
6053         operation |= 2;
6054     }
6055     return operation;
6056 }
6057 #endif
6058 #endif
6059 
6060 static bool hci_run_general_gap_le(void){
6061 
6062     btstack_linked_list_iterator_t lit;
6063 
6064 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6065     if (hci_stack->le_resolvable_private_address_update_s > 0){
6066         uint16_t update_s = hci_stack->le_resolvable_private_address_update_s;
6067         hci_stack->le_resolvable_private_address_update_s = 0;
6068         hci_send_cmd(&hci_le_set_resolvable_private_address_timeout, update_s);
6069         return true;
6070     }
6071 #endif
6072 
6073     // Phase 1: collect what to stop
6074 
6075 #ifdef ENABLE_LE_CENTRAL
6076     bool scanning_stop = false;
6077     bool connecting_stop = false;
6078 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6079 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6080     bool periodic_sync_stop = false;
6081 #endif
6082 #endif
6083 #endif
6084 
6085 #ifdef ENABLE_LE_PERIPHERAL
6086     bool advertising_stop = false;
6087 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6088     le_advertising_set_t * advertising_stop_set = NULL;
6089 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6090     bool periodic_advertising_stop = false;
6091 #endif
6092 #endif
6093 #endif
6094 
6095     // check if own address changes
6096     uint8_t address_change_mask = LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
6097     bool random_address_change = (hci_stack->le_advertisements_todo & address_change_mask) != 0;
6098 
6099     // check if whitelist needs modification
6100     bool whitelist_modification_pending = false;
6101     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6102     while (btstack_linked_list_iterator_has_next(&lit)){
6103         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6104         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
6105             whitelist_modification_pending = true;
6106             break;
6107         }
6108     }
6109 
6110     // check if resolving list needs modification
6111     bool resolving_list_modification_pending = false;
6112 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6113     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
6114 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
6115         resolving_list_modification_pending = true;
6116     }
6117 #endif
6118 
6119 #ifdef ENABLE_LE_CENTRAL
6120 
6121 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6122     // check if periodic advertiser list needs modification
6123     bool periodic_list_modification_pending = false;
6124     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6125     while (btstack_linked_list_iterator_has_next(&lit)){
6126         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6127         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
6128             periodic_list_modification_pending = true;
6129             break;
6130         }
6131     }
6132 #endif
6133 
6134     // scanning control
6135     if (hci_stack->le_scanning_active) {
6136         // stop if:
6137         // - parameter change required
6138         // - it's disabled
6139         // - whitelist change required but used for scanning
6140         // - resolving list modified
6141         // - own address changes
6142         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
6143         if ((hci_stack->le_scanning_param_update) ||
6144             !hci_stack->le_scanning_enabled ||
6145             (scanning_uses_whitelist && whitelist_modification_pending) ||
6146             resolving_list_modification_pending ||
6147             random_address_change){
6148 
6149             scanning_stop = true;
6150         }
6151     }
6152 
6153     // connecting control
6154     bool connecting_with_whitelist;
6155     switch (hci_stack->le_connecting_state){
6156         case LE_CONNECTING_DIRECT:
6157         case LE_CONNECTING_WHITELIST:
6158             // stop connecting if:
6159             // - connecting uses white and whitelist modification pending
6160             // - if it got disabled
6161             // - resolving list modified
6162             // - own address changes
6163             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
6164             if ((connecting_with_whitelist && whitelist_modification_pending) ||
6165                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
6166                 resolving_list_modification_pending ||
6167                 random_address_change) {
6168 
6169                 connecting_stop = true;
6170             }
6171             break;
6172         default:
6173             break;
6174     }
6175 
6176 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6177 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6178     // periodic sync control
6179     bool sync_with_advertiser_list;
6180     switch(hci_stack->le_periodic_sync_state){
6181         case LE_CONNECTING_DIRECT:
6182         case LE_CONNECTING_WHITELIST:
6183             // stop sync if:
6184             // - sync with advertiser list and advertiser list modification pending
6185             // - if it got disabled
6186             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
6187             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
6188                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
6189                 periodic_sync_stop = true;
6190             }
6191             break;
6192         default:
6193             break;
6194     }
6195 #endif
6196 #endif
6197 
6198 #endif /* ENABLE_LE_CENTRAL */
6199 
6200 #ifdef ENABLE_LE_PERIPHERAL
6201     // le advertisement control
6202     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
6203         // stop if:
6204         // - parameter change required
6205         // - random address used in advertising and changes
6206         // - it's disabled
6207         // - whitelist change required but used for advertisement filter policy
6208         // - resolving list modified
6209         // - own address changes
6210         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
6211         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
6212         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
6213         if (advertising_change ||
6214             (advertising_uses_random_address && random_address_change) ||
6215             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
6216             (advertising_uses_whitelist && whitelist_modification_pending) ||
6217             resolving_list_modification_pending ||
6218             random_address_change) {
6219 
6220             advertising_stop = true;
6221         }
6222     }
6223 
6224 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6225     if (hci_le_extended_advertising_supported() && (advertising_stop == false)){
6226         btstack_linked_list_iterator_t it;
6227         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6228         while (btstack_linked_list_iterator_has_next(&it)){
6229             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6230             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
6231                 // stop if:
6232                 // - parameter change required
6233                 // - random address used in connectable advertising and changes
6234                 // - it's disabled
6235                 // - whitelist change required but used for advertisement filter policy
6236                 // - resolving list modified
6237                 // - own address changes
6238                 // - advertisement set will be removed
6239                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
6240                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
6241                 bool advertising_uses_random_address =
6242                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
6243                         advertising_connectable;
6244                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
6245                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
6246                 bool advertising_set_random_address_change =
6247                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
6248                 bool advertising_set_will_be_removed =
6249                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
6250                 if (advertising_parameter_change ||
6251                     (advertising_uses_random_address && advertising_set_random_address_change) ||
6252                     (advertising_enabled == false) ||
6253                     (advertising_uses_whitelist && whitelist_modification_pending) ||
6254                     resolving_list_modification_pending ||
6255                     advertising_set_will_be_removed) {
6256 
6257                     advertising_stop = true;
6258                     advertising_stop_set = advertising_set;
6259                     break;
6260                 }
6261             }
6262 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6263             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
6264                 // stop if:
6265                 // - it's disabled
6266                 // - parameter change required
6267                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
6268                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
6269                 if ((periodic_enabled == false) || periodic_parameter_change){
6270                     periodic_advertising_stop = true;
6271                     advertising_stop_set = advertising_set;
6272                 }
6273             }
6274 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6275         }
6276     }
6277 #endif
6278 
6279 #endif
6280 
6281 
6282     // Phase 2: stop everything that should be off during modifications
6283 
6284 
6285     // 2.1 Outgoing connection
6286 #ifdef ENABLE_LE_CENTRAL
6287     if (connecting_stop){
6288         hci_send_cmd(&hci_le_create_connection_cancel);
6289         return true;
6290     }
6291 #endif
6292 
6293     // 2.2 Scanning
6294 #ifdef ENABLE_LE_CENTRAL
6295     if (scanning_stop){
6296         hci_stack->le_scanning_active = false;
6297         hci_le_scan_stop();
6298         return true;
6299     }
6300 
6301     // 2.3 Periodic Sync
6302 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6303     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
6304         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
6305         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
6306         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
6307         return true;
6308     }
6309 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6310     if (periodic_sync_stop){
6311         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
6312         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
6313         return true;
6314     }
6315 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6316 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6317 #endif /* ENABLE_LE_CENTRAL */
6318 
6319     // 2.4 Advertising: legacy, extended, periodic
6320 #ifdef ENABLE_LE_PERIPHERAL
6321     if (advertising_stop){
6322 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6323         if (hci_le_extended_advertising_supported()) {
6324             uint8_t advertising_stop_handle;
6325             if (advertising_stop_set != NULL){
6326                 advertising_stop_handle = advertising_stop_set->advertising_handle;
6327                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6328             } else {
6329                 advertising_stop_handle = 0;
6330                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6331             }
6332             const uint8_t advertising_handles[] = { advertising_stop_handle };
6333             const uint16_t durations[] = { 0 };
6334             const uint16_t max_events[] = { 0 };
6335             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
6336         } else
6337 #endif
6338         {
6339             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6340             hci_send_cmd(&hci_le_set_advertise_enable, 0);
6341         }
6342         return true;
6343     }
6344 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6345 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6346     if (periodic_advertising_stop){
6347         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6348         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
6349         return true;
6350     }
6351 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6352 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6353 #endif /* ENABLE_LE_PERIPHERAL */
6354 
6355 
6356     // Phase 3: modify
6357 
6358     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY) {
6359         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
6360         // GAP Privacy, notify clients upon upcoming random address change
6361         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
6362         // notify might cause hci_run to get executed, check if we still can send
6363         gap_privacy_clients_notify(hci_stack->le_random_address);
6364         if (!hci_can_send_command_packet_now()) {
6365             return true;
6366         }
6367     }
6368 
6369     // - wait until privacy update completed
6370     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PRIVACY_PENDING) != 0){
6371         return false;
6372     }
6373 
6374     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS){
6375         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6376         hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
6377 #ifdef ENABLE_LE_SET_ADV_PARAMS_ON_RANDOM_ADDRESS_CHANGE
6378         // workaround: on some Controllers, address in advertisements is updated only after next dv params set
6379         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6380 #endif
6381         return true;
6382     }
6383 
6384 #ifdef ENABLE_LE_CENTRAL
6385     if (hci_stack->le_scanning_param_update){
6386         hci_stack->le_scanning_param_update = false;
6387 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6388         if (hci_le_extended_advertising_supported()){
6389             // prepare arrays for all phys (LE Coded and LE 1M PHY)
6390             uint8_t  scan_types[2];
6391             uint16_t scan_intervals[2];
6392             uint16_t scan_windows[2];
6393 
6394             uint8_t i;
6395             uint8_t num_phys = hci_le_num_phys(hci_stack->le_scan_phys);
6396             for (i=0;i<num_phys;i++){
6397                 scan_types[i]     = hci_stack->le_scan_type;
6398                 scan_intervals[i] = hci_stack->le_scan_interval;
6399                 scan_windows[i]   = hci_stack->le_scan_window;
6400             }
6401             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
6402                          hci_stack->le_scan_filter_policy, hci_stack->le_scan_phys, scan_types, scan_intervals, scan_windows);
6403         } else
6404 #endif
6405         {
6406             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
6407                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
6408         }
6409         return true;
6410     }
6411 #endif
6412 
6413 #ifdef ENABLE_LE_PERIPHERAL
6414     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
6415         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6416         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
6417 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6418         if (hci_le_extended_advertising_supported()){
6419             // map advertisment type to advertising event properties
6420             uint16_t adv_event_properties = 0;
6421             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
6422             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
6423                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
6424             }
6425             hci_stack->le_advertising_set_in_current_command = 0;
6426             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6427                          0,
6428                          adv_event_properties,
6429                          hci_stack->le_advertisements_interval_min,
6430                          hci_stack->le_advertisements_interval_max,
6431                          hci_stack->le_advertisements_channel_map,
6432                          hci_stack->le_advertisements_own_addr_type,
6433                          hci_stack->le_advertisements_direct_address_type,
6434                          hci_stack->le_advertisements_direct_address,
6435                          hci_stack->le_advertisements_filter_policy,
6436                          0x7f,  // tx power: no preference
6437                          0x01,  // primary adv phy: LE 1M
6438                          0,     // secondary adv max skip
6439                          0x01,  // secondary adv phy
6440                          0,     // adv sid
6441                          0      // scan request notification
6442                          );
6443         } else
6444 #endif
6445         {
6446             hci_send_cmd(&hci_le_set_advertising_parameters,
6447                          hci_stack->le_advertisements_interval_min,
6448                          hci_stack->le_advertisements_interval_max,
6449                          hci_stack->le_advertisements_type,
6450                          hci_stack->le_advertisements_own_addr_type,
6451                          hci_stack->le_advertisements_direct_address_type,
6452                          hci_stack->le_advertisements_direct_address,
6453                          hci_stack->le_advertisements_channel_map,
6454                          hci_stack->le_advertisements_filter_policy);
6455         }
6456         return true;
6457     }
6458 
6459 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6460     // assumption: only set if extended advertising is supported
6461     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0) != 0){
6462         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
6463         hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
6464         return true;
6465     }
6466 #endif
6467 
6468     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
6469         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6470         uint8_t adv_data_clean[31];
6471         memset(adv_data_clean, 0, sizeof(adv_data_clean));
6472         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
6473                      hci_stack->le_advertisements_data_len);
6474         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
6475 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6476         if (hci_le_extended_advertising_supported()){
6477             hci_stack->le_advertising_set_in_current_command = 0;
6478             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
6479         } else
6480 #endif
6481         {
6482             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
6483         }
6484         return true;
6485     }
6486 
6487     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
6488         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6489         uint8_t scan_data_clean[31];
6490         memset(scan_data_clean, 0, sizeof(scan_data_clean));
6491         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
6492                      hci_stack->le_scan_response_data_len);
6493         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6494 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6495         if (hci_le_extended_advertising_supported()){
6496             hci_stack->le_advertising_set_in_current_command = 0;
6497             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6498         } else
6499 #endif
6500         {
6501             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6502         }
6503         return true;
6504     }
6505 
6506 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6507     if (hci_le_extended_advertising_supported()) {
6508         btstack_linked_list_iterator_t it;
6509         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6510         while (btstack_linked_list_iterator_has_next(&it)){
6511             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6512             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6513                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6514                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6515                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6516                 return true;
6517             }
6518             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6519                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6520                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6521                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6522                              advertising_set->advertising_handle,
6523                              advertising_set->extended_params.advertising_event_properties,
6524                              advertising_set->extended_params.primary_advertising_interval_min,
6525                              advertising_set->extended_params.primary_advertising_interval_max,
6526                              advertising_set->extended_params.primary_advertising_channel_map,
6527                              advertising_set->extended_params.own_address_type,
6528                              advertising_set->extended_params.peer_address_type,
6529                              advertising_set->extended_params.peer_address,
6530                              advertising_set->extended_params.advertising_filter_policy,
6531                              advertising_set->extended_params.advertising_tx_power,
6532                              advertising_set->extended_params.primary_advertising_phy,
6533                              advertising_set->extended_params.secondary_advertising_max_skip,
6534                              advertising_set->extended_params.secondary_advertising_phy,
6535                              advertising_set->extended_params.advertising_sid,
6536                              advertising_set->extended_params.scan_request_notification_enable
6537                 );
6538                 return true;
6539             }
6540             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
6541                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6542                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
6543                 return true;
6544             }
6545             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6546                 uint16_t pos = advertising_set->adv_data_pos;
6547                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6548                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6549                 if ((operation & 0x02) != 0){
6550                     // last fragment or complete data
6551                     operation |= 2;
6552                     advertising_set->adv_data_pos = 0;
6553                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6554                 } else {
6555                     advertising_set->adv_data_pos += data_to_upload;
6556                 }
6557                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6558                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6559                 return true;
6560             }
6561             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6562                 uint16_t pos = advertising_set->scan_data_pos;
6563                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6564                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6565                 if ((operation & 0x02) != 0){
6566                     advertising_set->scan_data_pos = 0;
6567                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6568                 } else {
6569                     advertising_set->scan_data_pos += data_to_upload;
6570                 }
6571                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6572                 hci_send_cmd(&hci_le_set_extended_scan_response_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
6573                 return true;
6574             }
6575 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6576             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
6577                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
6578                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6579                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
6580                              advertising_set->advertising_handle,
6581                              advertising_set->periodic_params.periodic_advertising_interval_min,
6582                              advertising_set->periodic_params.periodic_advertising_interval_max,
6583                              advertising_set->periodic_params.periodic_advertising_properties);
6584                 return true;
6585             }
6586             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
6587                 uint16_t pos = advertising_set->periodic_data_pos;
6588                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
6589                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6590                 if ((operation & 0x02) != 0){
6591                     // last fragment or complete data
6592                     operation |= 2;
6593                     advertising_set->periodic_data_pos = 0;
6594                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
6595                 } else {
6596                     advertising_set->periodic_data_pos += data_to_upload;
6597                 }
6598                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6599                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
6600                 return true;
6601             }
6602 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6603         }
6604     }
6605 #endif
6606 
6607 #endif
6608 
6609 #ifdef ENABLE_LE_CENTRAL
6610     // if connect with whitelist was active and is not cancelled yet, wait until next time
6611     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
6612 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6613     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
6614     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
6615 #endif
6616 #endif
6617 
6618     // LE Whitelist Management
6619     if (whitelist_modification_pending){
6620         // add/remove entries
6621         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6622         while (btstack_linked_list_iterator_has_next(&lit)){
6623             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6624 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
6625 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6626                 entry->state &= ~LE_WHITELIST_ON_CONTROLLER;
6627                 bd_addr_type_t address_type = entry->address_type;
6628                 bd_addr_t address;
6629                 memcpy(address, entry->address, 6);
6630                 if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) == 0){
6631                     // remove from whitelist if not scheduled for re-addition
6632                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6633                     btstack_memory_whitelist_entry_free(entry);
6634                 }
6635 				hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
6636 				return true;
6637 			}
6638             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
6639 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
6640                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
6641                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
6642                 return true;
6643             }
6644         }
6645     }
6646 
6647 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6648     // LE Resolving List Management
6649     if (resolving_list_modification_pending) {
6650 		uint16_t i;
6651         uint8_t null_16[16];
6652         uint8_t local_irk_flipped[16];
6653         const uint8_t *local_irk;
6654 		switch (hci_stack->le_resolving_list_state) {
6655 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
6656 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6657 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
6658 				return true;
6659 			case LE_RESOLVING_LIST_READ_SIZE:
6660 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
6661 				hci_send_cmd(&hci_le_read_resolving_list_size);
6662 				return true;
6663 			case LE_RESOLVING_LIST_SEND_CLEAR:
6664 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SET_IRK;
6665 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6666 							  sizeof(hci_stack->le_resolving_list_add_entries));
6667                 (void) memset(hci_stack->le_resolving_list_set_privacy_mode, 0xff,
6668                               sizeof(hci_stack->le_resolving_list_set_privacy_mode));
6669 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6670 							  sizeof(hci_stack->le_resolving_list_remove_entries));
6671 				hci_send_cmd(&hci_le_clear_resolving_list);
6672 				return true;
6673             case LE_RESOLVING_LIST_SET_IRK:
6674                 // set IRK used by RPA for undirected advertising
6675                 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
6676                 local_irk = gap_get_persistent_irk();
6677                 reverse_128(local_irk, local_irk_flipped);
6678                 memset(null_16, 0, sizeof(null_16));
6679                 hci_send_cmd(&hci_le_add_device_to_resolving_list, BD_ADDR_TYPE_LE_PUBLIC, null_16,
6680                              null_16, local_irk_flipped);
6681                 return true;
6682 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
6683                 // first remove old entries
6684 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6685 					uint8_t offset = i >> 3;
6686 					uint8_t mask = 1 << (i & 7);
6687 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
6688 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
6689 					bd_addr_t peer_identity_addreses;
6690 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6691 					sm_key_t peer_irk;
6692 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6693 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6694 
6695 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6696 					// trigger whitelist entry 'update' (work around for controller bug)
6697 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6698 					while (btstack_linked_list_iterator_has_next(&lit)) {
6699 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6700 						if (entry->address_type != peer_identity_addr_type) continue;
6701 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6702 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6703 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6704 					}
6705 #endif
6706 
6707 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6708 								 peer_identity_addreses);
6709 					return true;
6710 				}
6711 
6712                 // then add new entries
6713 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6714 					uint8_t offset = i >> 3;
6715 					uint8_t mask = 1 << (i & 7);
6716 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
6717 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
6718 					bd_addr_t peer_identity_addreses;
6719 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6720 					sm_key_t peer_irk;
6721 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6722 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6723                     if (btstack_is_null(peer_irk, 16)) continue;
6724 					local_irk = gap_get_persistent_irk();
6725 					// command uses format specifier 'P' that stores 16-byte value without flip
6726 					uint8_t peer_irk_flipped[16];
6727 					reverse_128(local_irk, local_irk_flipped);
6728 					reverse_128(peer_irk, peer_irk_flipped);
6729 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6730 								 peer_irk_flipped, local_irk_flipped);
6731 					return true;
6732 				}
6733 
6734                 // finally, set privacy mode
6735                 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6736                     uint8_t offset = i >> 3;
6737                     uint8_t mask = 1 << (i & 7);
6738                     if ((hci_stack->le_resolving_list_set_privacy_mode[offset] & mask) == 0) continue;
6739                     hci_stack->le_resolving_list_set_privacy_mode[offset] &= ~mask;
6740                     if (hci_stack->le_privacy_mode == LE_PRIVACY_MODE_NETWORK) {
6741                         // Network Privacy Mode is default
6742                         continue;
6743                     }
6744                     bd_addr_t peer_identity_address;
6745                     int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6746                     sm_key_t peer_irk;
6747                     le_device_db_info(i, &peer_identity_addr_type, peer_identity_address, peer_irk);
6748                     if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6749                     if (btstack_is_null(peer_irk, 16)) continue;
6750                     // command uses format specifier 'P' that stores 16-byte value without flip
6751                     uint8_t peer_irk_flipped[16];
6752                     reverse_128(peer_irk, peer_irk_flipped);
6753                     hci_send_cmd(&hci_le_set_privacy_mode, peer_identity_addr_type, peer_identity_address, hci_stack->le_privacy_mode);
6754                     return true;
6755                 }
6756 				break;
6757 
6758 			default:
6759 				break;
6760 		}
6761         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6762 	}
6763 #endif
6764 
6765 #ifdef ENABLE_LE_CENTRAL
6766 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6767     // LE Whitelist Management
6768     if (periodic_list_modification_pending){
6769         // add/remove entries
6770         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6771         while (btstack_linked_list_iterator_has_next(&lit)){
6772             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6773             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6774                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6775                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6776                 return true;
6777             }
6778             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6779                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6780                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
6781                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6782                 return true;
6783             }
6784             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6785                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6786                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6787             }
6788         }
6789     }
6790 #endif
6791 #endif
6792 
6793 #ifdef ENABLE_LE_CENTRAL
6794 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6795 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6796     if (hci_stack->le_past_set_default_params){
6797         hci_stack->le_past_set_default_params = false;
6798         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
6799                      hci_stack->le_past_mode,
6800                      hci_stack->le_past_skip,
6801                      hci_stack->le_past_sync_timeout,
6802                      hci_stack->le_past_cte_type);
6803         return true;
6804     }
6805 #endif
6806 #endif
6807 #endif
6808 
6809     // post-pone all actions until stack is fully working
6810     if (hci_stack->state != HCI_STATE_WORKING) return false;
6811 
6812     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6813     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6814 
6815     // Phase 4: restore state
6816 
6817 #ifdef ENABLE_LE_CENTRAL
6818     // re-start scanning
6819     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6820         hci_stack->le_scanning_active = true;
6821 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6822         if (hci_le_extended_advertising_supported()){
6823             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
6824         } else
6825 #endif
6826         {
6827             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
6828         }
6829         return true;
6830     }
6831 #endif
6832 
6833 #ifdef ENABLE_LE_CENTRAL
6834     // re-start connecting
6835     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6836         bd_addr_t null_addr;
6837         memset(null_addr, 0, 6);
6838         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6839         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6840         hci_send_le_create_connection(1, 0, null_addr);
6841         return true;
6842     }
6843 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6844     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6845         switch(hci_stack->le_periodic_sync_request){
6846             case LE_CONNECTING_DIRECT:
6847             case LE_CONNECTING_WHITELIST:
6848                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6849                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6850                              hci_stack->le_periodic_sync_options,
6851                              hci_stack->le_periodic_sync_advertising_sid,
6852                              hci_stack->le_periodic_sync_advertiser_address_type,
6853                              hci_stack->le_periodic_sync_advertiser_address,
6854                              hci_stack->le_periodic_sync_skip,
6855                              hci_stack->le_periodic_sync_timeout,
6856                              hci_stack->le_periodic_sync_cte_type);
6857                 return true;
6858             default:
6859                 break;
6860         }
6861     }
6862 #endif
6863 #endif
6864 
6865 #ifdef ENABLE_LE_PERIPHERAL
6866     // re-start advertising
6867     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6868         // check if advertisements should be enabled given
6869         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6870         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6871 
6872 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6873         if (hci_le_extended_advertising_supported()){
6874             const uint8_t advertising_handles[] = { 0 };
6875             const uint16_t durations[] = { 0 };
6876             const uint16_t max_events[] = { 0 };
6877             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6878         } else
6879 #endif
6880         {
6881             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6882         }
6883         return true;
6884     }
6885 
6886 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6887     if (hci_le_extended_advertising_supported()) {
6888         btstack_linked_list_iterator_t it;
6889         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6890         while (btstack_linked_list_iterator_has_next(&it)) {
6891             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6892             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6893                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6894                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6895                 const uint16_t durations[] = { advertising_set->enable_timeout };
6896                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6897                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6898                 return true;
6899             }
6900 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6901             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6902                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6903                 uint8_t enable = 1;
6904                 if (advertising_set->periodic_include_adi){
6905                     enable |= 2;
6906                 }
6907                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6908                 return true;
6909             }
6910 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6911         }
6912     }
6913 #endif
6914 #endif
6915 
6916     return false;
6917 }
6918 
6919 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6920 static bool hci_run_iso_tasks(void){
6921     btstack_linked_list_iterator_t it;
6922 
6923     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
6924         return false;
6925     }
6926 
6927     // BIG
6928     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6929     while (btstack_linked_list_iterator_has_next(&it)){
6930         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6931         switch (big->state){
6932             case LE_AUDIO_BIG_STATE_CREATE:
6933                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
6934                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6935                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6936                 hci_send_cmd(&hci_le_create_big,
6937                              big->params->big_handle,
6938                              big->params->advertising_handle,
6939                              big->params->num_bis,
6940                              big->params->sdu_interval_us,
6941                              big->params->max_sdu,
6942                              big->params->max_transport_latency_ms,
6943                              big->params->rtn,
6944                              big->params->phy,
6945                              big->params->packing,
6946                              big->params->framing,
6947                              big->params->encryption,
6948                              big->params->broadcast_code);
6949                 return true;
6950             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6951                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6952                 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);
6953                 return true;
6954             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6955                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6956                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6957                 return true;
6958             case LE_AUDIO_BIG_STATE_TERMINATE:
6959                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6960                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6961                 return true;
6962             default:
6963                 break;
6964         }
6965     }
6966 
6967     // BIG Sync
6968     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6969     while (btstack_linked_list_iterator_has_next(&it)){
6970         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6971         switch (big_sync->state){
6972             case LE_AUDIO_BIG_STATE_CREATE:
6973                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
6974                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6975                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6976                 hci_send_cmd(&hci_le_big_create_sync,
6977                              big_sync->params->big_handle,
6978                              big_sync->params->sync_handle,
6979                              big_sync->params->encryption,
6980                              big_sync->params->broadcast_code,
6981                              big_sync->params->mse,
6982                              big_sync->params->big_sync_timeout_10ms,
6983                              big_sync->params->num_bis,
6984                              big_sync->params->bis_indices);
6985                 return true;
6986             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6987                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6988                 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);
6989                 return true;
6990             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6991                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6992                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6993                 return true;
6994             case LE_AUDIO_BIG_STATE_TERMINATE:
6995                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6996                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6997                 return true;
6998             default:
6999                 break;
7000         }
7001     }
7002 
7003     // CIG
7004     bool cig_active;
7005     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
7006     while (btstack_linked_list_iterator_has_next(&it)) {
7007         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
7008         uint8_t i;
7009         // Set CIG Parameters
7010         uint8_t cis_id[MAX_NR_CIS];
7011         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
7012         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
7013         uint8_t phy_c_to_p[MAX_NR_CIS];
7014         uint8_t phy_p_to_c[MAX_NR_CIS];
7015         uint8_t rtn_c_to_p[MAX_NR_CIS];
7016         uint8_t rtn_p_to_c[MAX_NR_CIS];
7017         switch (cig->state) {
7018             case LE_AUDIO_CIG_STATE_CREATE:
7019                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7020                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7021                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
7022                 le_audio_cig_params_t * params = cig->params;
7023                 for (i = 0; i < params->num_cis; i++) {
7024                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
7025                     cis_id[i]         = cis_params->cis_id;
7026                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
7027                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
7028                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
7029                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
7030                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
7031                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
7032                 }
7033                 hci_send_cmd(&hci_le_set_cig_parameters,
7034                              cig->cig_id,
7035                              params->sdu_interval_c_to_p,
7036                              params->sdu_interval_p_to_c,
7037                              params->worst_case_sca,
7038                              params->packing,
7039                              params->framing,
7040                              params->max_transport_latency_c_to_p,
7041                              params->max_transport_latency_p_to_c,
7042                              params->num_cis,
7043                              cis_id,
7044                              max_sdu_c_to_p,
7045                              max_sdu_p_to_c,
7046                              phy_c_to_p,
7047                              phy_p_to_c,
7048                              rtn_c_to_p,
7049                              rtn_p_to_c
7050                 );
7051                 return true;
7052             case LE_AUDIO_CIG_STATE_CREATE_CIS:
7053                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7054                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7055                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
7056                 for (i=0;i<cig->num_cis;i++){
7057                     cig->cis_setup_active[i] = true;
7058                 }
7059                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
7060                 return true;
7061             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
7062                 while (cig->state_vars.next_cis < (cig->num_cis * 2)){
7063                     // find next path to setup
7064                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
7065                     if (cig->cis_established[cis_index] == false) {
7066                         continue;
7067                     }
7068                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
7069                     bool setup = true;
7070                     if (cis_direction == 0){
7071                         // 0 - input - host to controller
7072                         // we are central => central to peripheral
7073                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
7074                     } else {
7075                         // 1 - output - controller to host
7076                         // we are central => peripheral to central
7077                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
7078                     }
7079                     if (setup){
7080                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7081                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7082                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
7083                         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);
7084                         return true;
7085                     }
7086                     cig->state_vars.next_cis++;
7087                 }
7088                 // emit done
7089                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
7090                 break;
7091             case LE_AUDIO_CIG_STATE_REMOVE:
7092                 // check if CIG Active
7093                 cig_active = false;
7094                 for (i = 0; i < cig->num_cis; i++) {
7095                     if (cig->cis_con_handles[i] != HCI_CON_HANDLE_INVALID){
7096                         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
7097                         if (stream != NULL){
7098                             cig_active = true;
7099                             break;
7100                         }
7101                     }
7102                 }
7103                 if (cig_active == false){
7104                     btstack_linked_list_iterator_remove(&it);
7105                     hci_send_cmd(&hci_le_remove_cig, cig->cig_id);
7106                     return true;
7107                 }
7108             default:
7109                 break;
7110         }
7111     }
7112 
7113     // CIS Accept/Reject/Setup ISO Path/Close
7114     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
7115     while (btstack_linked_list_iterator_has_next(&it)) {
7116         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
7117         hci_con_handle_t con_handle;
7118         switch (iso_stream->state){
7119             case HCI_ISO_STREAM_W2_ACCEPT:
7120                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
7121                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7122                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7123                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->cis_handle);
7124                 return true;
7125             case HCI_ISO_STREAM_W2_REJECT:
7126                 con_handle = iso_stream->cis_handle;
7127                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7128                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7129                 hci_iso_stream_finalize(iso_stream);
7130                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
7131                 return true;
7132             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
7133                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7134                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7135                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
7136                 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);
7137                 break;
7138             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
7139                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7140                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7141                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT;
7142                 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);
7143                 break;
7144             case HCI_ISO_STREAM_STATE_W2_CLOSE:
7145                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_DISCONNECTED;
7146                 hci_send_cmd(&hci_disconnect, iso_stream->cis_handle);
7147                 break;
7148             default:
7149                 break;
7150         }
7151     }
7152 
7153     return false;
7154 }
7155 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
7156 #endif
7157 
7158 static bool hci_run_general_pending_commands(void){
7159     btstack_linked_item_t * it;
7160     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7161         hci_connection_t * connection = (hci_connection_t *) it;
7162 
7163         switch(connection->state){
7164             case SEND_CREATE_CONNECTION:
7165                 switch(connection->address_type){
7166 #ifdef ENABLE_CLASSIC
7167                     case BD_ADDR_TYPE_ACL:
7168                         log_info("sending hci_create_connection");
7169                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
7170                         break;
7171 #endif
7172                     default:
7173 #ifdef ENABLE_BLE
7174 #ifdef ENABLE_LE_CENTRAL
7175                         log_info("sending hci_le_create_connection");
7176                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
7177                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
7178                         hci_send_le_create_connection(0, connection->address_type, connection->address);
7179                         connection->state = SENT_CREATE_CONNECTION;
7180 #endif
7181 #endif
7182                         break;
7183                 }
7184                 return true;
7185 
7186 #ifdef ENABLE_CLASSIC
7187             case RECEIVED_CONNECTION_REQUEST:
7188                 if (connection->address_type == BD_ADDR_TYPE_ACL){
7189                     log_info("sending hci_accept_connection_request");
7190                     connection->state = ACCEPTED_CONNECTION_REQUEST;
7191                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
7192                     return true;
7193                 }
7194                 break;
7195 #endif
7196             case SEND_DISCONNECT:
7197                 connection->state = SENT_DISCONNECT;
7198                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7199                 return true;
7200 
7201             default:
7202                 break;
7203         }
7204 
7205         // no further commands if connection is about to get shut down
7206         if (connection->state == SENT_DISCONNECT) continue;
7207 
7208 #ifdef ENABLE_CLASSIC
7209 
7210         // Handling link key request requires remote supported features
7211         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
7212             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
7213             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
7214 
7215             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
7216             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
7217             if (have_link_key && security_level_sufficient){
7218                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
7219             } else {
7220                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
7221             }
7222             return true;
7223         }
7224 
7225         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
7226             log_info("denying to pin request");
7227             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
7228             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
7229             return true;
7230         }
7231 
7232         // security assessment requires remote features
7233         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
7234             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
7235             hci_ssp_assess_security_on_io_cap_request(connection);
7236             // 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
7237         }
7238 
7239         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
7240             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7241             // set authentication requirements:
7242             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
7243             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
7244             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
7245             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
7246                 authreq |= 1;
7247             }
7248             bool bonding = hci_stack->bondable;
7249             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
7250                 // if we have received IO Cap Response, we're in responder role
7251                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7252                 if (bonding && !remote_bonding){
7253                     log_info("Remote not bonding, dropping local flag");
7254                     bonding = false;
7255                 }
7256             }
7257             if (bonding){
7258                 if (connection->bonding_flags & BONDING_DEDICATED){
7259                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7260                 } else {
7261                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
7262                 }
7263             }
7264             uint8_t have_oob_data = 0;
7265 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7266             if (connection->classic_oob_c_192 != NULL){
7267                     have_oob_data |= 1;
7268             }
7269             if (connection->classic_oob_c_256 != NULL){
7270                 have_oob_data |= 2;
7271             }
7272 #endif
7273             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
7274             return true;
7275         }
7276 
7277         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
7278             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
7279             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
7280             return true;
7281         }
7282 
7283 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7284         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
7285             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
7286             const uint8_t zero[16] = { 0 };
7287             const uint8_t * r_192 = zero;
7288             const uint8_t * c_192 = zero;
7289             const uint8_t * r_256 = zero;
7290             const uint8_t * c_256 = zero;
7291             // verify P-256 OOB
7292             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
7293                 c_256 = connection->classic_oob_c_256;
7294                 if (connection->classic_oob_r_256 != NULL) {
7295                     r_256 = connection->classic_oob_r_256;
7296                 }
7297             }
7298             // verify P-192 OOB
7299             if ((connection->classic_oob_c_192 != NULL)) {
7300                 c_192 = connection->classic_oob_c_192;
7301                 if (connection->classic_oob_r_192 != NULL) {
7302                     r_192 = connection->classic_oob_r_192;
7303                 }
7304             }
7305 
7306             // assess security
7307             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
7308             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
7309             if (need_level_4 && !can_reach_level_4){
7310                 log_info("Level 4 required, but not possible -> abort");
7311                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
7312                 // send oob negative reply
7313                 c_256 = NULL;
7314                 c_192 = NULL;
7315             }
7316 
7317             // Reply
7318             if (c_256 != zero) {
7319                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
7320             } else if (c_192 != zero){
7321                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
7322             } else {
7323                 hci_stack->classic_oob_con_handle = connection->con_handle;
7324                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
7325             }
7326             return true;
7327         }
7328 #endif
7329 
7330         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
7331             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
7332             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
7333             return true;
7334         }
7335 
7336         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
7337             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
7338             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
7339             return true;
7340         }
7341 
7342         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
7343             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
7344             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
7345             return true;
7346         }
7347 
7348         if ((connection->bonding_flags & (BONDING_DISCONNECT_DEDICATED_DONE | BONDING_DEDICATED_DEFER_DISCONNECT)) == BONDING_DISCONNECT_DEDICATED_DONE){
7349             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
7350             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
7351             connection->state = SENT_DISCONNECT;
7352             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7353             return true;
7354         }
7355 
7356         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
7357             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
7358             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
7359             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
7360             return true;
7361         }
7362 
7363         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
7364             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
7365             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
7366             return true;
7367         }
7368 
7369         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
7370             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
7371             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
7372             return true;
7373         }
7374 
7375         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
7376             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7377             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
7378             return true;
7379         }
7380 
7381         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
7382             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
7383             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
7384             return true;
7385         }
7386 
7387         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
7388             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
7389             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
7390             return true;
7391         }
7392 #endif
7393 
7394         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
7395             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
7396 #ifdef ENABLE_CLASSIC
7397             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
7398 #endif
7399             if (connection->state != SENT_DISCONNECT){
7400                 connection->state = SENT_DISCONNECT;
7401                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
7402                 return true;
7403             }
7404         }
7405 
7406 #ifdef ENABLE_CLASSIC
7407         uint16_t sniff_min_interval;
7408         switch (connection->sniff_min_interval){
7409             case 0:
7410                 break;
7411             case 0xffff:
7412                 connection->sniff_min_interval = 0;
7413                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
7414                 return true;
7415             default:
7416                 sniff_min_interval = connection->sniff_min_interval;
7417                 connection->sniff_min_interval = 0;
7418                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
7419                 return true;
7420         }
7421 
7422         if (connection->sniff_subrating_max_latency != 0xffff){
7423             uint16_t max_latency = connection->sniff_subrating_max_latency;
7424             connection->sniff_subrating_max_latency = 0;
7425             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
7426             return true;
7427         }
7428 
7429         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
7430             uint8_t service_type = (uint8_t) connection->qos_service_type;
7431             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
7432             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);
7433             return true;
7434         }
7435 
7436         if (connection->request_role != HCI_ROLE_INVALID){
7437             hci_role_t role = connection->request_role;
7438             connection->request_role = HCI_ROLE_INVALID;
7439             hci_send_cmd(&hci_switch_role_command, connection->address, role);
7440             return true;
7441         }
7442 #endif
7443 
7444         if (connection->gap_connection_tasks != 0){
7445 #ifdef ENABLE_CLASSIC
7446             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
7447                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
7448                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
7449                 return true;
7450             }
7451             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
7452                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
7453                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
7454                 return true;
7455             }
7456 #endif
7457             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
7458                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
7459                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
7460                 return true;
7461             }
7462 #ifdef ENABLE_BLE
7463             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
7464                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
7465                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
7466                 return true;
7467             }
7468 #endif
7469         }
7470 
7471 #ifdef ENABLE_BLE
7472         switch (connection->le_con_parameter_update_state){
7473             // response to L2CAP CON PARAMETER UPDATE REQUEST
7474             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
7475                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7476                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
7477                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7478                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7479                 return true;
7480             case CON_PARAMETER_UPDATE_REPLY:
7481                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7482                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
7483                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7484                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7485                 return true;
7486             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
7487                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7488                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
7489                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
7490                 return true;
7491             default:
7492                 break;
7493         }
7494         if (connection->le_phy_update_all_phys != 0xffu){
7495             uint8_t all_phys = connection->le_phy_update_all_phys;
7496             connection->le_phy_update_all_phys = 0xff;
7497             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);
7498             return true;
7499         }
7500 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7501         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
7502             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
7503             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
7504             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
7505             return true;
7506         }
7507         if (connection->le_past_advertising_handle != 0xff){
7508             uint8_t advertising_handle = connection->le_past_advertising_handle;
7509             connection->le_past_advertising_handle = 0xff;
7510             hci_send_cmd(&hci_le_periodic_advertising_set_info_transfer, connection->con_handle, connection->le_past_service_data, advertising_handle);
7511             return true;
7512         }
7513 #endif
7514 #endif
7515     }
7516     return false;
7517 }
7518 
7519 static void hci_run(void){
7520 
7521     // stack state sub statemachines
7522     switch (hci_stack->state) {
7523         case HCI_STATE_INITIALIZING:
7524             hci_initializing_run();
7525             break;
7526         case HCI_STATE_HALTING:
7527             hci_halting_run();
7528             break;
7529         case HCI_STATE_FALLING_ASLEEP:
7530             hci_falling_asleep_run();
7531             break;
7532         default:
7533             break;
7534     }
7535 
7536     // allow to run after initialization to working transition
7537     if (hci_stack->state != HCI_STATE_WORKING){
7538         return;
7539     }
7540 
7541     bool done;
7542 
7543     // send continuation fragments first, as they block the prepared packet buffer
7544     done = hci_run_acl_fragments();
7545     if (done) return;
7546 
7547 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7548     done = hci_run_iso_fragments();
7549     if (done) return;
7550 #endif
7551 
7552 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7553     // send host num completed packets next as they don't require num_cmd_packets > 0
7554     if (!hci_can_send_comand_packet_transport()) return;
7555     if (hci_stack->host_completed_packets){
7556         hci_host_num_completed_packets();
7557         return;
7558     }
7559 #endif
7560 
7561     if (!hci_can_send_command_packet_now()) return;
7562 
7563     // global/non-connection oriented commands
7564 
7565 
7566 #ifdef ENABLE_CLASSIC
7567     // general gap classic
7568     done = hci_run_general_gap_classic();
7569     if (done) return;
7570 #endif
7571 
7572 #ifdef ENABLE_BLE
7573     // general gap le
7574     done = hci_run_general_gap_le();
7575     if (done) return;
7576 
7577 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7578     // ISO related tasks, e.g. BIG create/terminate/sync
7579     done = hci_run_iso_tasks();
7580     if (done) return;
7581 #endif
7582 #endif
7583 
7584     // send pending HCI commands
7585     hci_run_general_pending_commands();
7586 }
7587 
7588 #ifdef ENABLE_CLASSIC
7589 static void hci_set_sco_payload_length_for_flipped_packet_types(hci_connection_t * hci_connection, uint16_t flipped_packet_types){
7590     // bits 6-9 are 'don't use'
7591     uint16_t packet_types = flipped_packet_types ^ 0x03c0;
7592 
7593     // restrict packet types to local and remote supported
7594     packet_types &= hci_connection->remote_supported_sco_packets & hci_stack->usable_packet_types_sco;
7595     hci_connection->sco_payload_length = hci_sco_payload_length_for_packet_types(packet_types);
7596     log_info("Possible SCO packet types 0x%04x => payload length %u", packet_types, hci_connection->sco_payload_length);
7597 }
7598 #endif
7599 
7600 // funnel for sending cmd packet using single outgoing buffer
7601 static uint8_t hci_send_prepared_cmd_packet(void) {
7602     btstack_assert(hci_stack->hci_packet_buffer_reserved);
7603     // cache opcode
7604     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
7605     // get size
7606     uint16_t size = 3u + hci_stack->hci_packet_buffer[2u];
7607     // send packet
7608     uint8_t status = hci_send_cmd_packet(hci_stack->hci_packet_buffer, size);
7609     // release packet buffer on error or for synchronous transport implementations
7610     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7611         hci_release_packet_buffer();
7612     }
7613     return status;
7614 }
7615 
7616 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
7617     // house-keeping
7618 
7619 #ifdef ENABLE_CLASSIC
7620     bd_addr_t addr;
7621     hci_connection_t * conn;
7622 #endif
7623 #ifdef ENABLE_LE_CENTRAL
7624     uint8_t initiator_filter_policy;
7625 #endif
7626 
7627     uint16_t opcode = little_endian_read_16(packet, 0);
7628     switch (opcode) {
7629         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
7630             hci_stack->loopback_mode = packet[3];
7631             break;
7632 
7633 #ifdef ENABLE_CLASSIC
7634         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7635             reverse_bd_addr(&packet[3], addr);
7636             log_info("Create_connection to %s", bd_addr_to_str(addr));
7637 
7638             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
7639             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
7640                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
7641                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
7642             }
7643 
7644             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7645             if (!conn) {
7646                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
7647                 if (!conn) {
7648                     // notify client that alloc failed
7649                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7650                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
7651                 }
7652                 conn->state = SEND_CREATE_CONNECTION;
7653             }
7654 
7655             log_info("conn state %u", conn->state);
7656             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7657             switch (conn->state) {
7658                 // if connection active exists
7659                 case OPEN:
7660                     // and OPEN, emit connection complete command
7661                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
7662                     // packet not sent to controller
7663                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7664                 case RECEIVED_DISCONNECTION_COMPLETE:
7665                     // create connection triggered in disconnect complete event, let's do it now
7666                     break;
7667                 case SEND_CREATE_CONNECTION:
7668 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
7669                     if (hci_classic_operation_active()){
7670                         return ERROR_CODE_SUCCESS;
7671                     }
7672 #endif
7673                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7674                     break;
7675                 default:
7676                     // otherwise, just ignore as it is already in the open process
7677                     // packet not sent to controller
7678                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7679             }
7680             conn->state = SENT_CREATE_CONNECTION;
7681 
7682             // track outgoing connection
7683             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
7684             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7685             break;
7686 
7687         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
7688             conn = hci_connection_for_handle(little_endian_read_16(packet, 3));
7689             if (conn == NULL) {
7690                 // neither SCO nor ACL connection for con handle
7691                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7692             } else {
7693                 uint16_t remote_supported_sco_packets;
7694                 switch (conn->address_type){
7695                     case BD_ADDR_TYPE_ACL:
7696                         // assert SCO connection does not exit
7697                         if (hci_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO) != NULL){
7698                             return ERROR_CODE_COMMAND_DISALLOWED;
7699                         }
7700                         // cache remote sco packet types
7701                         remote_supported_sco_packets = conn->remote_supported_sco_packets;
7702 
7703                         // allocate connection struct
7704                         conn = create_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO,
7705                                                                       HCI_ROLE_MASTER);
7706                         if (!conn) {
7707                             return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7708                         }
7709                         conn->remote_supported_sco_packets = remote_supported_sco_packets;
7710                         break;
7711                     case BD_ADDR_TYPE_SCO:
7712                         // update of existing SCO connection
7713                         break;
7714                     default:
7715                         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7716                 }
7717             }
7718 
7719             // conn refers to hci connection of type sco now
7720 
7721             conn->state = SENT_CREATE_CONNECTION;
7722 
7723             // track outgoing connection to handle command status with error
7724             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7725             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7726 
7727             // setup_synchronous_connection? Voice setting at offset 22
7728             // TODO: compare to current setting if sco connection already active
7729             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7730 
7731             // derive sco payload length from packet types
7732             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 18));
7733             break;
7734 
7735         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
7736             // get SCO connection
7737             reverse_bd_addr(&packet[3], addr);
7738             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
7739             if (conn == NULL){
7740                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7741             }
7742 
7743             conn->state = ACCEPTED_CONNECTION_REQUEST;
7744 
7745             // track outgoing connection to handle command status with error
7746             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7747             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7748 
7749             // accept_synchronous_connection? Voice setting at offset 18
7750             // TODO: compare to current setting if sco connection already active
7751             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7752 
7753             // derive sco payload length from packet types
7754             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 22));
7755             break;
7756 #endif
7757 
7758 #ifdef ENABLE_BLE
7759 #ifdef ENABLE_LE_CENTRAL
7760         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7761             // white list used?
7762             initiator_filter_policy = packet[7];
7763             switch (initiator_filter_policy) {
7764                 case 0:
7765                     // whitelist not used
7766                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7767                     break;
7768                 case 1:
7769                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7770                     break;
7771                 default:
7772                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7773                     break;
7774             }
7775             // track outgoing connection
7776             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer address type
7777             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
7778             break;
7779 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7780         case HCI_OPCODE_HCI_LE_EXTENDED_CREATE_CONNECTION:
7781             // white list used?
7782             initiator_filter_policy = packet[3];
7783             switch (initiator_filter_policy) {
7784                 case 0:
7785                     // whitelist not used
7786                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7787                     break;
7788                 case 1:
7789                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7790                     break;
7791                 default:
7792                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7793                     break;
7794             }
7795             // track outgoing connection
7796             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[5]; // peer address type
7797             reverse_bd_addr( &packet[6], hci_stack->outgoing_addr); // peer address
7798             break;
7799 #endif
7800         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
7801             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
7802             break;
7803 #endif
7804 #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
7805         case HCI_OPCODE_HCI_LE_CONNECTION_UPDATE:
7806         case HCI_OPCODE_HCI_LE_READ_REMOTE_USED_FEATURES:
7807         case HCI_OPCODE_HCI_LE_START_ENCRYPTION:
7808         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_REQUEST_REPLY:
7809         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_NEGATIVE_REPLY:
7810         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY:
7811         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY:
7812         case HCI_OPCODE_HCI_LE_SET_DATA_LENGTH:
7813         case HCI_OPCODE_HCI_LE_READ_PHY:
7814         case HCI_OPCODE_HCI_LE_SET_PHY:
7815             // conection handle is first command parameter
7816             hci_stack->hci_command_con_handle = little_endian_read_16(packet, 3);
7817             break;
7818 #endif
7819 #endif /* ENABLE_BLE */
7820         default:
7821             break;
7822     }
7823 
7824     hci_stack->num_cmd_packets--;
7825 
7826     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
7827     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7828     uint8_t status;
7829     if (err == 0){
7830         status = ERROR_CODE_SUCCESS;
7831     } else {
7832         status = ERROR_CODE_HARDWARE_FAILURE;
7833     }
7834     return status;
7835 }
7836 
7837 // disconnect because of security block
7838 void hci_disconnect_security_block(hci_con_handle_t con_handle){
7839     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7840     if (!connection) return;
7841     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
7842 }
7843 
7844 
7845 // Configure Secure Simple Pairing
7846 
7847 #ifdef ENABLE_CLASSIC
7848 
7849 // enable will enable SSP during init
7850 void gap_ssp_set_enable(int enable){
7851     hci_stack->ssp_enable = enable;
7852 }
7853 
7854 static int hci_local_ssp_activated(void){
7855     return gap_ssp_supported() && hci_stack->ssp_enable;
7856 }
7857 
7858 // if set, BTstack will respond to io capability request using authentication requirement
7859 void gap_ssp_set_io_capability(int io_capability){
7860     hci_stack->ssp_io_capability = io_capability;
7861 }
7862 void gap_ssp_set_authentication_requirement(int authentication_requirement){
7863     hci_stack->ssp_authentication_requirement = authentication_requirement;
7864 }
7865 
7866 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
7867 void gap_ssp_set_auto_accept(int auto_accept){
7868     hci_stack->ssp_auto_accept = auto_accept;
7869 }
7870 
7871 void gap_secure_connections_enable(bool enable){
7872     hci_stack->secure_connections_enable = enable;
7873 }
7874 bool gap_secure_connections_active(void){
7875     return hci_stack->secure_connections_active;
7876 }
7877 
7878 #endif
7879 
7880 // va_list part of hci_send_cmd
7881 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
7882     if (!hci_can_send_command_packet_now()){
7883         log_error("hci_send_cmd called but cannot send packet now");
7884         return ERROR_CODE_COMMAND_DISALLOWED;
7885     }
7886 
7887     hci_reserve_packet_buffer();
7888     hci_cmd_create_from_template(hci_stack->hci_packet_buffer, cmd, argptr);
7889     return hci_send_prepared_cmd_packet();
7890 }
7891 
7892 /**
7893  * pre: numcmds >= 0 - it's allowed to send a command to the controller
7894  */
7895 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
7896     va_list argptr;
7897     va_start(argptr, cmd);
7898     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
7899     va_end(argptr);
7900     return status;
7901 }
7902 
7903 // Create various non-HCI events.
7904 // TODO: generalize, use table similar to hci_create_command
7905 
7906 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
7907     // dump packet
7908     if (dump) {
7909         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
7910     }
7911 
7912     // dispatch to all event handlers
7913     btstack_linked_list_iterator_t it;
7914     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
7915     while (btstack_linked_list_iterator_has_next(&it)){
7916         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
7917         entry->callback(HCI_EVENT_PACKET, 0, event, size);
7918     }
7919 }
7920 
7921 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
7922     if (!hci_stack->acl_packet_handler) return;
7923     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
7924 }
7925 
7926 #ifdef ENABLE_CLASSIC
7927 static void hci_notify_if_sco_can_send_now(void){
7928     // notify SCO sender if waiting
7929     if (!hci_stack->sco_waiting_for_can_send_now) return;
7930     if (hci_can_send_sco_packet_now()){
7931         hci_stack->sco_waiting_for_can_send_now = 0;
7932         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
7933         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
7934         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
7935     }
7936 }
7937 
7938 // parsing end emitting has been merged to reduce code size
7939 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
7940     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
7941 
7942     uint8_t * eir_data;
7943     ad_context_t context;
7944     const uint8_t * name;
7945     uint8_t         name_len;
7946 
7947     if (size < 3) return;
7948 
7949     int event_type = hci_event_packet_get_type(packet);
7950     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
7951     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
7952 
7953     switch (event_type){
7954         case HCI_EVENT_INQUIRY_RESULT:
7955         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7956             if (size != (3 + (num_responses * 14))) return;
7957             break;
7958         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7959             if (size != 257) return;
7960             if (num_responses != 1) return;
7961             break;
7962         default:
7963             return;
7964     }
7965 
7966     // event[1] is set at the end
7967     int i;
7968     for (i=0; i<num_responses;i++){
7969         memset(event, 0, sizeof(event));
7970         event[0] = GAP_EVENT_INQUIRY_RESULT;
7971         uint8_t event_size = 27;    // if name is not set by EIR
7972 
7973         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
7974         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
7975         (void)memcpy(&event[9],
7976                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
7977                      3); // class of device
7978         (void)memcpy(&event[12],
7979                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
7980                      2); // clock offset
7981 
7982         switch (event_type){
7983             case HCI_EVENT_INQUIRY_RESULT:
7984                 // 14,15,16,17 = 0, size 18
7985                 break;
7986             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7987                 event[14] = 1;
7988                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7989                 // 16,17 = 0, size 18
7990                 break;
7991             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7992                 event[14] = 1;
7993                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7994                 // EIR packets only contain a single inquiry response
7995                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
7996                 name = NULL;
7997                 // Iterate over EIR data
7998                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
7999                     uint8_t data_type    = ad_iterator_get_data_type(&context);
8000                     uint8_t data_size    = ad_iterator_get_data_len(&context);
8001                     const uint8_t * data = ad_iterator_get_data(&context);
8002                     // Prefer Complete Local Name over Shortened Local Name
8003                     switch (data_type){
8004                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
8005                             if (name) continue;
8006                             /* fall through */
8007                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
8008                             name = data;
8009                             name_len = data_size;
8010                             break;
8011                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
8012                             if (data_size != 8) break;
8013                             event[16] = 1;
8014                             memcpy(&event[17], data, 8);
8015                             break;
8016                         default:
8017                             break;
8018                     }
8019                 }
8020                 if (name){
8021                     event[25] = 1;
8022                     // truncate name if needed
8023                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
8024                     event[26] = len;
8025                     (void)memcpy(&event[27], name, len);
8026                     event_size += len;
8027                 }
8028                 break;
8029             default:
8030                 return;
8031         }
8032         event[1] = event_size - 2;
8033         hci_emit_event(event, event_size, 1);
8034     }
8035 }
8036 #endif
8037 
8038 void hci_emit_state(void){
8039     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
8040     uint8_t event[3];
8041     event[0] = BTSTACK_EVENT_STATE;
8042     event[1] = sizeof(event) - 2u;
8043     event[2] = hci_stack->state;
8044     hci_emit_event(event, sizeof(event), 1);
8045 }
8046 
8047 #ifdef ENABLE_CLASSIC
8048 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
8049     uint8_t event[13];
8050     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
8051     event[1] = sizeof(event) - 2;
8052     event[2] = status;
8053     little_endian_store_16(event, 3, con_handle);
8054     reverse_bd_addr(address, &event[5]);
8055     event[11] = 1; // ACL connection
8056     event[12] = 0; // encryption disabled
8057     hci_emit_event(event, sizeof(event), 1);
8058 }
8059 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
8060     if (disable_l2cap_timeouts) return;
8061     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
8062     uint8_t event[4];
8063     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
8064     event[1] = sizeof(event) - 2;
8065     little_endian_store_16(event, 2, conn->con_handle);
8066     hci_emit_event(event, sizeof(event), 1);
8067 }
8068 #endif
8069 
8070 #ifdef ENABLE_BLE
8071 #ifdef ENABLE_LE_CENTRAL
8072 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){
8073     uint8_t hci_event[21];
8074     hci_event[0] = HCI_EVENT_LE_META;
8075     hci_event[1] = sizeof(hci_event) - 2u;
8076     hci_event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
8077     hci_event[3] = status;
8078     little_endian_store_16(hci_event, 4, con_handle);
8079     hci_event[6] = 0; // TODO: role
8080     hci_event[7] = address_type;
8081     reverse_bd_addr(address, &hci_event[8]);
8082     little_endian_store_16(hci_event, 14, 0); // interval
8083     little_endian_store_16(hci_event, 16, 0); // latency
8084     little_endian_store_16(hci_event, 18, 0); // supervision timeout
8085     hci_event[20] = 0; // master clock accuracy
8086     hci_emit_event(hci_event, sizeof(hci_event), 1);
8087     // emit GAP event, too
8088     uint8_t gap_event[36];
8089     hci_create_gap_connection_complete_event(hci_event, gap_event);
8090     hci_emit_event(gap_event, sizeof(gap_event), 1);
8091 }
8092 #endif
8093 #endif
8094 
8095 static void hci_emit_transport_packet_sent(void){
8096     // notify upper stack that it might be possible to send again
8097     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
8098     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
8099 }
8100 
8101 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
8102     uint8_t event[6];
8103     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
8104     event[1] = sizeof(event) - 2u;
8105     event[2] = 0; // status = OK
8106     little_endian_store_16(event, 3, con_handle);
8107     event[5] = reason;
8108     hci_emit_event(event, sizeof(event), 1);
8109 }
8110 
8111 static void hci_emit_nr_connections_changed(void){
8112     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
8113     uint8_t event[3];
8114     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
8115     event[1] = sizeof(event) - 2u;
8116     event[2] = nr_hci_connections();
8117     hci_emit_event(event, sizeof(event), 1);
8118 }
8119 
8120 static void hci_emit_hci_open_failed(void){
8121     log_info("BTSTACK_EVENT_POWERON_FAILED");
8122     uint8_t event[2];
8123     event[0] = BTSTACK_EVENT_POWERON_FAILED;
8124     event[1] = sizeof(event) - 2u;
8125     hci_emit_event(event, sizeof(event), 1);
8126 }
8127 
8128 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
8129     log_info("hci_emit_dedicated_bonding_result %u ", status);
8130     uint8_t event[9];
8131     int pos = 0;
8132     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
8133     event[pos++] = sizeof(event) - 2u;
8134     event[pos++] = status;
8135     reverse_bd_addr(address, &event[pos]);
8136     hci_emit_event(event, sizeof(event), 1);
8137 }
8138 
8139 
8140 #ifdef ENABLE_CLASSIC
8141 
8142 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
8143     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
8144     uint8_t event[5];
8145     int pos = 0;
8146     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
8147     event[pos++] = sizeof(event) - 2;
8148     little_endian_store_16(event, 2, con_handle);
8149     pos += 2;
8150     event[pos++] = level;
8151     hci_emit_event(event, sizeof(event), 1);
8152 }
8153 
8154 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
8155     if (!connection) return LEVEL_0;
8156     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
8157     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
8158     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
8159     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
8160     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
8161     // LEVEL 4 always requires 128 bit encrytion key size
8162     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
8163         security_level = LEVEL_3;
8164     }
8165     return security_level;
8166 }
8167 
8168 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
8169     uint8_t event[4];
8170     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
8171     event[1] = sizeof(event) - 2;
8172     event[2] = discoverable;
8173     event[3] = connectable;
8174     hci_emit_event(event, sizeof(event), 1);
8175 }
8176 
8177 // query if remote side supports eSCO
8178 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
8179     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8180     if (!connection) return false;
8181     return (connection->remote_supported_features[0] & 1) != 0;
8182 }
8183 
8184 uint16_t hci_remote_sco_packet_types(hci_con_handle_t con_handle){
8185     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8186     if (!connection) return 0;
8187     return connection->remote_supported_sco_packets;
8188 }
8189 
8190 static bool hci_ssp_supported(hci_connection_t * connection){
8191     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
8192     return (connection->bonding_flags & mask) == mask;
8193 }
8194 
8195 // query if remote side supports SSP
8196 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
8197     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8198     if (!connection) return false;
8199     return hci_ssp_supported(connection) ? 1 : 0;
8200 }
8201 
8202 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
8203     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
8204 }
8205 
8206 /**
8207  * Check if remote supported features query has completed
8208  */
8209 bool hci_remote_features_available(hci_con_handle_t handle){
8210     hci_connection_t * connection = hci_connection_for_handle(handle);
8211     if (!connection) return false;
8212     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
8213 }
8214 
8215 /**
8216  * Trigger remote supported features query
8217  */
8218 
8219 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
8220     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
8221         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
8222     }
8223 }
8224 
8225 void hci_remote_features_query(hci_con_handle_t con_handle){
8226     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8227     if (!connection) return;
8228     hci_trigger_remote_features_for_connection(connection);
8229     hci_run();
8230 }
8231 
8232 // GAP API
8233 /**
8234  * @bbrief enable/disable bonding. default is enabled
8235  * @praram enabled
8236  */
8237 void gap_set_bondable_mode(int enable){
8238     hci_stack->bondable = enable ? 1 : 0;
8239 }
8240 /**
8241  * @brief Get bondable mode.
8242  * @return 1 if bondable
8243  */
8244 int gap_get_bondable_mode(void){
8245     return hci_stack->bondable;
8246 }
8247 
8248 /**
8249  * @brief map link keys to security levels
8250  */
8251 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
8252     switch (link_key_type){
8253         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8254             return LEVEL_4;
8255         case COMBINATION_KEY:
8256         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
8257             return LEVEL_3;
8258         default:
8259             return LEVEL_2;
8260     }
8261 }
8262 
8263 /**
8264  * @brief map link keys to secure connection yes/no
8265  */
8266 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
8267     switch (link_key_type){
8268         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8269         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8270             return true;
8271         default:
8272             return false;
8273     }
8274 }
8275 
8276 /**
8277  * @brief map link keys to authenticated
8278  */
8279 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
8280     switch (link_key_type){
8281         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
8282         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
8283             return true;
8284         default:
8285             return false;
8286     }
8287 }
8288 
8289 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
8290     log_info("gap_mitm_protection_required_for_security_level %u", level);
8291     return level > LEVEL_2;
8292 }
8293 
8294 /**
8295  * @brief get current security level
8296  */
8297 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
8298     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8299     if (!connection) return LEVEL_0;
8300     return gap_security_level_for_connection(connection);
8301 }
8302 
8303 /**
8304  * @brief request connection to device to
8305  * @result GAP_AUTHENTICATION_RESULT
8306  */
8307 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
8308     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8309     if (!connection){
8310         hci_emit_security_level(con_handle, LEVEL_0);
8311         return;
8312     }
8313 
8314     btstack_assert(hci_is_le_connection(connection) == false);
8315 
8316     // 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)
8317     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
8318     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
8319         requested_level = LEVEL_4;
8320     }
8321 
8322     gap_security_level_t current_level = gap_security_level(con_handle);
8323     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
8324         requested_level, connection->requested_security_level, current_level);
8325 
8326     // authentication active if authentication request was sent or planned level > 0
8327     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
8328     if (authentication_active){
8329         // authentication already active
8330         if (connection->requested_security_level < requested_level){
8331             // increase requested level as new level is higher
8332             // TODO: handle re-authentication when done
8333             connection->requested_security_level = requested_level;
8334         }
8335     } else {
8336         // no request active, notify if security sufficient
8337         if (requested_level <= current_level){
8338             hci_emit_security_level(con_handle, current_level);
8339             return;
8340         }
8341 
8342         // store request
8343         connection->requested_security_level = requested_level;
8344 
8345         // start to authenticate connection
8346         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
8347 
8348         // request remote features if not already active, also trigger hci_run
8349         hci_remote_features_query(con_handle);
8350     }
8351 }
8352 
8353 /**
8354  * @brief start dedicated bonding with device. disconnect after bonding
8355  * @param device
8356  * @param request MITM protection
8357  * @result GAP_DEDICATED_BONDING_COMPLETE
8358  */
8359 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
8360 
8361     // create connection state machine
8362     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
8363 
8364     if (!connection){
8365         return BTSTACK_MEMORY_ALLOC_FAILED;
8366     }
8367 
8368     // delete link key
8369     gap_drop_link_key_for_bd_addr(device);
8370 
8371     // configure LEVEL_2/3, dedicated bonding
8372     connection->state = SEND_CREATE_CONNECTION;
8373     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
8374     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
8375     connection->bonding_flags = BONDING_DEDICATED;
8376 
8377     hci_run();
8378 
8379     return 0;
8380 }
8381 
8382 uint8_t hci_dedicated_bonding_defer_disconnect(hci_con_handle_t con_handle, bool defer){
8383     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8384     if (connection == NULL){
8385         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8386     }
8387     if (defer){
8388         connection->bonding_flags |= BONDING_DEDICATED_DEFER_DISCONNECT;
8389     } else {
8390         connection->bonding_flags &= ~BONDING_DEDICATED_DEFER_DISCONNECT;
8391         // trigger disconnect
8392         hci_run();
8393     }
8394     return ERROR_CODE_SUCCESS;
8395 }
8396 
8397 void gap_set_local_name(const char * local_name){
8398     hci_stack->local_name = local_name;
8399     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
8400     // also update EIR if not set by user
8401     if (hci_stack->eir_data == NULL){
8402         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
8403     }
8404     hci_run();
8405 }
8406 #endif
8407 
8408 
8409 #ifdef ENABLE_BLE
8410 
8411 #ifdef ENABLE_LE_CENTRAL
8412 void gap_start_scan(void){
8413     hci_stack->le_scanning_enabled = true;
8414     hci_run();
8415 }
8416 
8417 void gap_stop_scan(void){
8418     hci_stack->le_scanning_enabled = false;
8419     hci_run();
8420 }
8421 
8422 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
8423     hci_stack->le_scan_type          = scan_type;
8424     hci_stack->le_scan_filter_policy = scanning_filter_policy;
8425     hci_stack->le_scan_interval      = scan_interval;
8426     hci_stack->le_scan_window        = scan_window;
8427     hci_stack->le_scanning_param_update = true;
8428     hci_run();
8429 }
8430 
8431 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
8432     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
8433 }
8434 
8435 void gap_set_scan_duplicate_filter(bool enabled){
8436     hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0;
8437 }
8438 
8439 void gap_set_scan_phys(uint8_t phys){
8440     // LE Coded and LE 1M PHY
8441     hci_stack->le_scan_phys = phys & 0x05;
8442 }
8443 
8444 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type) {
8445     // disallow le connection if outgoing already active
8446     if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8447         log_error("le connect already active");
8448         return ERROR_CODE_COMMAND_DISALLOWED;
8449     }
8450 
8451     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
8452     if (conn == NULL) {
8453         conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_MASTER);
8454         if (conn == false){
8455             // alloc failed
8456             log_info("gap_connect: failed to alloc hci_connection_t");
8457             return BTSTACK_MEMORY_ALLOC_FAILED;
8458         }
8459     } else {
8460         switch (conn->state) {
8461             case RECEIVED_DISCONNECTION_COMPLETE:
8462                 // connection was just disconnected, reset state and allow re-connect
8463                 conn->role = HCI_ROLE_MASTER;
8464                 break;
8465             default:
8466                 return ERROR_CODE_COMMAND_DISALLOWED;
8467         }
8468     }
8469 
8470     // set le connecting state
8471     if (hci_is_le_connection_type(addr_type)){
8472         hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
8473     }
8474 
8475     // trigger connect
8476     log_info("gap_connect: send create connection next");
8477     conn->state = SEND_CREATE_CONNECTION;
8478     hci_run();
8479     return ERROR_CODE_SUCCESS;
8480 }
8481 
8482 // @assumption: only a single outgoing LE Connection exists
8483 static hci_connection_t * gap_get_outgoing_le_connection(void){
8484     btstack_linked_item_t *it;
8485     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
8486         hci_connection_t * conn = (hci_connection_t *) it;
8487         if (hci_is_le_connection(conn)){
8488             switch (conn->state){
8489                 case SEND_CREATE_CONNECTION:
8490                 case SENT_CREATE_CONNECTION:
8491                     return conn;
8492                 default:
8493                     break;
8494             };
8495         }
8496     }
8497     return NULL;
8498 }
8499 
8500 uint8_t gap_connect_cancel(void){
8501     hci_connection_t * conn;
8502     switch (hci_stack->le_connecting_request){
8503         case LE_CONNECTING_IDLE:
8504             break;
8505         case LE_CONNECTING_WHITELIST:
8506             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8507             hci_run();
8508             break;
8509         case LE_CONNECTING_DIRECT:
8510             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8511             conn = gap_get_outgoing_le_connection();
8512             if (conn == NULL){
8513                 hci_run();
8514             } else {
8515                 switch (conn->state){
8516                     case SEND_CREATE_CONNECTION:
8517                         // skip sending create connection and emit event instead
8518                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
8519                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
8520                         btstack_memory_hci_connection_free( conn );
8521                         break;
8522                     case SENT_CREATE_CONNECTION:
8523                         // let hci_run_general_gap_le cancel outgoing connection
8524                         hci_run();
8525                         break;
8526                     default:
8527                         break;
8528                 }
8529             }
8530             break;
8531         default:
8532             btstack_unreachable();
8533             break;
8534     }
8535     return ERROR_CODE_SUCCESS;
8536 }
8537 
8538 /**
8539  * @brief Set connection parameters for outgoing connections
8540  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
8541  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
8542  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
8543  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
8544  * @param conn_latency, default: 4
8545  * @param supervision_timeout (unit: 10ms), default: 720 ms
8546  * @param min_ce_length (unit: 0.625ms), default: 10 ms
8547  * @param max_ce_length (unit: 0.625ms), default: 30 ms
8548  */
8549 
8550 void gap_set_connection_phys(uint8_t phys){
8551     // LE Coded, LE 1M, LE 2M PHY
8552     hci_stack->le_connection_phys = phys & 7;
8553 }
8554 
8555 #endif
8556 
8557 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
8558                                    uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
8559                                    uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
8560     hci_stack->le_connection_scan_interval = conn_scan_interval;
8561     hci_stack->le_connection_scan_window = conn_scan_window;
8562     hci_stack->le_connection_interval_min = conn_interval_min;
8563     hci_stack->le_connection_interval_max = conn_interval_max;
8564     hci_stack->le_connection_latency = conn_latency;
8565     hci_stack->le_supervision_timeout = supervision_timeout;
8566     hci_stack->le_minimum_ce_length = min_ce_length;
8567     hci_stack->le_maximum_ce_length = max_ce_length;
8568 }
8569 
8570 /**
8571  * @brief Updates the connection parameters for a given LE connection
8572  * @param handle
8573  * @param conn_interval_min (unit: 1.25ms)
8574  * @param conn_interval_max (unit: 1.25ms)
8575  * @param conn_latency
8576  * @param supervision_timeout (unit: 10ms)
8577  * @return 0 if ok
8578  */
8579 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8580     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8581     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8582     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8583     connection->le_conn_interval_min = conn_interval_min;
8584     connection->le_conn_interval_max = conn_interval_max;
8585     connection->le_conn_latency = conn_latency;
8586     connection->le_supervision_timeout = supervision_timeout;
8587     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
8588     hci_run();
8589     return 0;
8590 }
8591 
8592 /**
8593  * @brief Request an update of the connection parameter for a given LE connection
8594  * @param handle
8595  * @param conn_interval_min (unit: 1.25ms)
8596  * @param conn_interval_max (unit: 1.25ms)
8597  * @param conn_latency
8598  * @param supervision_timeout (unit: 10ms)
8599  * @return 0 if ok
8600  */
8601 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8602     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8603     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8604     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8605     connection->le_conn_interval_min = conn_interval_min;
8606     connection->le_conn_interval_max = conn_interval_max;
8607     connection->le_conn_latency = conn_latency;
8608     connection->le_supervision_timeout = supervision_timeout;
8609     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
8610     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
8611     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
8612     return 0;
8613 }
8614 
8615 #ifdef ENABLE_LE_PERIPHERAL
8616 
8617 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8618 static void hci_assert_advertisement_set_0_ready(void){
8619     // force advertising set creation for legacy LE Advertising
8620     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) == 0){
8621         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8622     }
8623 }
8624 #endif
8625 
8626 /**
8627  * @brief Set Advertisement Data
8628  * @param advertising_data_length
8629  * @param advertising_data (max 31 octets)
8630  * @note data is not copied, pointer has to stay valid
8631  */
8632 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
8633     hci_stack->le_advertisements_data_len = advertising_data_length;
8634     hci_stack->le_advertisements_data = advertising_data;
8635     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8636 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8637     hci_assert_advertisement_set_0_ready();
8638 #endif
8639     hci_run();
8640 }
8641 
8642 /**
8643  * @brief Set Scan Response 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_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
8649     hci_stack->le_scan_response_data_len = scan_response_data_length;
8650     hci_stack->le_scan_response_data = scan_response_data;
8651     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_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 Advertisement Parameters
8660  * @param adv_int_min
8661  * @param adv_int_max
8662  * @param adv_type
8663  * @param direct_address_type
8664  * @param direct_address
8665  * @param channel_map
8666  * @param filter_policy
8667  *
8668  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
8669  */
8670  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
8671     uint8_t direct_address_typ, bd_addr_t direct_address,
8672     uint8_t channel_map, uint8_t filter_policy) {
8673 
8674     hci_stack->le_advertisements_interval_min = adv_int_min;
8675     hci_stack->le_advertisements_interval_max = adv_int_max;
8676     hci_stack->le_advertisements_type = adv_type;
8677     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
8678     hci_stack->le_advertisements_channel_map = channel_map;
8679     hci_stack->le_advertisements_filter_policy = filter_policy;
8680     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
8681                  6);
8682 
8683     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8684     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
8685     hci_run();
8686  }
8687 
8688 /**
8689  * @brief Enable/Disable Advertisements
8690  * @param enabled
8691  */
8692 void gap_advertisements_enable(int enabled){
8693     if (enabled == 0){
8694         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8695     } else {
8696         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
8697     }
8698     hci_update_advertisements_enabled_for_current_roles();
8699     hci_run();
8700 }
8701 
8702 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8703 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
8704     btstack_linked_list_iterator_t it;
8705     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
8706     while (btstack_linked_list_iterator_has_next(&it)){
8707         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
8708         if ( item->advertising_handle == advertising_handle ) {
8709             return item;
8710         }
8711     }
8712     return NULL;
8713 }
8714 
8715 uint8_t gap_extended_advertising_set_resolvable_private_address_update(uint16_t update_s){
8716     hci_stack->le_resolvable_private_address_update_s = update_s;
8717     hci_run();
8718     return ERROR_CODE_SUCCESS;
8719 }
8720 
8721 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
8722     // find free advertisement handle
8723     uint8_t advertisement_handle;
8724     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
8725         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
8726     }
8727     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8728     // clear
8729     memset(storage, 0, sizeof(le_advertising_set_t));
8730     // copy params
8731     storage->advertising_handle = advertisement_handle;
8732     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8733     // add to list
8734     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
8735     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
8736     *out_advertising_handle = advertisement_handle;
8737     // set tasks and start
8738     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8739     hci_run();
8740     return ERROR_CODE_SUCCESS;
8741 }
8742 
8743 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
8744     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8745     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8746     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8747     // set tasks and start
8748     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8749     hci_run();
8750     return ERROR_CODE_SUCCESS;
8751 }
8752 
8753 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
8754     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8755     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8756     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
8757     return ERROR_CODE_SUCCESS;
8758 }
8759 
8760 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
8761     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8762     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8763     memcpy(advertising_set->random_address, random_address, 6);
8764     // set tasks and start
8765     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8766     hci_run();
8767     return ERROR_CODE_SUCCESS;
8768 }
8769 
8770 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
8771     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8772     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8773     advertising_set->adv_data = advertising_data;
8774     advertising_set->adv_data_len = advertising_data_length;
8775     // set tasks and start
8776     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8777     hci_run();
8778     return ERROR_CODE_SUCCESS;
8779 }
8780 
8781 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){
8782     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8783     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8784     advertising_set->scan_data = scan_response_data;
8785     advertising_set->scan_data_len = scan_response_data_length;
8786     // set tasks and start
8787     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8788     hci_run();
8789     return ERROR_CODE_SUCCESS;
8790 }
8791 
8792 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
8793     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8794     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8795     advertising_set->enable_timeout = timeout;
8796     advertising_set->enable_max_scan_events = num_extended_advertising_events;
8797     // set tasks and start
8798     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
8799     hci_run();
8800     return ERROR_CODE_SUCCESS;
8801 }
8802 
8803 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
8804     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8805     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8806     // set tasks and start
8807     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8808     hci_run();
8809     return ERROR_CODE_SUCCESS;
8810 }
8811 
8812 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8813     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8814     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8815     // set tasks and start
8816     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8817     hci_run();
8818     return ERROR_CODE_SUCCESS;
8819 }
8820 
8821 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8822 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8823     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8824     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8825     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8826     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8827     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8828     // set tasks and start
8829     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8830     hci_run();
8831     return ERROR_CODE_SUCCESS;
8832 }
8833 
8834 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8835     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8836     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8837     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8838     return ERROR_CODE_SUCCESS;
8839 }
8840 
8841 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8842     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8843     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8844     advertising_set->periodic_data = periodic_data;
8845     advertising_set->periodic_data_len = periodic_data_length;
8846     // set tasks and start
8847     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8848     hci_run();
8849     return ERROR_CODE_SUCCESS;
8850 }
8851 
8852 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
8853     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8854     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8855     // set tasks and start
8856     advertising_set->periodic_include_adi = include_adi;
8857     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8858     hci_run();
8859     return ERROR_CODE_SUCCESS;
8860 }
8861 
8862 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
8863     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8864     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8865     // set tasks and start
8866     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
8867     hci_run();
8868     return ERROR_CODE_SUCCESS;
8869 }
8870 
8871 uint8_t gap_periodic_advertising_sync_transfer_set_default_parameters(uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type){
8872     hci_stack->le_past_mode = mode;
8873     hci_stack->le_past_skip = skip;
8874     hci_stack->le_past_sync_timeout = sync_timeout;
8875     hci_stack->le_past_cte_type = cte_type;
8876     hci_stack->le_past_set_default_params = true;
8877     hci_run();
8878     return ERROR_CODE_SUCCESS;
8879 }
8880 
8881 uint8_t gap_periodic_advertising_sync_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, hci_con_handle_t sync_handle){
8882     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8883     if (hci_connection == NULL){
8884         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8885     }
8886     hci_connection->le_past_sync_handle = sync_handle;
8887     hci_connection->le_past_service_data = service_data;
8888     hci_run();
8889     return ERROR_CODE_SUCCESS;
8890 }
8891 
8892 uint8_t gap_periodic_advertising_set_info_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, uint8_t advertising_handle){
8893     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8894     if (hci_connection == NULL){
8895         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8896     }
8897     hci_connection->le_past_advertising_handle = advertising_handle;
8898     hci_connection->le_past_service_data = service_data;
8899     hci_run();
8900     return ERROR_CODE_SUCCESS;
8901 }
8902 
8903 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
8904 
8905 #endif
8906 
8907 #endif
8908 
8909 void hci_le_set_own_address_type(uint8_t own_address_type){
8910     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
8911     if (own_address_type == hci_stack->le_own_addr_type) return;
8912     hci_stack->le_own_addr_type = own_address_type;
8913 
8914 #ifdef ENABLE_LE_PERIPHERAL
8915     // update advertisement parameters, too
8916     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8917     hci_run();
8918 #endif
8919 #ifdef ENABLE_LE_CENTRAL
8920     // note: we don't update scan parameters or modify ongoing connection attempts
8921 #endif
8922 }
8923 
8924 void hci_le_random_address_set(const bd_addr_t random_address){
8925     log_info("gap_privacy: hci_le_random_address_set %s", bd_addr_to_str(random_address));
8926     memcpy(hci_stack->le_random_address, random_address, 6);
8927     hci_stack->le_random_address_set = true;
8928     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
8929 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8930     if (hci_le_extended_advertising_supported()){
8931         hci_assert_advertisement_set_0_ready();
8932         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
8933     }
8934 #endif
8935     hci_run();
8936 }
8937 
8938 #endif
8939 
8940 uint8_t gap_disconnect(hci_con_handle_t handle){
8941     hci_connection_t * conn = hci_connection_for_handle(handle);
8942     if (!conn){
8943         hci_emit_disconnection_complete(handle, 0);
8944         return 0;
8945     }
8946     // ignore if already disconnected
8947     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
8948         return 0;
8949     }
8950     conn->state = SEND_DISCONNECT;
8951     hci_run();
8952     return 0;
8953 }
8954 
8955 int gap_read_rssi(hci_con_handle_t con_handle){
8956     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8957     if (hci_connection == NULL) return 0;
8958     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
8959     hci_run();
8960     return 1;
8961 }
8962 
8963 /**
8964  * @brief Get connection type
8965  * @param con_handle
8966  * @result connection_type
8967  */
8968 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
8969     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8970     if (!conn) return GAP_CONNECTION_INVALID;
8971     switch (conn->address_type){
8972         case BD_ADDR_TYPE_LE_PUBLIC:
8973         case BD_ADDR_TYPE_LE_RANDOM:
8974         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
8975         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
8976             return GAP_CONNECTION_LE;
8977         case BD_ADDR_TYPE_SCO:
8978             return GAP_CONNECTION_SCO;
8979         case BD_ADDR_TYPE_ACL:
8980             return GAP_CONNECTION_ACL;
8981         default:
8982             return GAP_CONNECTION_INVALID;
8983     }
8984 }
8985 
8986 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
8987     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8988     if (!conn) return HCI_ROLE_INVALID;
8989     return (hci_role_t) conn->role;
8990 }
8991 
8992 
8993 #ifdef ENABLE_CLASSIC
8994 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
8995     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8996     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8997     conn->request_role = role;
8998     hci_run();
8999     return ERROR_CODE_SUCCESS;
9000 }
9001 #endif
9002 
9003 #ifdef ENABLE_BLE
9004 
9005 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){
9006     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9007     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9008 
9009     conn->le_phy_update_all_phys    = all_phys;
9010     conn->le_phy_update_tx_phys     = tx_phys;
9011     conn->le_phy_update_rx_phys     = rx_phys;
9012     conn->le_phy_update_phy_options = (uint8_t) phy_options;
9013 
9014     hci_run();
9015 
9016     return 0;
9017 }
9018 
9019 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9020 
9021 #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_WHITELIST_ENTRIES) || (MAX_NR_WHITELIST_ENTRIES == 0))
9022     // incorrect configuration:
9023     // - as MAX_NR_WHITELIST_ENTRIES is not defined or zero this function always fails
9024     // - please set MAX_NR_WHITELIST_ENTRIES in btstack_config.h
9025     btstack_assert(false);
9026 #endif
9027 
9028     // check if already in list
9029     btstack_linked_list_iterator_t it;
9030     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9031     while (btstack_linked_list_iterator_has_next(&it)) {
9032         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
9033         if (entry->address_type != address_type) {
9034             continue;
9035         }
9036         if (memcmp(entry->address, address, 6) != 0) {
9037             continue;
9038         }
9039 
9040         // if already on controller:
9041         if ((entry->state & LE_WHITELIST_ON_CONTROLLER) != 0){
9042             if ((entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER) != 0){
9043                 // drop remove request
9044                 entry->state = LE_WHITELIST_ON_CONTROLLER;
9045                 return ERROR_CODE_SUCCESS;
9046             } else {
9047                 // disallow as already on controller
9048                 return ERROR_CODE_COMMAND_DISALLOWED;
9049             }
9050         }
9051 
9052         // assume scheduled to add
9053 		return ERROR_CODE_COMMAND_DISALLOWED;
9054     }
9055 
9056     // alloc and add to list
9057     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
9058     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9059     entry->address_type = address_type;
9060     (void)memcpy(entry->address, address, 6);
9061     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
9062     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
9063     return ERROR_CODE_SUCCESS;
9064 }
9065 
9066 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9067     btstack_linked_list_iterator_t it;
9068     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9069     while (btstack_linked_list_iterator_has_next(&it)){
9070         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
9071         if (entry->address_type != address_type) {
9072             continue;
9073         }
9074         if (memcmp(entry->address, address, 6) != 0) {
9075             continue;
9076         }
9077         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9078             // remove from controller if already present
9079             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9080         }  else {
9081             // directly remove entry from whitelist
9082             btstack_linked_list_iterator_remove(&it);
9083             btstack_memory_whitelist_entry_free(entry);
9084         }
9085         return ERROR_CODE_SUCCESS;
9086     }
9087     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9088 }
9089 
9090 static void hci_whitelist_clear(void){
9091     btstack_linked_list_iterator_t it;
9092     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9093     while (btstack_linked_list_iterator_has_next(&it)){
9094         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
9095         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9096             // remove from controller if already present
9097             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9098             continue;
9099         }
9100         // directly remove entry from whitelist
9101         btstack_linked_list_iterator_remove(&it);
9102         btstack_memory_whitelist_entry_free(entry);
9103     }
9104 }
9105 
9106 /**
9107  * @brief Clear Whitelist
9108  * @return 0 if ok
9109  */
9110 uint8_t gap_whitelist_clear(void){
9111     hci_whitelist_clear();
9112     hci_run();
9113     return ERROR_CODE_SUCCESS;
9114 }
9115 
9116 /**
9117  * @brief Add Device to Whitelist
9118  * @param address_typ
9119  * @param address
9120  * @return 0 if ok
9121  */
9122 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9123     uint8_t status = hci_whitelist_add(address_type, address);
9124     if (status){
9125         return status;
9126     }
9127     hci_run();
9128     return ERROR_CODE_SUCCESS;
9129 }
9130 
9131 /**
9132  * @brief Remove Device from Whitelist
9133  * @param address_typ
9134  * @param address
9135  * @return 0 if ok
9136  */
9137 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9138     uint8_t status = hci_whitelist_remove(address_type, address);
9139     if (status){
9140         return status;
9141     }
9142     hci_run();
9143     return ERROR_CODE_SUCCESS;
9144 }
9145 
9146 #ifdef ENABLE_LE_CENTRAL
9147 /**
9148  * @brief Connect with Whitelist
9149  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
9150  * @return - if ok
9151  */
9152 uint8_t gap_connect_with_whitelist(void){
9153     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
9154         return ERROR_CODE_COMMAND_DISALLOWED;
9155     }
9156     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
9157     hci_run();
9158     return ERROR_CODE_SUCCESS;
9159 }
9160 
9161 /**
9162  * @brief Auto Connection Establishment - Start Connecting to device
9163  * @param address_typ
9164  * @param address
9165  * @return 0 if ok
9166  */
9167 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
9168     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
9169         return ERROR_CODE_COMMAND_DISALLOWED;
9170     }
9171 
9172     uint8_t status = hci_whitelist_add(address_type, address);
9173     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
9174         return status;
9175     }
9176 
9177     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
9178 
9179     hci_run();
9180     return ERROR_CODE_SUCCESS;
9181 }
9182 
9183 /**
9184  * @brief Auto Connection Establishment - Stop Connecting to device
9185  * @param address_typ
9186  * @param address
9187  * @return 0 if ok
9188  */
9189 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
9190     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
9191         return ERROR_CODE_COMMAND_DISALLOWED;
9192     }
9193 
9194     hci_whitelist_remove(address_type, address);
9195     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
9196         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
9197     }
9198     hci_run();
9199     return 0;
9200 }
9201 
9202 /**
9203  * @brief Auto Connection Establishment - Stop everything
9204  * @note  Convenience function to stop all active auto connection attempts
9205  */
9206 uint8_t gap_auto_connection_stop_all(void){
9207     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
9208         return ERROR_CODE_COMMAND_DISALLOWED;
9209     }
9210     hci_whitelist_clear();
9211     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
9212     hci_run();
9213     return ERROR_CODE_SUCCESS;
9214 }
9215 
9216 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
9217     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9218     if (!conn) return 0;
9219     return conn->le_connection_interval;
9220 }
9221 #endif
9222 #endif
9223 
9224 #ifdef ENABLE_CLASSIC
9225 /**
9226  * @brief Set Extended Inquiry Response data
9227  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
9228  * @note has to be done before stack starts up
9229  */
9230 void gap_set_extended_inquiry_response(const uint8_t * data){
9231     hci_stack->eir_data = data;
9232     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
9233     hci_run();
9234 }
9235 
9236 /**
9237  * @brief Start GAP Classic Inquiry
9238  * @param duration in 1.28s units
9239  * @return 0 if ok
9240  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
9241  */
9242 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
9243     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
9244     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9245     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
9246         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9247     }
9248     hci_stack->inquiry_state = duration_in_1280ms_units;
9249     hci_stack->inquiry_max_period_length = 0;
9250     hci_stack->inquiry_min_period_length = 0;
9251     hci_run();
9252     return 0;
9253 }
9254 
9255 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
9256     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
9257     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
9258     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9259     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9260     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
9261     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
9262 
9263     hci_stack->inquiry_state = duration;
9264     hci_stack->inquiry_max_period_length = max_period_length;
9265     hci_stack->inquiry_min_period_length = min_period_length;
9266     hci_run();
9267     return 0;
9268 }
9269 
9270 /**
9271  * @brief Stop GAP Classic Inquiry
9272  * @return 0 if ok
9273  */
9274 int gap_inquiry_stop(void){
9275     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
9276         // emit inquiry complete event, before it even started
9277         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
9278         hci_emit_event(event, sizeof(event), 1);
9279         return 0;
9280     }
9281     switch (hci_stack->inquiry_state){
9282         case GAP_INQUIRY_STATE_ACTIVE:
9283             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
9284             hci_run();
9285             return ERROR_CODE_SUCCESS;
9286         case GAP_INQUIRY_STATE_PERIODIC:
9287             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
9288             hci_run();
9289             return ERROR_CODE_SUCCESS;
9290         default:
9291             return ERROR_CODE_COMMAND_DISALLOWED;
9292     }
9293 }
9294 
9295 void gap_inquiry_set_lap(uint32_t lap){
9296     hci_stack->inquiry_lap = lap;
9297 }
9298 
9299 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
9300     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
9301     hci_stack->inquiry_scan_window   = inquiry_scan_window;
9302     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
9303     hci_run();
9304 }
9305 
9306 void gap_inquiry_set_transmit_power_level(int8_t tx_power)
9307 {
9308     hci_stack->inquiry_tx_power_level = tx_power;
9309     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
9310     hci_run();
9311 }
9312 
9313 
9314 /**
9315  * @brief Remote Name Request
9316  * @param addr
9317  * @param page_scan_repetition_mode
9318  * @param clock_offset only used when bit 15 is set
9319  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
9320  */
9321 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
9322     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9323     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
9324     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
9325     hci_stack->remote_name_clock_offset = clock_offset;
9326     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
9327     hci_run();
9328     return 0;
9329 }
9330 
9331 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
9332     hci_stack->gap_pairing_state = state;
9333     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
9334     hci_run();
9335     return 0;
9336 }
9337 
9338 /**
9339  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
9340  * @param addr
9341  * @param pin_data
9342  * @param pin_len
9343  * @return 0 if ok
9344  */
9345 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
9346     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9347     if (pin_len > PIN_CODE_LEN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9348     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
9349     hci_stack->gap_pairing_pin_len = pin_len;
9350     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
9351 }
9352 
9353 /**
9354  * @brief Legacy Pairing Pin Code Response
9355  * @param addr
9356  * @param pin
9357  * @return 0 if ok
9358  */
9359 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
9360     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
9361 }
9362 
9363 /**
9364  * @brief Abort Legacy Pairing
9365  * @param addr
9366  * @param pin
9367  * @return 0 if ok
9368  */
9369 int gap_pin_code_negative(bd_addr_t addr){
9370     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9371     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
9372 }
9373 
9374 /**
9375  * @brief SSP Passkey Response
9376  * @param addr
9377  * @param passkey
9378  * @return 0 if ok
9379  */
9380 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
9381     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9382     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
9383     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
9384 }
9385 
9386 /**
9387  * @brief Abort SSP Passkey Entry/Pairing
9388  * @param addr
9389  * @param pin
9390  * @return 0 if ok
9391  */
9392 int gap_ssp_passkey_negative(const bd_addr_t addr){
9393     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9394     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
9395 }
9396 
9397 /**
9398  * @brief Accept SSP Numeric Comparison
9399  * @param addr
9400  * @param passkey
9401  * @return 0 if ok
9402  */
9403 int gap_ssp_confirmation_response(const bd_addr_t addr){
9404     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9405     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
9406 }
9407 
9408 /**
9409  * @brief Abort SSP Numeric Comparison/Pairing
9410  * @param addr
9411  * @param pin
9412  * @return 0 if ok
9413  */
9414 int gap_ssp_confirmation_negative(const bd_addr_t addr){
9415     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9416     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
9417 }
9418 
9419 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
9420 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
9421     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9422     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9423     connectionSetAuthenticationFlags(conn, flag);
9424     hci_run();
9425     return ERROR_CODE_SUCCESS;
9426 }
9427 #endif
9428 
9429 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
9430 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
9431     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
9432 }
9433 
9434 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
9435     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
9436 }
9437 #endif
9438 
9439 #ifdef ENABLE_CLASSIC_PAIRING_OOB
9440 /**
9441  * @brief Report Remote OOB Data
9442  * @param bd_addr
9443  * @param c_192 Simple Pairing Hash C derived from P-192 public key
9444  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
9445  * @param c_256 Simple Pairing Hash C derived from P-256 public key
9446  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
9447  */
9448 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){
9449     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9450     if (connection == NULL) {
9451         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9452     }
9453     connection->classic_oob_c_192 = c_192;
9454     connection->classic_oob_r_192 = r_192;
9455 
9456     // ignore P-256 if not supported by us
9457     if (hci_stack->secure_connections_active){
9458         connection->classic_oob_c_256 = c_256;
9459         connection->classic_oob_r_256 = r_256;
9460     }
9461 
9462     return ERROR_CODE_SUCCESS;
9463 }
9464 /**
9465  * @brief Generate new OOB data
9466  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
9467  */
9468 void gap_ssp_generate_oob_data(void){
9469     hci_stack->classic_read_local_oob_data = true;
9470     hci_run();
9471 }
9472 
9473 #endif
9474 
9475 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
9476 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
9477     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9478     if (connection == NULL) {
9479         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9480     }
9481 
9482     memcpy(connection->link_key, link_key, sizeof(link_key_t));
9483     connection->link_key_type = type;
9484 
9485     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
9486 }
9487 
9488 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
9489 /**
9490  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
9491  * @param inquiry_mode see bluetooth_defines.h
9492  */
9493 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
9494     hci_stack->inquiry_mode = inquiry_mode;
9495 }
9496 
9497 /**
9498  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
9499  */
9500 void hci_set_sco_voice_setting(uint16_t voice_setting){
9501     hci_stack->sco_voice_setting = voice_setting;
9502 }
9503 
9504 /**
9505  * @brief Get SCO Voice Setting
9506  * @return current voice setting
9507  */
9508 uint16_t hci_get_sco_voice_setting(void){
9509     return hci_stack->sco_voice_setting;
9510 }
9511 
9512 static int hci_have_usb_transport(void){
9513     if (!hci_stack->hci_transport) return 0;
9514     const char * transport_name = hci_stack->hci_transport->name;
9515     if (!transport_name) return 0;
9516     return (transport_name[0] == 'H') && (transport_name[1] == '2');
9517 }
9518 
9519 static uint16_t hci_sco_packet_length_for_payload_length(uint16_t payload_size){
9520     uint16_t sco_packet_length = 0;
9521 
9522 #if defined(ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
9523     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
9524     int multiplier;
9525     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) &&
9526         ((hci_stack->sco_voice_setting_active & 0x20) == 0x20)) {
9527         multiplier = 2;
9528     } else {
9529         multiplier = 1;
9530     }
9531 #endif
9532 
9533 #ifdef ENABLE_SCO_OVER_HCI
9534     if (hci_have_usb_transport()){
9535         // see Core Spec for H2 USB Transfer.
9536         // 3 byte SCO header + 24 bytes per connection
9537         // @note multiple sco connections not supported currently
9538         sco_packet_length = 3 + 24 * multiplier;
9539     } else {
9540         // 3 byte SCO header + SCO packet length over the air
9541         sco_packet_length = 3 + payload_size * multiplier;
9542         // assert that it still fits inside an SCO buffer
9543         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
9544             sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9545         }
9546     }
9547 #endif
9548 #ifdef HAVE_SCO_TRANSPORT
9549     // 3 byte SCO header + SCO packet length over the air
9550     sco_packet_length = 3 + payload_size * multiplier;
9551     // assert that it still fits inside an SCO buffer
9552     if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
9553         sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9554     }
9555 #endif
9556     return sco_packet_length;
9557 }
9558 
9559 uint16_t hci_get_sco_packet_length_for_connection(hci_con_handle_t sco_con_handle){
9560     hci_connection_t * connection = hci_connection_for_handle(sco_con_handle);
9561     if (connection != NULL){
9562         return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);
9563     }
9564     return 0;
9565 }
9566 
9567 uint16_t hci_get_sco_packet_length(void){
9568     btstack_linked_list_iterator_t it;
9569     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9570     while (btstack_linked_list_iterator_has_next(&it)){
9571         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
9572         if ( connection->address_type == BD_ADDR_TYPE_SCO ) {
9573             return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);;
9574         }
9575     }
9576     return 0;
9577 }
9578 
9579 /**
9580 * @brief Sets the master/slave policy
9581 * @param policy (0: attempt to become master, 1: let connecting device decide)
9582 */
9583 void hci_set_master_slave_policy(uint8_t policy){
9584     hci_stack->master_slave_policy = policy;
9585 }
9586 
9587 #endif
9588 
9589 HCI_STATE hci_get_state(void){
9590     return hci_stack->state;
9591 }
9592 
9593 #ifdef ENABLE_CLASSIC
9594 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
9595     hci_stack->gap_classic_accept_callback = accept_callback;
9596 }
9597 #endif
9598 
9599 /**
9600  * @brief Set callback for Bluetooth Hardware Error
9601  */
9602 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
9603     hci_stack->hardware_error_callback = fn;
9604 }
9605 
9606 void hci_disconnect_all(void){
9607     btstack_linked_list_iterator_t it;
9608     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9609     while (btstack_linked_list_iterator_has_next(&it)){
9610         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9611         if (con->state == SENT_DISCONNECT) continue;
9612         con->state = SEND_DISCONNECT;
9613     }
9614     hci_run();
9615 }
9616 
9617 uint16_t hci_get_manufacturer(void){
9618     return hci_stack->manufacturer;
9619 }
9620 
9621 #ifdef ENABLE_BLE
9622 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
9623     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
9624     if (!hci_con) return NULL;
9625     return &hci_con->sm_connection;
9626 }
9627 
9628 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
9629 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
9630 #endif
9631 
9632 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
9633     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9634     if (hci_connection == NULL) return 0;
9635     if (hci_is_le_connection(hci_connection)){
9636 #ifdef ENABLE_BLE
9637         sm_connection_t * sm_conn = &hci_connection->sm_connection;
9638         if (sm_conn->sm_connection_encrypted != 0u) {
9639             return sm_conn->sm_actual_encryption_key_size;
9640         }
9641 #endif
9642     } else {
9643 #ifdef ENABLE_CLASSIC
9644         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
9645             return hci_connection->encryption_key_size;
9646         }
9647 #endif
9648     }
9649     return 0;
9650 }
9651 
9652 bool gap_authenticated(hci_con_handle_t con_handle){
9653     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9654     if (hci_connection == NULL) return false;
9655 
9656     switch (hci_connection->address_type){
9657 #ifdef ENABLE_BLE
9658         case BD_ADDR_TYPE_LE_PUBLIC:
9659         case BD_ADDR_TYPE_LE_RANDOM:
9660         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9661         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9662             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
9663             return hci_connection->sm_connection.sm_connection_authenticated != 0;
9664 #endif
9665 #ifdef ENABLE_CLASSIC
9666         case BD_ADDR_TYPE_SCO:
9667         case BD_ADDR_TYPE_ACL:
9668             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
9669 #endif
9670         default:
9671             return false;
9672     }
9673 }
9674 
9675 bool gap_secure_connection(hci_con_handle_t con_handle){
9676     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9677     if (hci_connection == NULL) return 0;
9678 
9679     switch (hci_connection->address_type){
9680 #ifdef ENABLE_BLE
9681         case BD_ADDR_TYPE_LE_PUBLIC:
9682         case BD_ADDR_TYPE_LE_RANDOM:
9683         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9684         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9685             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
9686             return hci_connection->sm_connection.sm_connection_sc;
9687 #endif
9688 #ifdef ENABLE_CLASSIC
9689         case BD_ADDR_TYPE_SCO:
9690         case BD_ADDR_TYPE_ACL:
9691             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
9692 #endif
9693         default:
9694             return false;
9695     }
9696 }
9697 
9698 bool gap_bonded(hci_con_handle_t con_handle){
9699 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9700 	if (hci_connection == NULL) return 0;
9701 
9702 #ifdef ENABLE_CLASSIC
9703 	link_key_t link_key;
9704 	link_key_type_t link_key_type;
9705 #endif
9706 	switch (hci_connection->address_type){
9707 #ifdef ENABLE_BLE
9708 		case BD_ADDR_TYPE_LE_PUBLIC:
9709 		case BD_ADDR_TYPE_LE_RANDOM:
9710 	    case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9711         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9712             return hci_connection->sm_connection.sm_le_db_index >= 0;
9713 #endif
9714 #ifdef ENABLE_CLASSIC
9715 		case BD_ADDR_TYPE_SCO:
9716 		case BD_ADDR_TYPE_ACL:
9717 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
9718 #endif
9719 		default:
9720 			return false;
9721 	}
9722 }
9723 
9724 #ifdef ENABLE_BLE
9725 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
9726     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
9727     if (sm_conn == NULL)                             return AUTHORIZATION_UNKNOWN; // wrong connection
9728     if (sm_conn->sm_connection_encrypted == 0u)      return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
9729     if (sm_conn->sm_connection_authenticated == 0u)  return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
9730     return sm_conn->sm_connection_authorization_state;
9731 }
9732 #endif
9733 
9734 #ifdef ENABLE_CLASSIC
9735 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){
9736     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9737     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9738     conn->sniff_min_interval = sniff_min_interval;
9739     conn->sniff_max_interval = sniff_max_interval;
9740     conn->sniff_attempt = sniff_attempt;
9741     conn->sniff_timeout = sniff_timeout;
9742     hci_run();
9743     return 0;
9744 }
9745 
9746 /**
9747  * @brief Exit Sniff mode
9748  * @param con_handle
9749  @ @return 0 if ok
9750  */
9751 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
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 = 0xffff;
9755     hci_run();
9756     return 0;
9757 }
9758 
9759 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){
9760     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9761     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9762     conn->sniff_subrating_max_latency = max_latency;
9763     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
9764     conn->sniff_subrating_min_local_timeout = min_local_timeout;
9765     hci_run();
9766     return ERROR_CODE_SUCCESS;
9767 }
9768 
9769 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){
9770     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9771     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9772     conn->qos_service_type = service_type;
9773     conn->qos_token_rate = token_rate;
9774     conn->qos_peak_bandwidth = peak_bandwidth;
9775     conn->qos_latency = latency;
9776     conn->qos_delay_variation = delay_variation;
9777     hci_run();
9778     return ERROR_CODE_SUCCESS;
9779 }
9780 
9781 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
9782     hci_stack->new_page_scan_interval = page_scan_interval;
9783     hci_stack->new_page_scan_window = page_scan_window;
9784     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
9785     hci_run();
9786 }
9787 
9788 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
9789     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
9790     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
9791     hci_run();
9792 }
9793 
9794 void gap_set_page_timeout(uint16_t page_timeout){
9795     hci_stack->page_timeout = page_timeout;
9796     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
9797     hci_run();
9798 }
9799 
9800 #endif
9801 
9802 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
9803 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
9804     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9805     if (le_device_db_index >= le_device_db_max_count()) return;
9806     uint8_t offset = le_device_db_index >> 3;
9807     uint8_t mask = 1 << (le_device_db_index & 7);
9808     hci_stack->le_resolving_list_add_entries[offset] |= mask;
9809     hci_stack->le_resolving_list_set_privacy_mode[offset] |= mask;
9810     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9811     	// note: go back to remove entries, otherwise, a remove + add will skip the add
9812         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9813     }
9814 }
9815 
9816 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
9817 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
9818 	if (le_device_db_index >= le_device_db_max_count()) return;
9819 	uint8_t offset = le_device_db_index >> 3;
9820 	uint8_t mask = 1 << (le_device_db_index & 7);
9821 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
9822 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
9823 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
9824 	}
9825 }
9826 
9827 uint8_t gap_load_resolving_list_from_le_device_db(void){
9828     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
9829 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
9830 	}
9831 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
9832 		// restart le resolving list update
9833 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
9834 	}
9835 	return ERROR_CODE_SUCCESS;
9836 }
9837 
9838 void gap_set_peer_privacy_mode(le_privacy_mode_t privacy_mode ){
9839     hci_stack->le_privacy_mode = privacy_mode;
9840 }
9841 #endif
9842 
9843 #ifdef ENABLE_BLE
9844 #ifdef ENABLE_LE_CENTRAL
9845 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
9846 
9847 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9848 
9849 #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES) || (MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES == 0))
9850     // incorrect configuration:
9851     // - as MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES is not defined or zero this function always fails
9852     // - please set MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES in btstack_config.h
9853     btstack_assert(false);
9854 #endif
9855 
9856     // check if already in list
9857     btstack_linked_list_iterator_t it;
9858     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9859     while (btstack_linked_list_iterator_has_next(&it)) {
9860         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
9861         if (entry->sid != advertising_sid) {
9862             continue;
9863         }
9864         if (entry->address_type != address_type) {
9865             continue;
9866         }
9867         if (memcmp(entry->address, address, 6) != 0) {
9868             continue;
9869         }
9870         // disallow if already scheduled to add
9871         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
9872             return ERROR_CODE_COMMAND_DISALLOWED;
9873         }
9874         // still on controller, but scheduled to remove -> re-add
9875         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9876         return ERROR_CODE_SUCCESS;
9877     }
9878     // alloc and add to list
9879     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
9880     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9881     entry->sid = advertising_sid;
9882     entry->address_type = address_type;
9883     (void)memcpy(entry->address, address, 6);
9884     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9885     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
9886     return ERROR_CODE_SUCCESS;
9887 }
9888 
9889 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9890     btstack_linked_list_iterator_t it;
9891     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9892     while (btstack_linked_list_iterator_has_next(&it)){
9893         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9894         if (entry->sid != advertising_sid) {
9895             continue;
9896         }
9897         if (entry->address_type != address_type) {
9898             continue;
9899         }
9900         if (memcmp(entry->address, address, 6) != 0) {
9901             continue;
9902         }
9903         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9904             // remove from controller if already present
9905             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9906         }  else {
9907             // directly remove entry from whitelist
9908             btstack_linked_list_iterator_remove(&it);
9909             btstack_memory_periodic_advertiser_list_entry_free(entry);
9910         }
9911         return ERROR_CODE_SUCCESS;
9912     }
9913     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9914 }
9915 
9916 static void hci_periodic_advertiser_list_clear(void){
9917     btstack_linked_list_iterator_t it;
9918     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9919     while (btstack_linked_list_iterator_has_next(&it)){
9920         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9921         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9922             // remove from controller if already present
9923             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9924             continue;
9925         }
9926         // directly remove entry from whitelist
9927         btstack_linked_list_iterator_remove(&it);
9928         btstack_memory_periodic_advertiser_list_entry_free(entry);
9929     }
9930 }
9931 
9932 uint8_t gap_periodic_advertiser_list_clear(void){
9933     hci_periodic_advertiser_list_clear();
9934     hci_run();
9935     return ERROR_CODE_SUCCESS;
9936 }
9937 
9938 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9939     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
9940     if (status){
9941         return status;
9942     }
9943     hci_run();
9944     return ERROR_CODE_SUCCESS;
9945 }
9946 
9947 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9948     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
9949     if (status){
9950         return status;
9951     }
9952     hci_run();
9953     return ERROR_CODE_SUCCESS;
9954 }
9955 
9956 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
9957                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
9958     // abort if already active
9959     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
9960         return ERROR_CODE_COMMAND_DISALLOWED;
9961     }
9962     // store request
9963     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
9964     hci_stack->le_periodic_sync_options = options;
9965     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
9966     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
9967     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
9968     hci_stack->le_periodic_sync_skip = skip;
9969     hci_stack->le_periodic_sync_timeout = sync_timeout;
9970     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
9971 
9972     hci_run();
9973     return ERROR_CODE_SUCCESS;
9974 }
9975 
9976 uint8_t gap_periodic_advertising_create_sync_cancel(void){
9977     // abort if not requested
9978     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
9979         return ERROR_CODE_COMMAND_DISALLOWED;
9980     }
9981     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
9982     hci_run();
9983     return ERROR_CODE_SUCCESS;
9984 }
9985 
9986 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
9987     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
9988         return ERROR_CODE_COMMAND_DISALLOWED;
9989     }
9990     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
9991     hci_run();
9992     return ERROR_CODE_SUCCESS;
9993 }
9994 
9995 #endif
9996 #endif
9997 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
9998 static hci_iso_stream_t *
9999 hci_iso_stream_create(hci_iso_type_t iso_type, hci_iso_stream_state_t state, uint8_t group_id, uint8_t stream_id) {
10000     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
10001     if (iso_stream != NULL){
10002         iso_stream->iso_type = iso_type;
10003         iso_stream->state = state;
10004         iso_stream->group_id = group_id;
10005         iso_stream->stream_id = stream_id;
10006         iso_stream->cis_handle = HCI_CON_HANDLE_INVALID;
10007         iso_stream->acl_handle = HCI_CON_HANDLE_INVALID;
10008         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
10009     }
10010     return iso_stream;
10011 }
10012 
10013 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
10014     btstack_linked_list_iterator_t it;
10015     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10016     while (btstack_linked_list_iterator_has_next(&it)){
10017         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10018         if (iso_stream->cis_handle == con_handle ) {
10019             return iso_stream;
10020         }
10021     }
10022     return NULL;
10023 }
10024 
10025 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
10026     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->cis_handle, iso_stream->group_id);
10027     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
10028     btstack_memory_hci_iso_stream_free(iso_stream);
10029 }
10030 
10031 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
10032     btstack_linked_list_iterator_t it;
10033     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10034     while (btstack_linked_list_iterator_has_next(&it)){
10035         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10036         if ((iso_stream->group_id == group_id) &&
10037             (iso_stream->iso_type == iso_type)){
10038             btstack_linked_list_iterator_remove(&it);
10039             btstack_memory_hci_iso_stream_free(iso_stream);
10040         }
10041     }
10042 }
10043 
10044 static void hci_iso_stream_requested_finalize(uint8_t group_id) {
10045     btstack_linked_list_iterator_t it;
10046     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10047     while (btstack_linked_list_iterator_has_next(&it)){
10048         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10049         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
10050             (iso_stream->group_id == group_id)){
10051             btstack_linked_list_iterator_remove(&it);
10052             btstack_memory_hci_iso_stream_free(iso_stream);
10053         }
10054     }
10055 }
10056 static void hci_iso_stream_requested_confirm(uint8_t big_handle){
10057     btstack_linked_list_iterator_t it;
10058     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10059     while (btstack_linked_list_iterator_has_next(&it)){
10060         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10061         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
10062             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
10063         }
10064     }
10065 }
10066 
10067 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
10068     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
10069     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
10070     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
10071     return (sdu_len_offset + 2 + sdu_len) == size;
10072 }
10073 
10074 static void hci_iso_packet_handler(hci_iso_stream_t *iso_stream, uint8_t *packet, uint16_t size) {
10075     if (iso_stream == NULL){
10076         log_error("acl_handler called with non-registered handle %u!" , READ_ISO_CONNECTION_HANDLE(packet));
10077         return;
10078     }
10079 
10080     if (hci_stack->iso_packet_handler == NULL) {
10081         return;
10082     }
10083 
10084     // parse header
10085     uint16_t con_handle_and_flags = little_endian_read_16(packet, 0);
10086     uint16_t data_total_length = little_endian_read_16(packet, 2);
10087     uint8_t  pb_flag = (con_handle_and_flags >> 12) & 3;
10088 
10089     // assert packet is complete
10090     if ((data_total_length + 4u) != size){
10091         return;
10092     }
10093 
10094     if ((pb_flag & 0x01) == 0){
10095         if (pb_flag == 0x02){
10096             // The ISO_SDU_Fragment field contains a header and a complete SDU.
10097             if (hci_iso_sdu_complete(packet, size)) {
10098                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
10099             }
10100         } else {
10101             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
10102             if (size > sizeof(iso_stream->reassembly_buffer)){
10103                 return;
10104             }
10105             memcpy(iso_stream->reassembly_buffer, packet, size);
10106             // fix pb_flag
10107             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
10108             iso_stream->reassembly_pos = size;
10109         }
10110     } else {
10111         // ISO_SDU_Fragment contains continuation or last fragment of an SDU
10112         uint8_t ts_flag = (con_handle_and_flags >> 14) & 1;
10113         if (ts_flag != 0){
10114            return;
10115         }
10116         // append fragment
10117         if (iso_stream->reassembly_pos == 0){
10118             return;
10119         }
10120 
10121         if ((iso_stream->reassembly_pos + data_total_length) > sizeof(iso_stream->reassembly_buffer)){
10122             // reset reassembly buffer
10123             iso_stream->reassembly_pos = 0;
10124             return;
10125         }
10126         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], data_total_length);
10127         iso_stream->reassembly_pos += data_total_length;
10128 
10129         // deliver if last fragment and SDU complete
10130         if (pb_flag == 0x03){
10131             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
10132                 // fix data_total_length
10133                 little_endian_store_16(iso_stream->reassembly_buffer, 2, iso_stream->reassembly_pos - HCI_ISO_HEADER_SIZE);
10134                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
10135             }
10136             // reset reassembly buffer
10137             iso_stream->reassembly_pos = 0;
10138         }
10139     }
10140 }
10141 
10142 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
10143     uint8_t event [6 + (MAX_NR_BIS * 2)];
10144     uint16_t pos = 0;
10145     event[pos++] = HCI_EVENT_META_GAP;
10146     event[pos++] = 4 + (2 * big->num_bis);
10147     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
10148     event[pos++] = status;
10149     event[pos++] = big->big_handle;
10150     event[pos++] = big->num_bis;
10151     uint8_t i;
10152     for (i=0;i<big->num_bis;i++){
10153         little_endian_store_16(event, pos, big->bis_con_handles[i]);
10154         pos += 2;
10155     }
10156     hci_emit_event(event, pos, 0);
10157 }
10158 
10159 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
10160     uint8_t event [6 + (MAX_NR_CIS * 2)];
10161     uint16_t pos = 0;
10162     event[pos++] = HCI_EVENT_META_GAP;
10163     event[pos++] = 4 + (2 * cig->num_cis);
10164     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
10165     event[pos++] = status;
10166     event[pos++] = cig->cig_id;
10167     event[pos++] = cig->num_cis;
10168     uint8_t i;
10169     for (i=0;i<cig->num_cis;i++){
10170         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
10171         pos += 2;
10172     }
10173     hci_emit_event(event, pos, 0);
10174 }
10175 
10176 static uint16_t hci_setup_cis_created(uint8_t * event, hci_iso_stream_t * iso_stream, uint8_t status) {
10177     uint16_t pos = 0;
10178     event[pos++] = HCI_EVENT_META_GAP;
10179     event[pos++] = 8;
10180     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
10181     event[pos++] = status;
10182     event[pos++] = iso_stream->group_id;
10183     event[pos++] = iso_stream->stream_id;
10184     little_endian_store_16(event, pos, iso_stream->cis_handle);
10185     pos += 2;
10186     little_endian_store_16(event, pos, iso_stream->acl_handle);
10187     pos += 2;
10188     little_endian_store_16(event, pos, iso_stream->iso_interval_1250us);
10189     pos += 2;
10190     event[pos++] = iso_stream->number_of_subevents;
10191     event[pos++] = iso_stream->burst_number_c_to_p;
10192     event[pos++] = iso_stream->burst_number_p_to_c;
10193     event[pos++] = iso_stream->flush_timeout_c_to_p;
10194     event[pos++] = iso_stream->flush_timeout_p_to_c;
10195     return pos;
10196 }
10197 
10198 // emits GAP_SUBEVENT_CIS_CREATED after calling hci_iso_finalize
10199 static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status){
10200     // cache data before finalizing struct
10201     uint8_t event [17];
10202     uint16_t pos = hci_setup_cis_created(event, iso_stream, status);
10203     btstack_assert(pos <= sizeof(event));
10204     if (status != ERROR_CODE_SUCCESS){
10205         hci_iso_stream_finalize(iso_stream);
10206     }
10207     hci_emit_event(event, pos, 0);
10208 }
10209 
10210 static void hci_emit_big_terminated(const le_audio_big_t * big){
10211     uint8_t event [4];
10212     uint16_t pos = 0;
10213     event[pos++] = HCI_EVENT_META_GAP;
10214     event[pos++] = 2;
10215     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
10216     event[pos++] = big->big_handle;
10217     hci_emit_event(event, pos, 0);
10218 }
10219 
10220 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
10221     uint8_t event [6 + (MAX_NR_BIS * 2)];
10222     uint16_t pos = 0;
10223     event[pos++] = HCI_EVENT_META_GAP;
10224     event[pos++] = 4;
10225     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
10226     event[pos++] = status;
10227     event[pos++] = big_sync->big_handle;
10228     event[pos++] = big_sync->num_bis;
10229     uint8_t i;
10230     for (i=0;i<big_sync->num_bis;i++){
10231         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
10232         pos += 2;
10233     }
10234     hci_emit_event(event, pos, 0);
10235 }
10236 
10237 static void hci_emit_big_sync_stopped(uint8_t big_handle){
10238     uint8_t event [4];
10239     uint16_t pos = 0;
10240     event[pos++] = HCI_EVENT_META_GAP;
10241     event[pos++] = 2;
10242     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
10243     event[pos++] = big_handle;
10244     hci_emit_event(event, pos, 0);
10245 }
10246 
10247 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
10248     uint8_t event[6];
10249     uint16_t pos = 0;
10250     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
10251     event[pos++] = sizeof(event) - 2;
10252     event[pos++] = big->big_handle;
10253     event[pos++] = bis_index;
10254     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
10255     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
10256 }
10257 
10258 static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) {
10259     uint8_t event[4];
10260     uint16_t pos = 0;
10261     event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW;
10262     event[pos++] = sizeof(event) - 2;
10263     little_endian_store_16(event, pos, cis_con_handle);
10264     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
10265 }
10266 
10267 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
10268     btstack_linked_list_iterator_t it;
10269     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10270     while (btstack_linked_list_iterator_has_next(&it)){
10271         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10272         if ( big->big_handle == big_handle ) {
10273             return big;
10274         }
10275     }
10276     return NULL;
10277 }
10278 
10279 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
10280     btstack_linked_list_iterator_t it;
10281     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
10282     while (btstack_linked_list_iterator_has_next(&it)){
10283         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
10284         if ( big_sync->big_handle == big_handle ) {
10285             return big_sync;
10286         }
10287     }
10288     return NULL;
10289 }
10290 
10291 void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
10292     hci_stack->iso_packets_to_queue = num_packets;
10293 }
10294 
10295 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
10296     btstack_linked_list_iterator_t it;
10297     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
10298     while (btstack_linked_list_iterator_has_next(&it)){
10299         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
10300         if ( cig->cig_id == cig_id ) {
10301             return cig;
10302         }
10303     }
10304     return NULL;
10305 }
10306 
10307 static void hci_iso_notify_can_send_now(void){
10308 
10309     // BIG
10310 
10311     btstack_linked_list_iterator_t it;
10312     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10313     while (btstack_linked_list_iterator_has_next(&it)){
10314         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10315         // track number completed packet timestamps
10316         if (big->num_completed_timestamp_current_valid){
10317             big->num_completed_timestamp_current_valid = false;
10318             if (big->num_completed_timestamp_previous_valid){
10319                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
10320                 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
10321                 int32_t  num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
10322                                                                                big->num_completed_timestamp_previous_ms);
10323                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
10324                     // to catch up, skip packet on all BIS
10325                     uint8_t i;
10326                     for (i=0;i<big->num_bis;i++){
10327                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10328                         if (iso_stream){
10329                             iso_stream->num_packets_to_skip++;
10330                         }
10331                     }
10332                 }
10333             }
10334             big->num_completed_timestamp_previous_valid = true;
10335             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
10336         }
10337 
10338         if (big->can_send_now_requested){
10339             // check if no outgoing iso packets pending and no can send now have to be emitted
10340             uint8_t i;
10341             bool can_send = true;
10342             uint8_t num_iso_queued_minimum = 0;
10343             for (i=0;i<big->num_bis;i++){
10344                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10345                 if (iso_stream == NULL) continue;
10346                 // handle case where individual ISO packet was sent too late:
10347                 // for each additionally queued packet, a new one needs to get skipped
10348                 if (i==0){
10349                     num_iso_queued_minimum = iso_stream->num_packets_sent;
10350                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
10351                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
10352                     iso_stream->num_packets_to_skip += num_packets_to_skip;
10353                     iso_stream->num_packets_sent    -= num_packets_to_skip;
10354                 }
10355                 // check if we can send now
10356                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
10357                     can_send = false;
10358                     break;
10359                 }
10360             }
10361             if (can_send){
10362                 // propagate can send now to individual streams
10363                 big->can_send_now_requested = false;
10364                 for (i=0;i<big->num_bis;i++){
10365                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10366                     iso_stream->emit_ready_to_send = true;
10367                 }
10368             }
10369         }
10370     }
10371 
10372     if (hci_stack->hci_packet_buffer_reserved) return;
10373 
10374     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
10375     while (btstack_linked_list_iterator_has_next(&it)){
10376         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10377         // report bis ready
10378         uint8_t i;
10379         for (i=0;i<big->num_bis;i++){
10380             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10381             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
10382                 iso_stream->emit_ready_to_send = false;
10383                 hci_emit_bis_can_send_now(big, i);
10384                 break;
10385             }
10386         }
10387     }
10388 
10389     // CIS
10390     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10391     while (btstack_linked_list_iterator_has_next(&it)) {
10392         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10393         if ((iso_stream->can_send_now_requested) &&
10394             (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){
10395             iso_stream->can_send_now_requested = false;
10396             hci_emit_cis_can_send_now(iso_stream->cis_handle);
10397         }
10398     }
10399 }
10400 
10401 static uint8_t gap_big_setup_iso_streams(uint8_t num_bis, uint8_t big_handle){
10402     // make big handle unique and usuable for big and big sync
10403     if (hci_big_for_handle(big_handle) != NULL){
10404         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10405     }
10406     if (hci_big_sync_for_handle(big_handle) != NULL){
10407         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10408     }
10409     if (num_bis == 0){
10410         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10411     }
10412     if (num_bis > MAX_NR_BIS){
10413         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10414     }
10415 
10416     // reserve ISO Streams
10417     uint8_t i;
10418     uint8_t status = ERROR_CODE_SUCCESS;
10419     for (i=0;i<num_bis;i++){
10420         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_ISO_STREAM_STATE_REQUESTED, big_handle, i);
10421         if (iso_stream == NULL) {
10422             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10423             break;
10424         }
10425     }
10426 
10427     // free structs on error
10428     if (status != ERROR_CODE_SUCCESS){
10429         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_handle);
10430     }
10431 
10432     return status;
10433 }
10434 
10435 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
10436     uint8_t status = gap_big_setup_iso_streams(big_params->num_bis, big_params->big_handle);
10437     if (status != ERROR_CODE_SUCCESS){
10438         return status;
10439     }
10440 
10441     le_audio_big_t * big = storage;
10442     big->big_handle = big_params->big_handle;
10443     big->params = big_params;
10444     big->state = LE_AUDIO_BIG_STATE_CREATE;
10445     big->num_bis = big_params->num_bis;
10446     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
10447 
10448     hci_run();
10449 
10450     return ERROR_CODE_SUCCESS;
10451 }
10452 
10453 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
10454     uint8_t status = gap_big_setup_iso_streams(big_sync_params->num_bis, big_sync_params->big_handle);
10455     if (status != ERROR_CODE_SUCCESS){
10456         return status;
10457     }
10458 
10459     le_audio_big_sync_t * big_sync = storage;
10460     big_sync->big_handle = big_sync_params->big_handle;
10461     big_sync->params = big_sync_params;
10462     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
10463     big_sync->num_bis = big_sync_params->num_bis;
10464     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10465 
10466     hci_run();
10467 
10468     return ERROR_CODE_SUCCESS;
10469 }
10470 
10471 uint8_t gap_big_terminate(uint8_t big_handle){
10472     le_audio_big_t * big = hci_big_for_handle(big_handle);
10473     if (big == NULL){
10474         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10475     }
10476     switch (big->state){
10477         case LE_AUDIO_BIG_STATE_CREATE:
10478             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
10479             hci_emit_big_terminated(big);
10480             break;
10481         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
10482             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
10483             break;
10484         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
10485         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
10486         case LE_AUDIO_BIG_STATE_ACTIVE:
10487             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
10488             hci_run();
10489             break;
10490         default:
10491             return ERROR_CODE_COMMAND_DISALLOWED;
10492     }
10493     return ERROR_CODE_SUCCESS;
10494 }
10495 
10496 uint8_t gap_big_sync_terminate(uint8_t big_handle){
10497     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
10498     if (big_sync == NULL){
10499         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10500     }
10501     switch (big_sync->state){
10502         case LE_AUDIO_BIG_STATE_CREATE:
10503             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10504             hci_emit_big_sync_stopped(big_handle);
10505             break;
10506         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
10507             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
10508             break;
10509         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
10510         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
10511         case LE_AUDIO_BIG_STATE_ACTIVE:
10512             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
10513             hci_run();
10514             break;
10515         default:
10516             return ERROR_CODE_COMMAND_DISALLOWED;
10517     }
10518     return ERROR_CODE_SUCCESS;
10519 }
10520 
10521 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
10522     le_audio_big_t * big = hci_big_for_handle(big_handle);
10523     if (big == NULL){
10524         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10525     }
10526     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
10527         return ERROR_CODE_COMMAND_DISALLOWED;
10528     }
10529     big->can_send_now_requested = true;
10530     hci_iso_notify_can_send_now();
10531     return ERROR_CODE_SUCCESS;
10532 }
10533 
10534 uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){
10535     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
10536     if (iso_stream == NULL){
10537         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10538     }
10539     if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) {
10540         return ERROR_CODE_COMMAND_DISALLOWED;
10541     }
10542     iso_stream->can_send_now_requested = true;
10543     hci_iso_notify_can_send_now();
10544     return ERROR_CODE_SUCCESS;
10545 }
10546 
10547 uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
10548     if (hci_cig_for_id(cig_params->cig_id) != NULL){
10549         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10550     }
10551     if (cig_params->num_cis == 0){
10552         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10553     }
10554     if (cig_params->num_cis > MAX_NR_CIS){
10555         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10556     }
10557 
10558     // reserve ISO Streams
10559     uint8_t i;
10560     uint8_t status = ERROR_CODE_SUCCESS;
10561     for (i=0;i<cig_params->num_cis;i++){
10562         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS,HCI_ISO_STREAM_STATE_REQUESTED, cig_params->cig_id, i);
10563         if (iso_stream == NULL) {
10564             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10565             break;
10566         }
10567     }
10568 
10569     // free structs on error
10570     if (status != ERROR_CODE_SUCCESS){
10571         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
10572         return status;
10573     }
10574 
10575     le_audio_cig_t * cig = storage;
10576     cig->cig_id = cig_params->cig_id;
10577     cig->num_cis = cig_params->num_cis;
10578     cig->params = cig_params;
10579     cig->state = LE_AUDIO_CIG_STATE_CREATE;
10580     for (i=0;i<cig->num_cis;i++){
10581         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
10582         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
10583         cig->cis_setup_active[i] = false;
10584         cig->cis_established[i] = false;
10585     }
10586     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
10587 
10588     hci_run();
10589 
10590     return ERROR_CODE_SUCCESS;
10591 }
10592 
10593 uint8_t gap_cig_remove(uint8_t cig_id){
10594     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10595     if (cig == NULL){
10596         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10597     }
10598 
10599     // close active CIS
10600     uint8_t i;
10601     for (i=0;i<cig->num_cis;i++){
10602         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
10603         if (stream != NULL){
10604             stream->state = HCI_ISO_STREAM_STATE_W2_CLOSE;
10605         }
10606     }
10607     cig->state = LE_AUDIO_CIG_STATE_REMOVE;
10608 
10609     hci_run();
10610 
10611     return ERROR_CODE_SUCCESS;
10612 }
10613 
10614 uint8_t gap_cis_create(uint8_t cig_id, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
10615     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10616     if (cig == NULL){
10617         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10618     }
10619 
10620     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
10621         return ERROR_CODE_COMMAND_DISALLOWED;
10622     }
10623 
10624     // store ACL Connection Handles
10625     uint8_t i;
10626     for (i=0;i<cig->num_cis;i++){
10627         // check that all con handles exist and store
10628         hci_con_handle_t cis_handle = cis_con_handles[i];
10629         if (cis_handle == HCI_CON_HANDLE_INVALID){
10630             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10631         }
10632         uint8_t j;
10633         bool found = false;
10634         for (j=0;j<cig->num_cis;j++){
10635             if (cig->cis_con_handles[j] == cis_handle){
10636                 cig->acl_con_handles[j] = acl_con_handles[j];
10637                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
10638                 btstack_assert(iso_stream != NULL);
10639                 iso_stream->acl_handle = acl_con_handles[j];
10640                 found = true;
10641                 break;
10642             }
10643         }
10644         if (!found){
10645             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10646         }
10647     }
10648 
10649     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
10650     hci_run();
10651 
10652     return ERROR_CODE_SUCCESS;
10653 }
10654 
10655 static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_handle, hci_iso_stream_state_t state){
10656     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
10657     if (iso_stream == NULL){
10658         // if we got a CIS Request but fail to allocate a hci_iso_stream_t object, we won't find it here
10659         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10660     }
10661 
10662     // set next state and continue
10663     iso_stream->state = state;
10664     hci_run();
10665     return ERROR_CODE_SUCCESS;
10666 }
10667 
10668 uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){
10669     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT);
10670 }
10671 
10672 uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){
10673     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT);
10674 }
10675 
10676 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
10677 
10678 // GAP Privacy - notify clients before random address update
10679 
10680 static bool gap_privacy_client_all_ready(void){
10681     // check if all ready
10682     btstack_linked_list_iterator_t it;
10683     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10684     while (btstack_linked_list_iterator_has_next(&it)) {
10685         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10686         if (client->state != GAP_PRIVACY_CLIENT_STATE_READY){
10687             return false;
10688         }
10689     }
10690     return true;
10691 }
10692 
10693 static void gap_privacy_clients_handle_ready(void){
10694     // clear 'ready'
10695     btstack_linked_list_iterator_t it;
10696     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10697     while (btstack_linked_list_iterator_has_next(&it)) {
10698         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10699         client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10700     }
10701     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
10702     hci_run();
10703 }
10704 
10705 static void gap_privacy_clients_notify(bd_addr_t new_random_address){
10706     btstack_linked_list_iterator_t it;
10707     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10708     while (btstack_linked_list_iterator_has_next(&it)) {
10709         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10710         if (client->state == GAP_PRIVACY_CLIENT_STATE_IDLE){
10711             client->state = GAP_PRIVACY_CLIENT_STATE_PENDING;
10712             (*client->callback)(client, new_random_address);
10713         }
10714     }
10715     if (gap_privacy_client_all_ready()){
10716         gap_privacy_clients_handle_ready();
10717     }
10718 }
10719 
10720 void gap_privacy_client_register(gap_privacy_client_t * client){
10721     client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10722     btstack_linked_list_add(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10723 }
10724 
10725 void gap_privacy_client_ready(gap_privacy_client_t * client){
10726     client->state = GAP_PRIVACY_CLIENT_STATE_READY;
10727     if (gap_privacy_client_all_ready()){
10728         gap_privacy_clients_handle_ready();
10729     }
10730 }
10731 
10732 void gap_privacy_client_unregister(gap_privacy_client_t * client){
10733     btstack_linked_list_remove(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10734 }
10735 
10736 #endif /* ENABLE_BLE */
10737 
10738 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
10739 void hci_setup_test_connections_fuzz(void){
10740     hci_connection_t * conn;
10741 
10742     // default address: 66:55:44:33:00:01
10743     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
10744 
10745     // setup Controller info
10746     hci_stack->num_cmd_packets = 255;
10747     hci_stack->acl_packets_total_num = 255;
10748 
10749     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
10750     addr[5] = 0x01;
10751     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
10752     conn->con_handle = addr[5];
10753     conn->state = RECEIVED_CONNECTION_REQUEST;
10754     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10755 
10756     // setup incoming Classic SCO connection with con handle 0x0002
10757     addr[5] = 0x02;
10758     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
10759     conn->con_handle = addr[5];
10760     conn->state = RECEIVED_CONNECTION_REQUEST;
10761     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10762 
10763     // setup ready Classic ACL connection with con handle 0x0003
10764     addr[5] = 0x03;
10765     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
10766     conn->con_handle = addr[5];
10767     conn->state = OPEN;
10768     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10769 
10770     // setup ready Classic SCO connection with con handle 0x0004
10771     addr[5] = 0x04;
10772     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
10773     conn->con_handle = addr[5];
10774     conn->state = OPEN;
10775     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10776 
10777     // setup ready LE ACL connection with con handle 0x005 and public address
10778     addr[5] = 0x05;
10779     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC, HCI_ROLE_SLAVE);
10780     conn->con_handle = addr[5];
10781     conn->state = OPEN;
10782     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
10783     conn->sm_connection.sm_connection_encrypted = 1;
10784 }
10785 
10786 void hci_free_connections_fuzz(void){
10787     btstack_linked_list_iterator_t it;
10788     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
10789     while (btstack_linked_list_iterator_has_next(&it)){
10790         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
10791         btstack_linked_list_iterator_remove(&it);
10792         btstack_memory_hci_connection_free(con);
10793     }
10794 }
10795 void hci_simulate_working_fuzz(void){
10796     hci_stack->le_scanning_param_update = false;
10797     hci_init_done();
10798     hci_stack->num_cmd_packets = 255;
10799 }
10800 #endif
10801