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