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