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