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