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