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