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