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