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