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