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