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