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