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