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