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