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