xref: /btstack/src/hci.c (revision b8cf9cc03df108e90aa081275c907a15238115dc)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "hci.c"
39 
40 /*
41  *  hci.c
42  *
43  *  Created by Matthias Ringwald on 4/29/09.
44  *
45  */
46 
47 #include "btstack_config.h"
48 
49 
50 #ifdef ENABLE_CLASSIC
51 #ifdef HAVE_EMBEDDED_TICK
52 #include "btstack_run_loop_embedded.h"
53 #endif
54 #endif
55 
56 #ifdef ENABLE_BLE
57 #include "gap.h"
58 #include "ble/le_device_db.h"
59 #endif
60 
61 #include <stdarg.h>
62 #include <string.h>
63 #include <inttypes.h>
64 
65 #include "btstack_debug.h"
66 #include "btstack_event.h"
67 #include "btstack_linked_list.h"
68 #include "btstack_memory.h"
69 #include "bluetooth_company_id.h"
70 #include "bluetooth_data_types.h"
71 #include "gap.h"
72 #include "hci.h"
73 #include "hci_cmd.h"
74 #include "hci_dump.h"
75 #include "ad_parser.h"
76 
77 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
78 #include <stdio.h>  // sprintf
79 #endif
80 
81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
82 #ifndef HCI_HOST_ACL_PACKET_NUM
83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
84 #endif
85 #ifndef HCI_HOST_ACL_PACKET_LEN
86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
87 #endif
88 #ifndef HCI_HOST_SCO_PACKET_NUM
89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
90 #endif
91 #ifndef HCI_HOST_SCO_PACKET_LEN
92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
93 #endif
94 #endif
95 
96 #ifndef MAX_NR_CONTROLLER_ACL_BUFFERS
97 #define MAX_NR_CONTROLLER_ACL_BUFFERS 255
98 #endif
99 #ifndef MAX_NR_CONTROLLER_SCO_PACKETS
100 #define MAX_NR_CONTROLLER_SCO_PACKETS 255
101 #endif
102 
103 #ifndef HCI_ACL_CHUNK_SIZE_ALIGNMENT
104 #define HCI_ACL_CHUNK_SIZE_ALIGNMENT 1
105 #endif
106 
107 #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
108 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM."
109 #endif
110 
111 #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT)
112 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or HAVE_SCO_TRANSPORT."
113 #endif
114 
115 #define HCI_CONNECTION_TIMEOUT_MS 10000
116 
117 #ifndef HCI_RESET_RESEND_TIMEOUT_MS
118 #define HCI_RESET_RESEND_TIMEOUT_MS 200
119 #endif
120 
121 // Names are arbitrarily shortened to 32 bytes if not requested otherwise
122 #ifndef GAP_INQUIRY_MAX_NAME_LEN
123 #define GAP_INQUIRY_MAX_NAME_LEN 32
124 #endif
125 
126 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
127 #define GAP_INQUIRY_DURATION_MIN       0x01
128 #define GAP_INQUIRY_DURATION_MAX       0x30
129 #define GAP_INQUIRY_MIN_PERIODIC_LEN_MIN 0x02
130 #define GAP_INQUIRY_MAX_PERIODIC_LEN_MIN 0x03
131 #define GAP_INQUIRY_STATE_IDLE         0x00
132 #define GAP_INQUIRY_STATE_W4_ACTIVE    0x80
133 #define GAP_INQUIRY_STATE_ACTIVE       0x81
134 #define GAP_INQUIRY_STATE_W2_CANCEL    0x82
135 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83
136 #define GAP_INQUIRY_STATE_PERIODIC     0x84
137 #define GAP_INQUIRY_STATE_W2_EXIT_PERIODIC 0x85
138 
139 // GAP Remote Name Request
140 #define GAP_REMOTE_NAME_STATE_IDLE 0
141 #define GAP_REMOTE_NAME_STATE_W2_SEND 1
142 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
143 
144 // GAP Pairing
145 #define GAP_PAIRING_STATE_IDLE                       0
146 #define GAP_PAIRING_STATE_SEND_PIN                   1
147 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
148 #define GAP_PAIRING_STATE_SEND_PASSKEY               3
149 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
150 #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
151 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
152 #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE  7
153 
154 //
155 // compact storage of relevant supported HCI Commands.
156 // X-Macro below provides enumeration and mapping table into the supported
157 // commands bitmap (64 bytes) from HCI Read Local Supported Commands
158 //
159 
160 // format: command name, byte offset, bit nr in 64-byte supported commands
161 // currently stored in 32-bit variable
162 #define SUPPORTED_HCI_COMMANDS \
163     X( SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES         ,  2, 5) \
164     X( SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE , 10, 4) \
165     X( SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE                      , 14, 7) \
166     X( SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, 18, 3) \
167     X( SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE              , 20, 4) \
168     X( SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2                 , 22, 2) \
169     X( SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED               , 24, 6) \
170     X( SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, 32, 1) \
171     X( SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST         , 32, 3) \
172     X( SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND  , 32, 6) \
173     X( SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, 34, 0) \
174     X( SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE      , 35, 1) \
175     X( SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH           , 35, 3) \
176     X( SUPPORTED_HCI_COMMAND_LE_SET_DEFAULT_PHY                    , 35, 5) \
177     X( SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE    , 36, 6) \
178     X( SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2                , 41, 5) \
179     X( SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE           , 45, 7) \
180 
181 // enumerate supported commands
182 #define X(name, offset, bit) name,
183 enum {
184     SUPPORTED_HCI_COMMANDS
185     SUPPORTED_HCI_COMMANDS_COUNT
186 };
187 #undef X
188 
189 // prototypes
190 #ifdef ENABLE_CLASSIC
191 static void hci_update_scan_enable(void);
192 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable);
193 static int  hci_local_ssp_activated(void);
194 static bool hci_remote_ssp_supported(hci_con_handle_t con_handle);
195 static bool hci_ssp_supported(hci_connection_t * connection);
196 static void hci_notify_if_sco_can_send_now(void);
197 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
198 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
199 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
200 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
201 static void hci_connection_timestamp(hci_connection_t *connection);
202 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
203 static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
204 #endif
205 
206 static int  hci_power_control_on(void);
207 static void hci_power_control_off(void);
208 static void hci_state_reset(void);
209 static void hci_halting_timeout_handler(btstack_timer_source_t * ds);
210 static void hci_emit_transport_packet_sent(void);
211 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
212 static void hci_emit_nr_connections_changed(void);
213 static void hci_emit_hci_open_failed(void);
214 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
215 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
216 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
217 static void hci_run(void);
218 static bool hci_is_le_connection(hci_connection_t * connection);
219 
220 #ifdef ENABLE_CLASSIC
221 static int hci_have_usb_transport(void);
222 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection);
223 #endif
224 
225 #ifdef ENABLE_BLE
226 static bool hci_run_general_gap_le(void);
227 static void gap_privacy_clients_handle_ready(void);
228 static void gap_privacy_clients_notify(bd_addr_t new_random_address);
229 #ifdef ENABLE_LE_CENTRAL
230 // called from test/ble_client/advertising_data_parser.c
231 void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
232 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
233 static hci_connection_t * gap_get_outgoing_le_connection(void);
234 static void hci_le_scan_stop(void);
235 #endif
236 #ifdef ENABLE_LE_PERIPHERAL
237 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
238 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle);
239 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
240 #endif /* ENABLE_LE_PERIPHERAL */
241 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
242 static hci_iso_stream_t * hci_iso_stream_create(hci_iso_type_t iso_type, hci_iso_stream_state_t state, uint8_t group_id, uint8_t stream_id);
243 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream);
244 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id);
245 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle);
246 static void hci_iso_stream_requested_finalize(uint8_t big_handle);
247 static void hci_iso_stream_requested_confirm(uint8_t big_handle);
248 static void hci_iso_packet_handler(hci_iso_stream_t *iso_stream, uint8_t *packet, uint16_t size);
249 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle);
250 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id);
251 static void hci_iso_notify_can_send_now(void);
252 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status);
253 static void hci_emit_big_terminated(const le_audio_big_t * big);
254 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status);
255 static void hci_emit_big_sync_stopped(uint8_t big_handle);
256 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status);
257 static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status);
258 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle);
259 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
260 #endif /* ENABLE_BLE */
261 
262 // the STACK is here
263 #ifndef HAVE_MALLOC
264 static hci_stack_t   hci_stack_static;
265 #endif
266 static hci_stack_t * hci_stack = NULL;
267 
268 #ifdef ENABLE_CLASSIC
269 // default name
270 static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
271 
272 // test helper
273 static uint8_t disable_l2cap_timeouts = 0;
274 #endif
275 
276 // reset connection state on create and on reconnect
277 // don't overwrite addr, con handle, role
278 static void hci_connection_init(hci_connection_t * conn){
279     conn->authentication_flags = AUTH_FLAG_NONE;
280     conn->bonding_flags = 0;
281     conn->requested_security_level = LEVEL_0;
282     conn->link_key_type = INVALID_LINK_KEY;
283 #ifdef ENABLE_CLASSIC
284     conn->request_role = HCI_ROLE_INVALID;
285     conn->sniff_subrating_max_latency = 0xffff;
286     conn->qos_service_type = HCI_SERVICE_TYPE_INVALID;
287     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
288     btstack_run_loop_set_timer_context(&conn->timeout, conn);
289     hci_connection_timestamp(conn);
290 #endif
291     conn->acl_recombination_length = 0;
292     conn->acl_recombination_pos = 0;
293     conn->num_packets_sent = 0;
294 
295     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
296 #ifdef ENABLE_BLE
297     conn->le_phy_update_all_phys = 0xff;
298 #endif
299 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
300     conn->le_max_tx_octets = 27;
301 #endif
302 #ifdef ENABLE_CLASSIC_PAIRING_OOB
303     conn->classic_oob_c_192 = NULL;
304     conn->classic_oob_r_192 = NULL;
305     conn->classic_oob_c_256 = NULL;
306     conn->classic_oob_r_256 = NULL;
307 #endif
308 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
309     conn->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
310     conn->le_past_advertising_handle = 0xff;
311 #endif
312 }
313 
314 /**
315  * create connection for given address
316  *
317  * @return connection OR NULL, if no memory left
318  */
319 static hci_connection_t *
320 create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type, hci_role_t role) {
321     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
322 
323     hci_connection_t * conn = btstack_memory_hci_connection_get();
324     if (!conn) return NULL;
325     hci_connection_init(conn);
326 
327     bd_addr_copy(conn->address, addr);
328     conn->address_type = addr_type;
329     conn->con_handle = HCI_CON_HANDLE_INVALID;
330     conn->role = role;
331     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
332 
333     return conn;
334 }
335 
336 
337 /**
338  * get le connection parameter range
339 *
340  * @return le connection parameter range struct
341  */
342 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
343     *range = hci_stack->le_connection_parameter_range;
344 }
345 
346 /**
347  * set le connection parameter range
348  *
349  */
350 
351 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
352     hci_stack->le_connection_parameter_range = *range;
353 }
354 
355 /**
356  * @brief Test if connection parameters are inside in existing rage
357  * @param conn_interval_min (unit: 1.25ms)
358  * @param conn_interval_max (unit: 1.25ms)
359  * @param conn_latency
360  * @param supervision_timeout (unit: 10ms)
361  * @return 1 if included
362  */
363 int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){
364     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
365     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
366 
367     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
368     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
369 
370     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
371     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
372 
373     return 1;
374 }
375 
376 /**
377  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
378  * @note: default: 1
379  * @param max_peripheral_connections
380  */
381 #ifdef ENABLE_LE_PERIPHERAL
382 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
383     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
384 }
385 #endif
386 
387 /**
388  * get hci connections iterator
389  *
390  * @return hci connections iterator
391  */
392 
393 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
394     btstack_linked_list_iterator_init(it, &hci_stack->connections);
395 }
396 
397 /**
398  * get connection for a given handle
399  *
400  * @return connection OR NULL, if not found
401  */
402 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
403     btstack_linked_list_iterator_t it;
404     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
405     while (btstack_linked_list_iterator_has_next(&it)){
406         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
407         if ( item->con_handle == con_handle ) {
408             return item;
409         }
410     }
411     return NULL;
412 }
413 
414 /**
415  * get connection for given address
416  *
417  * @return connection OR NULL, if not found
418  */
419 hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
420     btstack_linked_list_iterator_t it;
421     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
422     while (btstack_linked_list_iterator_has_next(&it)){
423         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
424         if (connection->address_type != addr_type)  continue;
425         if (memcmp(addr, connection->address, 6) != 0) continue;
426         return connection;
427     }
428     return NULL;
429 }
430 
431 #ifdef ENABLE_CLASSIC
432 
433 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
434     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
435 }
436 
437 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
438     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
439 }
440 
441 #ifdef ENABLE_SCO_OVER_HCI
442 static int hci_number_sco_connections(void){
443     int connections = 0;
444     btstack_linked_list_iterator_t it;
445     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
446     while (btstack_linked_list_iterator_has_next(&it)){
447         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
448         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
449         connections++;
450     }
451     return connections;
452 }
453 #endif
454 
455 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
456     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
457 #ifdef HAVE_EMBEDDED_TICK
458     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
459         // connections might be timed out
460         hci_emit_l2cap_check_timeout(connection);
461     }
462 #else
463     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
464         // connections might be timed out
465         hci_emit_l2cap_check_timeout(connection);
466     }
467 #endif
468 }
469 
470 static void hci_connection_timestamp(hci_connection_t *connection){
471 #ifdef HAVE_EMBEDDED_TICK
472     connection->timestamp = btstack_run_loop_embedded_get_ticks();
473 #else
474     connection->timestamp = btstack_run_loop_get_time_ms();
475 #endif
476 }
477 
478 /**
479  * add authentication flags and reset timer
480  * @note: assumes classic connection
481  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
482  */
483 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
484     bd_addr_t addr;
485     reverse_bd_addr(bd_addr, addr);
486     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
487     if (conn) {
488         connectionSetAuthenticationFlags(conn, flags);
489         hci_connection_timestamp(conn);
490     }
491 }
492 
493 static bool hci_pairing_active(hci_connection_t * hci_connection){
494     return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0;
495 }
496 
497 static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){
498     if (hci_pairing_active(hci_connection)) return;
499     if (ssp){
500         hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE;
501     } else {
502         hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE;
503     }
504     // if we are initiator, we have sent an HCI Authenticate Request
505     bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0;
506 
507     // if we are responder, use minimal service security level as required level
508     if (!initiator){
509         hci_connection->requested_security_level = (gap_security_level_t) btstack_max((uint32_t) hci_connection->requested_security_level, (uint32_t) hci_stack->gap_minimal_service_security_level);
510     }
511 
512     log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level);
513 
514     uint8_t event[12];
515     event[0] = GAP_EVENT_PAIRING_STARTED;
516     event[1] = 10;
517     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
518     reverse_bd_addr(hci_connection->address, &event[4]);
519     event[10] = (uint8_t) ssp;
520     event[11] = (uint8_t) initiator;
521     hci_emit_event(event, sizeof(event), 1);
522 }
523 
524 static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){
525     hci_connection->requested_security_level = LEVEL_0;
526     if (!hci_pairing_active(hci_connection)) return;
527     hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK;
528 #ifdef ENABLE_CLASSIC_PAIRING_OOB
529     hci_connection->classic_oob_c_192 = NULL;
530     hci_connection->classic_oob_r_192 = NULL;
531     hci_connection->classic_oob_c_256 = NULL;
532     hci_connection->classic_oob_r_256 = NULL;
533 #endif
534     log_info("pairing complete, status %02x", status);
535 
536     uint8_t event[11];
537     event[0] = GAP_EVENT_PAIRING_COMPLETE;
538     event[1] = 9;
539     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
540     reverse_bd_addr(hci_connection->address, &event[4]);
541     event[10] = status;
542     hci_emit_event(event, sizeof(event), 1);
543 
544     // emit dedicated bonding done on failure, otherwise verify that connection can be encrypted
545     if ((status != ERROR_CODE_SUCCESS) && ((hci_connection->bonding_flags & BONDING_DEDICATED) != 0)){
546         hci_connection->bonding_flags &= ~BONDING_DEDICATED;
547         hci_connection->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
548         hci_connection->bonding_status = status;
549     }
550 }
551 
552 bool hci_authentication_active_for_handle(hci_con_handle_t handle){
553     hci_connection_t * conn = hci_connection_for_handle(handle);
554     if (!conn) return false;
555     return hci_pairing_active(conn);
556 }
557 
558 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
559     if (!hci_stack->link_key_db) return;
560     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
561     hci_stack->link_key_db->delete_link_key(addr);
562 }
563 
564 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
565     if (!hci_stack->link_key_db) return;
566     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
567     hci_stack->link_key_db->put_link_key(addr, link_key, type);
568 }
569 
570 bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
571 	if (!hci_stack->link_key_db) return false;
572 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
573 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
574 	return result;
575 }
576 
577 void gap_delete_all_link_keys(void){
578     bd_addr_t  addr;
579     link_key_t link_key;
580     link_key_type_t type;
581     btstack_link_key_iterator_t it;
582     int ok = gap_link_key_iterator_init(&it);
583     if (!ok) {
584         log_error("could not initialize iterator");
585         return;
586     }
587     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
588         gap_drop_link_key_for_bd_addr(addr);
589     }
590     gap_link_key_iterator_done(&it);
591 }
592 
593 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
594     if (!hci_stack->link_key_db) return 0;
595     if (!hci_stack->link_key_db->iterator_init) return 0;
596     return hci_stack->link_key_db->iterator_init(it);
597 }
598 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){
599     if (!hci_stack->link_key_db) return 0;
600     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
601 }
602 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
603     if (!hci_stack->link_key_db) return;
604     hci_stack->link_key_db->iterator_done(it);
605 }
606 #endif
607 
608 bool hci_is_le_connection_type(bd_addr_type_t address_type){
609     switch (address_type){
610         case BD_ADDR_TYPE_LE_PUBLIC:
611         case BD_ADDR_TYPE_LE_RANDOM:
612         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
613         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
614             return true;
615         default:
616             return false;
617     }
618 }
619 
620 bool hci_is_le_identity_address_type(bd_addr_type_t address_type){
621     switch (address_type){
622         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
623         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
624             return true;
625         default:
626             return false;
627     }
628 }
629 
630 static bool hci_is_le_connection(hci_connection_t * connection){
631     return hci_is_le_connection_type(connection->address_type);
632 }
633 
634 /**
635  * count connections
636  */
637 static int nr_hci_connections(void){
638     int count = 0;
639     btstack_linked_item_t *it;
640     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
641         count++;
642     }
643     return count;
644 }
645 
646 uint16_t hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
647 
648     unsigned int num_packets_sent_classic = 0;
649     unsigned int num_packets_sent_le = 0;
650 
651     btstack_linked_item_t *it;
652     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
653         hci_connection_t * connection = (hci_connection_t *) it;
654         if (hci_is_le_connection(connection)){
655             num_packets_sent_le += connection->num_packets_sent;
656         }
657         if (connection->address_type == BD_ADDR_TYPE_ACL){
658             num_packets_sent_classic += connection->num_packets_sent;
659         }
660     }
661     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
662     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
663     int free_slots_le = 0;
664 
665     if (free_slots_classic < 0){
666         log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num);
667         return 0;
668     }
669 
670     if (hci_stack->le_acl_packets_total_num){
671         // if we have LE slots, they are used
672         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
673         if (free_slots_le < 0){
674             log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num);
675             return 0;
676         }
677     } else {
678         // otherwise, classic slots are used for LE, too
679         free_slots_classic -= num_packets_sent_le;
680         if (free_slots_classic < 0){
681             log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num);
682             return 0;
683         }
684     }
685 
686     switch (address_type){
687         case BD_ADDR_TYPE_UNKNOWN:
688             log_error("hci_number_free_acl_slots: unknown address type");
689             return 0;
690 
691         case BD_ADDR_TYPE_ACL:
692             return (uint16_t) free_slots_classic;
693 
694         default:
695            if (hci_stack->le_acl_packets_total_num > 0){
696                return (uint16_t) free_slots_le;
697            }
698            return (uint16_t) free_slots_classic;
699     }
700 }
701 
702 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
703     // get connection type
704     hci_connection_t * connection = hci_connection_for_handle(con_handle);
705     if (!connection){
706         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
707         return 0;
708     }
709     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
710 }
711 
712 #ifdef ENABLE_CLASSIC
713 static int hci_number_free_sco_slots(void){
714     unsigned int num_sco_packets_sent  = 0;
715     btstack_linked_item_t *it;
716     if (hci_stack->synchronous_flow_control_enabled){
717         // explicit flow control
718         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
719             hci_connection_t * connection = (hci_connection_t *) it;
720             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
721             num_sco_packets_sent += connection->num_packets_sent;
722         }
723         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
724             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
725             return 0;
726         }
727         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
728     } else {
729         // implicit flow control
730         int num_ready = 0;
731         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
732             hci_connection_t * connection = (hci_connection_t *) it;
733             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
734             if (connection->sco_tx_ready == 0) continue;
735             num_ready++;
736         }
737         return num_ready;
738     }
739 }
740 #endif
741 
742 // only used to send HCI Host Number Completed Packets
743 static int hci_can_send_comand_packet_transport(void){
744     if (hci_stack->hci_packet_buffer_reserved) return 0;
745 
746     // check for async hci transport implementations
747     if (hci_stack->hci_transport->can_send_packet_now){
748         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
749             return 0;
750         }
751     }
752     return 1;
753 }
754 
755 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
756 bool hci_can_send_command_packet_now(void){
757     if (hci_can_send_comand_packet_transport() == 0) return false;
758     return hci_stack->num_cmd_packets > 0u;
759 }
760 
761 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
762     // check for async hci transport implementations
763     if (!hci_stack->hci_transport->can_send_packet_now) return true;
764     return hci_stack->hci_transport->can_send_packet_now(packet_type);
765 }
766 
767 static bool hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
768     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
769     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
770 }
771 
772 bool hci_can_send_acl_le_packet_now(void){
773     if (hci_stack->hci_packet_buffer_reserved) return false;
774     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
775 }
776 
777 bool hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
778     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
779     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
780 }
781 
782 bool hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
783     if (hci_stack->hci_packet_buffer_reserved) return false;
784     return hci_can_send_prepared_acl_packet_now(con_handle);
785 }
786 
787 #ifdef ENABLE_CLASSIC
788 bool hci_can_send_acl_classic_packet_now(void){
789     if (hci_stack->hci_packet_buffer_reserved) return false;
790     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
791 }
792 
793 bool hci_can_send_prepared_sco_packet_now(void){
794     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return false;
795     if (hci_have_usb_transport()){
796         return hci_stack->sco_can_send_now;
797     } else {
798         return hci_number_free_sco_slots() > 0;
799     }
800 }
801 
802 bool hci_can_send_sco_packet_now(void){
803     if (hci_stack->hci_packet_buffer_reserved) return false;
804     return hci_can_send_prepared_sco_packet_now();
805 }
806 
807 void hci_request_sco_can_send_now_event(void){
808     hci_stack->sco_waiting_for_can_send_now = 1;
809     hci_notify_if_sco_can_send_now();
810 }
811 #endif
812 
813 // used for internal checks in l2cap.c
814 bool hci_is_packet_buffer_reserved(void){
815     return hci_stack->hci_packet_buffer_reserved;
816 }
817 
818 void hci_reserve_packet_buffer(void){
819     btstack_assert(hci_stack->hci_packet_buffer_reserved == false);
820     hci_stack->hci_packet_buffer_reserved = true;
821 }
822 
823 void hci_release_packet_buffer(void){
824     btstack_assert(hci_stack->hci_packet_buffer_reserved);
825     hci_stack->hci_packet_buffer_reserved = false;
826     hci_emit_transport_packet_sent();
827 }
828 
829 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
830 static int hci_transport_synchronous(void){
831     return hci_stack->hci_transport->can_send_packet_now == NULL;
832 }
833 
834 // used for debugging
835 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
836 static void hci_controller_dump_packets(void){
837     // format: "{handle:04x}:{count:02d} "
838     char summaries[3][7 * 8 + 1];
839     uint16_t totals[3];
840     uint8_t index;
841     for (index = 0 ; index < 3 ; index++){
842         summaries[index][0] = 0;
843         totals[index] = 0;
844     }
845     btstack_linked_item_t *it;
846     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
847         hci_connection_t * connection = (hci_connection_t *) it;
848         switch (connection->address_type){
849             case BD_ADDR_TYPE_ACL:
850                 index = 0;
851                 break;
852             case BD_ADDR_TYPE_SCO:
853                 index = 2;
854                 break;
855             default:
856                 index = 1;
857                 break;
858         }
859         totals[index] += connection->num_packets_sent;
860         char item_text[10];
861         sprintf(item_text, "%04x:%02d ", connection->con_handle,connection->num_packets_sent);
862         btstack_strcat(summaries[index], sizeof(summaries[0]), item_text);
863     }
864     for (index = 0 ; index < 3 ; index++){
865         if (summaries[index][0] == 0){
866             summaries[index][0] = '-';
867             summaries[index][1] = 0;
868         }
869     }
870     log_info("Controller ACL BR/EDR: %s total %u / LE: %s total %u / SCO: %s total %u", summaries[0], totals[0], summaries[1], totals[1], summaries[2], totals[2]);
871 }
872 #endif
873 
874 static uint8_t hci_send_acl_packet_fragments(hci_connection_t *connection){
875 
876     // log_info("hci_send_acl_packet_fragments  %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle);
877 
878     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
879     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
880     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
881         max_acl_data_packet_length = hci_stack->le_data_packets_length;
882     }
883 
884 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
885     if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){
886         max_acl_data_packet_length = connection->le_max_tx_octets;
887     }
888 #endif
889 
890     log_debug("hci_send_acl_packet_fragments entered");
891 
892     uint8_t status = ERROR_CODE_SUCCESS;
893     // multiple packets could be send on a synchronous HCI transport
894     while (true){
895 
896         log_debug("hci_send_acl_packet_fragments loop entered");
897 
898         // get current data
899         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
900         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
901         bool more_fragments = false;
902 
903         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
904         if (current_acl_data_packet_length > max_acl_data_packet_length){
905             more_fragments = true;
906             current_acl_data_packet_length = max_acl_data_packet_length & (~(HCI_ACL_CHUNK_SIZE_ALIGNMENT-1));
907         }
908 
909         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
910         if (acl_header_pos > 0u){
911             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
912             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
913             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
914         }
915 
916         // update header len
917         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
918 
919         // count packet
920         connection->num_packets_sent++;
921         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
922 
923         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
924         if (more_fragments){
925             // update start of next fragment to send
926             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
927         } else {
928             // done
929             hci_stack->acl_fragmentation_pos = 0;
930             hci_stack->acl_fragmentation_total_size = 0;
931         }
932 
933         // send packet
934         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
935         const int size = current_acl_data_packet_length + 4;
936         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
937         hci_stack->acl_fragmentation_tx_active = 1;
938         int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
939         if (err != 0){
940             // no error from HCI Transport expected
941             status = ERROR_CODE_HARDWARE_FAILURE;
942         }
943 
944 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
945         hci_controller_dump_packets();
946 #endif
947 
948         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
949 
950         // done yet?
951         if (!more_fragments) break;
952 
953         // can send more?
954         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return status;
955     }
956 
957     log_debug("hci_send_acl_packet_fragments loop over");
958 
959     // release buffer now for synchronous transport
960     if (hci_transport_synchronous()){
961         hci_stack->acl_fragmentation_tx_active = 0;
962         hci_release_packet_buffer();
963     }
964 
965     return status;
966 }
967 
968 // pre: caller has reserved the packet buffer
969 uint8_t hci_send_acl_packet_buffer(int size){
970     btstack_assert(hci_stack->hci_packet_buffer_reserved);
971 
972     uint8_t * packet = hci_stack->hci_packet_buffer;
973     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
974 
975     hci_connection_t *connection = hci_connection_for_handle( con_handle);
976     if (!connection) {
977         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
978         hci_release_packet_buffer();
979         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
980     }
981 
982     // check for free places on Bluetooth module
983     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
984         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
985         hci_release_packet_buffer();
986         return BTSTACK_ACL_BUFFERS_FULL;
987     }
988 
989 #ifdef ENABLE_CLASSIC
990     hci_connection_timestamp(connection);
991 #endif
992 
993     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
994 
995     // setup data
996     hci_stack->acl_fragmentation_total_size = size;
997     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
998 
999     return hci_send_acl_packet_fragments(connection);
1000 }
1001 
1002 #ifdef ENABLE_CLASSIC
1003 // pre: caller has reserved the packet buffer
1004 uint8_t hci_send_sco_packet_buffer(int size){
1005     btstack_assert(hci_stack->hci_packet_buffer_reserved);
1006 
1007     uint8_t * packet = hci_stack->hci_packet_buffer;
1008 
1009     // skip checks in loopback mode
1010     if (!hci_stack->loopback_mode){
1011         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
1012 
1013         // check for free places on Bluetooth module
1014         if (!hci_can_send_prepared_sco_packet_now()) {
1015             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
1016             hci_release_packet_buffer();
1017             return BTSTACK_ACL_BUFFERS_FULL;
1018         }
1019 
1020         // track send packet in connection struct
1021         hci_connection_t *connection = hci_connection_for_handle( con_handle);
1022         if (!connection) {
1023             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
1024             hci_release_packet_buffer();
1025             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1026         }
1027 
1028         if (hci_have_usb_transport()){
1029             // token used
1030             hci_stack->sco_can_send_now = false;
1031         } else {
1032             if (hci_stack->synchronous_flow_control_enabled){
1033                 connection->num_packets_sent++;
1034             } else {
1035                 connection->sco_tx_ready--;
1036             }
1037         }
1038     }
1039 
1040     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
1041 
1042 #ifdef HAVE_SCO_TRANSPORT
1043     hci_stack->sco_transport->send_packet(packet, size);
1044     hci_release_packet_buffer();
1045     hci_emit_transport_packet_sent();
1046 
1047     return 0;
1048 #else
1049     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
1050     if (hci_transport_synchronous()){
1051         hci_release_packet_buffer();
1052     }
1053 
1054     if (err != 0){
1055         return ERROR_CODE_HARDWARE_FAILURE;
1056     }
1057     return ERROR_CODE_SUCCESS;
1058 #endif
1059 }
1060 #endif
1061 
1062 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
1063 static uint8_t hci_send_iso_packet_fragments(void){
1064 
1065     uint16_t max_iso_data_packet_length = hci_stack->le_iso_packets_length;
1066     uint8_t status = ERROR_CODE_SUCCESS;
1067     // multiple packets could be send on a synchronous HCI transport
1068     while (true){
1069 
1070         // get current data
1071         const uint16_t iso_header_pos = hci_stack->iso_fragmentation_pos - 4u;
1072         int current_iso_data_packet_length = hci_stack->iso_fragmentation_total_size - hci_stack->iso_fragmentation_pos;
1073         bool more_fragments = false;
1074 
1075         // if ISO packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
1076         if (current_iso_data_packet_length > max_iso_data_packet_length){
1077             more_fragments = true;
1078             current_iso_data_packet_length = max_iso_data_packet_length;
1079         }
1080 
1081         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
1082         uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1083         uint8_t pb_flags;
1084         if (iso_header_pos == 0u){
1085             // first fragment, keep TS field
1086             pb_flags = more_fragments ? 0x00 : 0x02;
1087             handle_and_flags = (handle_and_flags & 0x4fffu) | (pb_flags << 12u);
1088         } else {
1089             // later fragment, drop TS field
1090             pb_flags = more_fragments ? 0x01 : 0x03;
1091             handle_and_flags = (handle_and_flags & 0x0fffu) | (pb_flags << 12u);
1092         }
1093         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos, handle_and_flags);
1094 
1095         // update header len
1096         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos + 2u, current_iso_data_packet_length);
1097 
1098         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
1099         if (more_fragments){
1100             // update start of next fragment to send
1101             hci_stack->iso_fragmentation_pos += current_iso_data_packet_length;
1102         } else {
1103             // done
1104             hci_stack->iso_fragmentation_pos = 0;
1105             hci_stack->iso_fragmentation_total_size = 0;
1106         }
1107 
1108         // send packet
1109         uint8_t * packet = &hci_stack->hci_packet_buffer[iso_header_pos];
1110         const int size = current_iso_data_packet_length + 4;
1111         hci_dump_packet(HCI_ISO_DATA_PACKET, 0, packet, size);
1112         hci_stack->iso_fragmentation_tx_active = true;
1113         int err = hci_stack->hci_transport->send_packet(HCI_ISO_DATA_PACKET, packet, size);
1114         if (err != 0){
1115             // no error from HCI Transport expected
1116             status = ERROR_CODE_HARDWARE_FAILURE;
1117         }
1118 
1119         // done yet?
1120         if (!more_fragments) break;
1121 
1122         // can send more?
1123         if (!hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)) return false;
1124     }
1125 
1126     // release buffer now for synchronous transport
1127     if (hci_transport_synchronous()){
1128         hci_stack->iso_fragmentation_tx_active = false;
1129         hci_release_packet_buffer();
1130         hci_emit_transport_packet_sent();
1131     }
1132 
1133     return status;
1134 }
1135 
1136 uint8_t hci_send_iso_packet_buffer(uint16_t size){
1137     btstack_assert(hci_stack->hci_packet_buffer_reserved);
1138 
1139     hci_con_handle_t con_handle = (hci_con_handle_t) little_endian_read_16(hci_stack->hci_packet_buffer, 0) & 0xfff;
1140     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(con_handle);
1141     if (iso_stream == NULL){
1142         hci_release_packet_buffer();
1143         hci_iso_notify_can_send_now();
1144         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1145     }
1146 
1147     // TODO: check for space on controller
1148 
1149     // skip iso packets if needed
1150     if (iso_stream->num_packets_to_skip > 0){
1151         iso_stream->num_packets_to_skip--;
1152         // pretend it was processed and trigger next one
1153         hci_release_packet_buffer();
1154         hci_iso_notify_can_send_now();
1155         return ERROR_CODE_SUCCESS;
1156     }
1157 
1158     // track outgoing packet sent
1159     log_info("Outgoing ISO packet for con handle 0x%04x", con_handle);
1160     iso_stream->num_packets_sent++;
1161 
1162     // setup data
1163     hci_stack->iso_fragmentation_total_size = size;
1164     hci_stack->iso_fragmentation_pos = 4;   // start of L2CAP packet
1165 
1166     return hci_send_iso_packet_fragments();
1167 }
1168 #endif
1169 
1170 static void acl_handler(uint8_t *packet, uint16_t size){
1171 
1172     // get info
1173     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
1174     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
1175     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
1176     uint16_t acl_length         = READ_ACL_LENGTH(packet);
1177 
1178     // ignore non-registered handle
1179     if (!conn){
1180         log_error("acl_handler called with non-registered handle %u!" , con_handle);
1181         return;
1182     }
1183 
1184     // assert packet is complete
1185     if ((acl_length + 4u) != size){
1186         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
1187         return;
1188     }
1189 
1190 #ifdef ENABLE_CLASSIC
1191     // update idle timestamp
1192     hci_connection_timestamp(conn);
1193 #endif
1194 
1195 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1196     hci_stack->host_completed_packets = 1;
1197     conn->num_packets_completed++;
1198 #endif
1199 
1200     // handle different packet types
1201     switch (acl_flags & 0x03u) {
1202 
1203         case 0x01: // continuation fragment
1204 
1205             // sanity checks
1206             if (conn->acl_recombination_pos == 0u) {
1207                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
1208                 return;
1209             }
1210             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
1211                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
1212                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
1213                 conn->acl_recombination_pos = 0;
1214                 return;
1215             }
1216 
1217             // append fragment payload (header already stored)
1218             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
1219                          &packet[4], acl_length);
1220             conn->acl_recombination_pos += acl_length;
1221 
1222             // forward complete L2CAP packet if complete.
1223             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
1224                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
1225                 // reset recombination buffer
1226                 conn->acl_recombination_length = 0;
1227                 conn->acl_recombination_pos = 0;
1228             }
1229             break;
1230 
1231         case 0x02: { // first fragment
1232 
1233             // sanity check
1234             if (conn->acl_recombination_pos) {
1235                 // we just received the first fragment, but still have data. Only warn if the packet wasn't a flushable packet
1236                 if ((conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE+1] >> 4) != 0x02){
1237                     log_error( "ACL First Fragment but %u bytes in buffer for handle 0x%02x, dropping stale fragments", conn->acl_recombination_pos, con_handle);
1238                 }
1239                 conn->acl_recombination_pos = 0;
1240             }
1241 
1242             // peek into L2CAP packet!
1243             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
1244 
1245             // compare fragment size to L2CAP packet size
1246             if (acl_length >= (l2cap_length + 4u)){
1247                 // forward fragment as L2CAP packet
1248                 hci_emit_acl_packet(packet, acl_length + 4u);
1249             } else {
1250 
1251                 if (acl_length > HCI_ACL_BUFFER_SIZE){
1252                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
1253                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
1254                     return;
1255                 }
1256 
1257                 // store first fragment and tweak acl length for complete package
1258                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
1259                              packet, acl_length + 4u);
1260                 conn->acl_recombination_pos    = acl_length + 4u;
1261                 conn->acl_recombination_length = l2cap_length;
1262                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
1263             }
1264             break;
1265 
1266         }
1267         default:
1268             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
1269             return;
1270     }
1271 
1272     // execute main loop
1273     hci_run();
1274 }
1275 
1276 static void hci_connection_stop_timer(hci_connection_t * conn){
1277     btstack_run_loop_remove_timer(&conn->timeout);
1278 #ifdef ENABLE_CLASSIC
1279     btstack_run_loop_remove_timer(&conn->timeout_sco);
1280 #endif
1281 }
1282 
1283 static void hci_shutdown_connection(hci_connection_t *conn){
1284     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
1285 
1286 #ifdef ENABLE_CLASSIC
1287 #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1288     bd_addr_type_t addr_type = conn->address_type;
1289 #endif
1290 #ifdef HAVE_SCO_TRANSPORT
1291     hci_con_handle_t con_handle = conn->con_handle;
1292 #endif
1293 #endif
1294 
1295     hci_connection_stop_timer(conn);
1296 
1297     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1298     btstack_memory_hci_connection_free( conn );
1299 
1300     // now it's gone
1301     hci_emit_nr_connections_changed();
1302 
1303 #ifdef ENABLE_CLASSIC
1304 #ifdef ENABLE_SCO_OVER_HCI
1305     // update SCO
1306     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1307         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1308     }
1309 #endif
1310 #ifdef HAVE_SCO_TRANSPORT
1311     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1312         hci_stack->sco_transport->close(con_handle);
1313     }
1314 #endif
1315 #endif
1316 }
1317 
1318 #ifdef ENABLE_CLASSIC
1319 
1320 static const uint16_t hci_acl_packet_type_sizes[] = {
1321     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
1322     HCI_ACL_DH1_SIZE, 0, 0, 0,
1323     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
1324     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
1325 };
1326 static const uint8_t hci_acl_packet_type_feature_requirement_bit[] = {
1327      0, // 3 slot packets
1328      1, // 5 slot packets
1329     25, // EDR 2 mpbs
1330     26, // EDR 3 mbps
1331     39, // 3 slot EDR packts
1332     40, // 5 slot EDR packet
1333 };
1334 static const uint16_t hci_acl_packet_type_feature_packet_mask[] = {
1335     0x0f00, // 3 slot packets
1336     0xf000, // 5 slot packets
1337     0x1102, // EDR 2 mpbs
1338     0x2204, // EDR 3 mbps
1339     0x0300, // 3 slot EDR packts
1340     0x3000, // 5 slot EDR packet
1341 };
1342 
1343 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
1344     // enable packet types based on size
1345     uint16_t packet_types = 0;
1346     unsigned int i;
1347     for (i=0;i<16;i++){
1348         if (hci_acl_packet_type_sizes[i] == 0) continue;
1349         if (hci_acl_packet_type_sizes[i] <= buffer_size){
1350             packet_types |= 1 << i;
1351         }
1352     }
1353     // disable packet types due to missing local supported features
1354     for (i=0;i<sizeof(hci_acl_packet_type_feature_requirement_bit); i++){
1355         unsigned int bit_idx = hci_acl_packet_type_feature_requirement_bit[i];
1356         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1357         if (feature_set) continue;
1358         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, hci_acl_packet_type_feature_packet_mask[i]);
1359         packet_types &= ~hci_acl_packet_type_feature_packet_mask[i];
1360     }
1361     return packet_types;
1362 }
1363 
1364 uint16_t hci_usable_acl_packet_types(void){
1365     uint16_t active_packet_types = (hci_stack->usable_packet_types_acl &  hci_stack->enabled_packet_types_acl);
1366     // flip bits for "may not be used"
1367     return  active_packet_types ^ 0x3306;
1368 }
1369 
1370 void hci_enable_acl_packet_types(uint16_t packet_types){
1371     hci_stack->enabled_packet_types_acl = packet_types;
1372 }
1373 
1374 static const struct {
1375     uint8_t feature_index;
1376     uint16_t feature_packet_mask;
1377 } hci_sco_packet_type_feature_requirements[] = {
1378         { 12, SCO_PACKET_TYPES_HV2 },                           // HV2 packets
1379         { 13, SCO_PACKET_TYPES_HV3 },                           // HV3 packets
1380         { 31, SCO_PACKET_TYPES_ESCO },                          // eSCO links (EV3 packets)
1381         { 32, SCO_PACKET_TYPES_EV4 },                           // EV4 packets
1382         { 45, SCO_PACKET_TYPES_2EV3 | SCO_PACKET_TYPES_2EV5 },  // EDR eSCO 2 Mb/s
1383         { 46, SCO_PACKET_TYPES_3EV3 | SCO_PACKET_TYPES_3EV5 },  // EDR eSCO 3 Mb/s
1384         { 47, SCO_PACKET_TYPES_2EV5 | SCO_PACKET_TYPES_3EV5 },  // 3-slot EDR eSCO packets, 2-EV3/3-EV3 use single slot
1385 };
1386 
1387 // map packet types to payload length, prefer eSCO over SCO and large over small packets
1388 static const struct {
1389     uint16_t type;
1390     uint16_t payload_length;
1391 } hci_sco_packet_type_to_payload_length[] = {
1392         {SCO_PACKET_TYPES_3EV5, HCI_SCO_3EV5_SIZE}, // 540
1393         {SCO_PACKET_TYPES_2EV5, HCI_SCO_2EV5_SIZE}, // 360
1394         {SCO_PACKET_TYPES_EV5,  HCI_SCO_EV5_SIZE},  // 180
1395         {SCO_PACKET_TYPES_EV4,  HCI_SCO_EV4_SIZE},  // 120
1396         {SCO_PACKET_TYPES_3EV3, HCI_SCO_3EV3_SIZE}, //  90
1397         {SCO_PACKET_TYPES_2EV3, HCI_SCO_2EV3_SIZE}, //  60
1398         {SCO_PACKET_TYPES_EV3,  HCI_SCO_EV3_SIZE},  //  30
1399         {SCO_PACKET_TYPES_HV3,  HCI_SCO_HV3_SIZE},  //  30
1400         {SCO_PACKET_TYPES_HV2,  HCI_SCO_HV2_SIZE},  //  20
1401         {SCO_PACKET_TYPES_HV1,  HCI_SCO_HV1_SIZE}   //  10
1402 };
1403 
1404 static uint16_t hci_sco_packet_types_for_features(const uint8_t * local_supported_features){
1405     uint16_t packet_types = SCO_PACKET_TYPES_ALL;
1406     unsigned int i;
1407     // disable packet types due to missing local supported features
1408     for (i=0;i<(sizeof(hci_sco_packet_type_feature_requirements)/sizeof(hci_sco_packet_type_feature_requirements[0])); i++){
1409         unsigned int bit_idx = hci_sco_packet_type_feature_requirements[i].feature_index;
1410         bool feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1411         if (feature_set) continue;
1412         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, hci_sco_packet_type_feature_requirements[i].feature_packet_mask);
1413         packet_types &= ~hci_sco_packet_type_feature_requirements[i].feature_packet_mask;
1414     }
1415     return packet_types;
1416 }
1417 
1418 uint16_t hci_usable_sco_packet_types(void){
1419     return hci_stack->usable_packet_types_sco;
1420 }
1421 
1422 static uint16_t hci_sco_payload_length_for_packet_types(uint16_t packet_types){
1423     uint8_t i;
1424     for (i=0;i<sizeof(hci_sco_packet_type_to_payload_length)/sizeof(hci_sco_packet_type_to_payload_length[0]);i++){
1425         if ((hci_sco_packet_type_to_payload_length[i].type & packet_types) != 0){
1426             return hci_sco_packet_type_to_payload_length[i].payload_length;
1427         }
1428     }
1429     return 0;
1430 }
1431 
1432 #endif
1433 
1434 uint8_t* hci_get_outgoing_packet_buffer(void){
1435     // hci packet buffer is >= acl data packet length
1436     return hci_stack->hci_packet_buffer;
1437 }
1438 
1439 uint16_t hci_max_acl_data_packet_length(void){
1440     return hci_stack->acl_data_packet_length;
1441 }
1442 
1443 #ifdef ENABLE_CLASSIC
1444 bool hci_extended_sco_link_supported(void){
1445     // No. 31, byte 3, bit 7
1446     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
1447 }
1448 #endif
1449 
1450 bool hci_non_flushable_packet_boundary_flag_supported(void){
1451     // No. 54, byte 6, bit 6
1452     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
1453 }
1454 
1455 #ifdef ENABLE_CLASSIC
1456 static bool gap_ssp_supported(void){
1457     // No. 51, byte 6, bit 3
1458     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1459 }
1460 #endif
1461 
1462 bool hci_classic_supported(void){
1463 #ifdef ENABLE_CLASSIC
1464     // No. 37, byte 4, bit 5, = No BR/EDR Support
1465     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
1466 #else
1467     return false;
1468 #endif
1469 }
1470 
1471 bool hci_le_supported(void){
1472 #ifdef ENABLE_BLE
1473     // No. 37, byte 4, bit 6 = LE Supported (Controller)
1474     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1475 #else
1476     return false;
1477 #endif
1478 }
1479 
1480 static bool hci_command_supported(uint8_t command_index){
1481     return (hci_stack->local_supported_commands & (1LU << command_index)) != 0;
1482 }
1483 
1484 #ifdef ENABLE_BLE
1485 
1486 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1487 bool hci_le_extended_advertising_supported(void){
1488     return hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE);
1489 }
1490 #endif
1491 
1492 static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
1493     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
1494         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
1495     } else {
1496         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
1497     }
1498 }
1499 
1500 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
1501     *addr_type = hci_stack->le_own_addr_type;
1502     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
1503 }
1504 
1505 #ifdef ENABLE_LE_PERIPHERAL
1506 void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
1507     *addr_type = hci_stack->le_advertisements_own_addr_type;
1508     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
1509 };
1510 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1511 void gap_le_get_own_advertising_set_address(uint8_t * addr_type, bd_addr_t addr, uint8_t advertising_handle){
1512     if (advertising_handle == 0){
1513         gap_le_get_own_advertisements_address(addr_type, addr);
1514     } else {
1515         le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
1516         if (advertising_set != NULL){
1517             switch (advertising_set->extended_params.own_address_type){
1518                 case BD_ADDR_TYPE_LE_PUBLIC:
1519                     *addr_type = BD_ADDR_TYPE_LE_PUBLIC;
1520                     memcpy(addr, hci_stack->local_bd_addr, 6);
1521                     break;
1522                 case BD_ADDR_TYPE_LE_RANDOM:
1523                     *addr_type = BD_ADDR_TYPE_LE_RANDOM;
1524                     memcpy(addr, advertising_set->random_address, 6);
1525                     break;
1526                 case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
1527                 case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
1528                     // do nothing as random address was already set from enhanced connection complete
1529                     break;
1530                 default:
1531                     break;
1532             }
1533         }
1534     }
1535 };
1536 #endif
1537 #endif
1538 
1539 #ifdef ENABLE_LE_CENTRAL
1540 
1541 /**
1542  * @brief Get own addr type and address used for LE connections (Central)
1543  */
1544 void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
1545     *addr_type = hci_stack->le_connection_own_addr_type;
1546     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
1547 }
1548 
1549 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
1550 
1551     uint16_t offset = 3;
1552     uint8_t num_reports = packet[offset];
1553     offset += 1;
1554 
1555     uint16_t i;
1556     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1557     for (i=0; (i<num_reports) && (offset < size);i++){
1558         // sanity checks on data_length:
1559         uint8_t data_length = packet[offset + 8];
1560         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1561         if ((offset + 9u + data_length + 1u) > size)    return;
1562         // setup event
1563         uint8_t event_size = 10u + data_length;
1564         uint16_t pos = 0;
1565         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1566         event[pos++] = event_size;
1567         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1568         offset += 8;
1569         pos += 8;
1570         event[pos++] = packet[offset + 1 + data_length]; // rssi
1571         event[pos++] = data_length;
1572         offset++;
1573         (void)memcpy(&event[pos], &packet[offset], data_length);
1574         pos +=    data_length;
1575         offset += data_length + 1u; // rssi
1576         hci_emit_event(event, pos, 1);
1577     }
1578 }
1579 
1580 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1581 void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size) {
1582     uint16_t offset = 3;
1583     uint8_t num_reports = packet[offset++];
1584     uint8_t event[2 + 255]; // use upper bound to avoid var size automatic var
1585     uint8_t i;
1586     for (i=0; (i<num_reports) && (offset < size);i++){
1587         // sanity checks on data_length:
1588         uint16_t data_length = packet[offset + 23];
1589         if (data_length > LE_EXTENDED_ADVERTISING_DATA_SIZE) return;
1590         if ((offset + 24u + data_length) > size)    return;
1591         uint16_t event_type = little_endian_read_16(packet, offset);
1592         offset += 2;
1593         if ((event_type & 0x10) != 0) {
1594            // setup legacy event
1595             uint8_t legacy_event_type;
1596             switch (event_type){
1597                 case 0b0010011:
1598                     // ADV_IND
1599                     legacy_event_type = 0;
1600                     break;
1601                 case 0b0010101:
1602                     // ADV_DIRECT_IND
1603                     legacy_event_type = 1;
1604                     break;
1605                 case 0b0010010:
1606                     // ADV_SCAN_IND
1607                     legacy_event_type = 2;
1608                     break;
1609                 case 0b0010000:
1610                     // ADV_NONCONN_IND
1611                     legacy_event_type = 3;
1612                     break;
1613                 case 0b0011011:
1614                 case 0b0011010:
1615                     // SCAN_RSP
1616                     legacy_event_type = 4;
1617                     break;
1618                 default:
1619                     legacy_event_type = 0;
1620                     break;
1621             }
1622             uint16_t pos = 0;
1623             event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1624             event[pos++] = 10u + data_length;
1625             event[pos++] = legacy_event_type;
1626             // copy address type + address
1627             (void) memcpy(&event[pos], &packet[offset], 1 + 6);
1628             offset += 7;
1629             pos += 7;
1630             // skip primary_phy, secondary_phy, advertising_sid, tx_power
1631             offset += 4;
1632             // copy rssi
1633             event[pos++] = packet[offset++];
1634             // skip periodic advertising interval and direct address
1635             offset += 9;
1636             // copy data len + data;
1637             (void) memcpy(&event[pos], &packet[offset], 1 + data_length);
1638             pos    += 1 +data_length;
1639             offset += 1+ data_length;
1640             hci_emit_event(event, pos, 1);
1641         } else {
1642             event[0] = GAP_EVENT_EXTENDED_ADVERTISING_REPORT;
1643             uint8_t report_len = 24 + data_length;
1644             event[1] = report_len;
1645             little_endian_store_16(event, 2, event_type);
1646             memcpy(&event[4], &packet[offset], report_len);
1647             offset += report_len;
1648             hci_emit_event(event, 2 + report_len, 1);
1649         }
1650     }
1651 }
1652 #endif
1653 
1654 #endif
1655 #endif
1656 
1657 #ifdef ENABLE_BLE
1658 #ifdef ENABLE_LE_PERIPHERAL
1659 static void hci_update_advertisements_enabled_for_current_roles(void){
1660     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ENABLED) != 0){
1661         // get number of active le slave connections
1662         int num_slave_connections = 0;
1663         btstack_linked_list_iterator_t it;
1664         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
1665         while (btstack_linked_list_iterator_has_next(&it)){
1666             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
1667             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
1668             if (con->state != OPEN) continue;
1669             if (con->role  != HCI_ROLE_SLAVE) continue;
1670             if (!hci_is_le_connection(con)) continue;
1671             num_slave_connections++;
1672         }
1673         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1674         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1675     } else {
1676         hci_stack->le_advertisements_enabled_for_current_roles = false;
1677     }
1678 }
1679 #endif
1680 #endif
1681 
1682 #ifdef ENABLE_CLASSIC
1683 static void gap_run_set_local_name(void){
1684     hci_reserve_packet_buffer();
1685     uint8_t * packet = hci_stack->hci_packet_buffer;
1686     // construct HCI Command and send
1687     uint16_t opcode = hci_write_local_name.opcode;
1688     hci_stack->last_cmd_opcode = opcode;
1689     packet[0] = opcode & 0xff;
1690     packet[1] = opcode >> 8;
1691     packet[2] = DEVICE_NAME_LEN;
1692     memset(&packet[3], 0, DEVICE_NAME_LEN);
1693     uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1694     uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
1695     // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
1696     (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
1697     // expand '00:00:00:00:00:00' in name with bd_addr
1698     btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
1699     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1700 }
1701 
1702 static void gap_run_set_eir_data(void){
1703     hci_reserve_packet_buffer();
1704     uint8_t * packet = hci_stack->hci_packet_buffer;
1705     // construct HCI Command in-place and send
1706     uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1707     hci_stack->last_cmd_opcode = opcode;
1708     uint16_t offset = 0;
1709     packet[offset++] = opcode & 0xff;
1710     packet[offset++] = opcode >> 8;
1711     packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
1712     packet[offset++] = 0;  // FEC not required
1713     memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1714     if (hci_stack->eir_data){
1715         // copy items and expand '00:00:00:00:00:00' in name with bd_addr
1716         ad_context_t context;
1717         for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
1718             uint8_t data_type   = ad_iterator_get_data_type(&context);
1719             uint8_t size        = ad_iterator_get_data_len(&context);
1720             const uint8_t *data = ad_iterator_get_data(&context);
1721             // copy item
1722             packet[offset++] = size + 1;
1723             packet[offset++] = data_type;
1724             memcpy(&packet[offset], data, size);
1725             // update name item
1726             if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
1727                 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
1728             }
1729             offset += size;
1730         }
1731     } else {
1732         uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1733         uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
1734         packet[offset++] = bytes_to_copy + 1;
1735         packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1736         (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
1737         // expand '00:00:00:00:00:00' in name with bd_addr
1738         btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
1739     }
1740     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1741 }
1742 
1743 static void hci_run_gap_tasks_classic(void){
1744     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
1745         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
1746         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1747         return;
1748     }
1749     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_LOCAL_NAME) != 0) {
1750         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_LOCAL_NAME;
1751         gap_run_set_local_name();
1752         return;
1753     }
1754     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_EIR_DATA) != 0) {
1755         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_EIR_DATA;
1756         gap_run_set_eir_data();
1757         return;
1758     }
1759     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
1760         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
1761         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1762         return;
1763     }
1764     // write page scan activity
1765     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) {
1766         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
1767         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
1768         return;
1769     }
1770     // write page scan type
1771     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) {
1772         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE;
1773         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
1774         return;
1775     }
1776     // write page timeout
1777     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_TIMEOUT) != 0) {
1778         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_TIMEOUT;
1779         hci_send_cmd(&hci_write_page_timeout, hci_stack->page_timeout);
1780         return;
1781     }
1782     // send scan enable
1783     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_SCAN_ENABLE) != 0) {
1784         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_SCAN_ENABLE;
1785         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1786         return;
1787     }
1788     // send write scan activity
1789     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY) != 0) {
1790         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
1791         hci_send_cmd(&hci_write_inquiry_scan_activity, hci_stack->inquiry_scan_interval, hci_stack->inquiry_scan_window);
1792         return;
1793     }
1794     // send write inquiry transmit power level
1795     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL) != 0) {
1796         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
1797         hci_send_cmd(&hci_write_inquiry_transmit_power_level, hci_stack->inquiry_tx_power_level);
1798         return;
1799     }
1800 }
1801 #endif
1802 
1803 #ifndef HAVE_HOST_CONTROLLER_API
1804 
1805 static uint32_t hci_transport_uart_get_main_baud_rate(void){
1806     if (!hci_stack->config) return 0;
1807     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1808     // Limit baud rate for Broadcom chipsets to 3 mbps
1809     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
1810         baud_rate = 3000000;
1811     }
1812     return baud_rate;
1813 }
1814 
1815 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
1816     UNUSED(ds);
1817 
1818     switch (hci_stack->substate){
1819         case HCI_INIT_W4_SEND_RESET:
1820             log_info("Resend HCI Reset");
1821             hci_stack->substate = HCI_INIT_SEND_RESET;
1822             hci_stack->num_cmd_packets = 1;
1823             hci_run();
1824             break;
1825         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
1826             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
1827             if (hci_stack->hci_transport->reset_link){
1828                 hci_stack->hci_transport->reset_link();
1829             }
1830 
1831             /* fall through */
1832 
1833         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1834             log_info("Resend HCI Reset - CSR Warm Boot");
1835             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1836             hci_stack->num_cmd_packets = 1;
1837             hci_run();
1838             break;
1839         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1840             if (hci_stack->hci_transport->set_baudrate){
1841                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1842                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
1843                 hci_stack->hci_transport->set_baudrate(baud_rate);
1844             }
1845             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
1846             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1847                 if (hci_stack->hci_transport->reset_link){
1848                     log_info("Link Reset");
1849                     hci_stack->hci_transport->reset_link();
1850                 }
1851                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1852                 hci_run();
1853             }
1854             break;
1855         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1856             // otherwise continue
1857             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1858             hci_send_cmd(&hci_read_local_supported_commands);
1859             break;
1860         default:
1861             break;
1862     }
1863 }
1864 #endif
1865 
1866 static void hci_initializing_next_state(void){
1867     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
1868 }
1869 
1870 static void hci_init_done(void){
1871     // done. tell the app
1872     log_info("hci_init_done -> HCI_STATE_WORKING");
1873     hci_stack->state = HCI_STATE_WORKING;
1874     hci_emit_state();
1875 }
1876 
1877 // assumption: hci_can_send_command_packet_now() == true
1878 static void hci_initializing_run(void){
1879     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1880 
1881     if (!hci_can_send_command_packet_now()) return;
1882 
1883 #ifndef HAVE_HOST_CONTROLLER_API
1884     bool need_baud_change = hci_stack->config
1885             && hci_stack->chipset
1886             && hci_stack->chipset->set_baudrate_command
1887             && hci_stack->hci_transport->set_baudrate
1888             && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1889 #endif
1890 
1891     switch (hci_stack->substate){
1892         case HCI_INIT_SEND_RESET:
1893             hci_state_reset();
1894 
1895 #ifndef HAVE_HOST_CONTROLLER_API
1896             // prepare reset if command complete not received in 100ms
1897             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1898             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1899             btstack_run_loop_add_timer(&hci_stack->timeout);
1900 #endif
1901             // send command
1902             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1903             hci_send_cmd(&hci_reset);
1904             break;
1905         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1906             hci_send_cmd(&hci_read_local_version_information);
1907             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1908             break;
1909 
1910 #ifndef HAVE_HOST_CONTROLLER_API
1911         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1912             hci_state_reset();
1913             // prepare reset if command complete not received in 100ms
1914             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1915             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1916             btstack_run_loop_add_timer(&hci_stack->timeout);
1917             // send command
1918             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1919             hci_send_cmd(&hci_reset);
1920             break;
1921         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1922             hci_state_reset();
1923             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1924             hci_send_cmd(&hci_reset);
1925             break;
1926         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1927             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1928             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1929             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1930             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1931             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1932             break;
1933         }
1934         case HCI_INIT_SET_BD_ADDR:
1935             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1936             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1937             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1938             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1939             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1940             break;
1941         case HCI_INIT_SEND_READ_LOCAL_NAME:
1942 #ifdef ENABLE_CLASSIC
1943             hci_send_cmd(&hci_read_local_name);
1944             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1945             break;
1946 #endif
1947             /* fall through */
1948 
1949         case HCI_INIT_SEND_BAUD_CHANGE:
1950             if (need_baud_change) {
1951                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1952                 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1953                 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1954                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1955                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1956                 // STLC25000D: baudrate change happens within 0.5 s after command was send,
1957                 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1958                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1959                     btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1960                     btstack_run_loop_add_timer(&hci_stack->timeout);
1961                }
1962                break;
1963             }
1964             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1965 
1966             /* fall through */
1967 
1968         case HCI_INIT_CUSTOM_INIT:
1969         case HCI_INIT_CUSTOM_PRE_INIT:
1970             // Custom initialization
1971             if (hci_stack->chipset && hci_stack->chipset->next_command){
1972                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1973                 bool send_cmd = false;
1974                 switch (hci_stack->chipset_result){
1975                     case BTSTACK_CHIPSET_VALID_COMMAND:
1976                         send_cmd = true;
1977                         switch (hci_stack->substate){
1978                             case HCI_INIT_CUSTOM_INIT:
1979                                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1980                                 break;
1981                             case HCI_INIT_CUSTOM_PRE_INIT:
1982                                 hci_stack->substate = HCI_INIT_W4_CUSTOM_PRE_INIT;
1983                                 break;
1984                             default:
1985                                 btstack_assert(false);
1986                                 break;
1987                         }
1988                         break;
1989                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1990                         send_cmd = true;
1991                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1992                         log_info("CSR Warm Boot");
1993                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1994                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1995                         btstack_run_loop_add_timer(&hci_stack->timeout);
1996                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1997                             && hci_stack->config
1998                             && hci_stack->chipset
1999                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
2000                             && hci_stack->hci_transport->set_baudrate
2001                             && hci_transport_uart_get_main_baud_rate()){
2002                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
2003                         } else {
2004                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
2005                         }
2006                         break;
2007                     default:
2008                         break;
2009                 }
2010 
2011                 if (send_cmd){
2012                     int size = 3u + hci_stack->hci_packet_buffer[2u];
2013                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
2014                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
2015                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
2016                     break;
2017                 }
2018                 log_info("Init script done");
2019 
2020                 // Custom Pre-Init complete, start regular init with HCI Reset
2021                 if (hci_stack->substate == HCI_INIT_CUSTOM_PRE_INIT){
2022                     hci_stack->substate = HCI_INIT_W4_SEND_RESET;
2023                     hci_send_cmd(&hci_reset);
2024                     break;
2025                 }
2026 
2027                 // Init script download on Broadcom chipsets causes:
2028                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2029                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
2030                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
2031 
2032                     // - baud rate to reset, restore UART baud rate if needed
2033                     if (need_baud_change) {
2034                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
2035                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
2036                         hci_stack->hci_transport->set_baudrate(baud_rate);
2037                     }
2038 
2039                     uint16_t bcm_delay_ms = 300;
2040                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
2041                     //   -> Work around: wait here.
2042                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
2043                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
2044                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
2045                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
2046                     btstack_run_loop_add_timer(&hci_stack->timeout);
2047                     break;
2048                 }
2049             }
2050 #endif
2051             /* fall through */
2052 
2053         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
2054             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
2055             hci_send_cmd(&hci_read_local_supported_commands);
2056             break;
2057         case HCI_INIT_READ_BD_ADDR:
2058             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
2059             hci_send_cmd(&hci_read_bd_addr);
2060             break;
2061         case HCI_INIT_READ_BUFFER_SIZE:
2062             // only read buffer size if supported
2063             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE)){
2064                 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
2065                 hci_send_cmd(&hci_read_buffer_size);
2066                 break;
2067             }
2068 
2069             /* fall through */
2070 
2071         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
2072             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
2073             hci_send_cmd(&hci_read_local_supported_features);
2074             break;
2075 
2076 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2077         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
2078             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
2079             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
2080             break;
2081         case HCI_INIT_HOST_BUFFER_SIZE:
2082             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
2083             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
2084                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
2085             break;
2086 #endif
2087 
2088         case HCI_INIT_SET_EVENT_MASK:
2089             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
2090             if (hci_le_supported()){
2091                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
2092             } else {
2093                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
2094                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
2095             }
2096             break;
2097 
2098         case HCI_INIT_SET_EVENT_MASK_2:
2099             // On Bluettooth PTS dongle (BL 654) with PacketCraft HCI Firmware (LMP subversion) 0x5244,
2100             // setting Event Mask 2 causes Controller to drop Encryption Change events.
2101             if (hci_command_supported(SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2)
2102             && (hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC)){
2103                 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK_2;
2104                 // Encryption Change Event v2 - bit 25
2105                 hci_send_cmd(&hci_set_event_mask_2,0x02000000U, 0x0);
2106                 break;
2107             }
2108 
2109 #ifdef ENABLE_CLASSIC
2110             /* fall through */
2111 
2112         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
2113             if (hci_classic_supported() && gap_ssp_supported()){
2114                 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
2115                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
2116                 break;
2117             }
2118 
2119             /* fall through */
2120 
2121         case HCI_INIT_WRITE_INQUIRY_MODE:
2122             if (hci_classic_supported()){
2123                 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
2124                 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
2125                 break;
2126             }
2127 
2128             /* fall through */
2129 
2130         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
2131             // skip write secure connections host support if not supported or disabled
2132             if (hci_classic_supported() && hci_stack->secure_connections_enable
2133             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST)) {
2134                 hci_stack->secure_connections_active = true;
2135                 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
2136                 hci_send_cmd(&hci_write_secure_connections_host_support, 1);
2137                 break;
2138             }
2139 
2140             /* fall through */
2141 
2142         case HCI_INIT_SET_MIN_ENCRYPTION_KEY_SIZE:
2143             // skip set min encryption key size
2144             if (hci_classic_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE)) {
2145                 hci_stack->substate = HCI_INIT_W4_SET_MIN_ENCRYPTION_KEY_SIZE;
2146                 hci_send_cmd(&hci_set_min_encryption_key_size, hci_stack->gap_required_encyrption_key_size);
2147                 break;
2148             }
2149 
2150 #ifdef ENABLE_SCO_OVER_HCI
2151             /* fall through */
2152 
2153         // only sent if ENABLE_SCO_OVER_HCI is defined
2154         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2155             // skip write synchronous flow control if not supported
2156             if (hci_classic_supported()
2157             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)) {
2158                 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
2159                 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
2160                 break;
2161             }
2162             /* fall through */
2163 
2164         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
2165             // skip write default erroneous data reporting if not supported
2166             if (hci_classic_supported()
2167             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) {
2168                 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
2169                 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
2170                 break;
2171             }
2172 #endif
2173 
2174 #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM)
2175             /* fall through */
2176 
2177         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
2178         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
2179             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2180                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
2181 #ifdef ENABLE_SCO_OVER_HCI
2182                 log_info("BCM: Route SCO data via HCI transport");
2183                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
2184 #endif
2185 #ifdef ENABLE_SCO_OVER_PCM
2186                 log_info("BCM: Route SCO data via PCM interface");
2187 #ifdef ENABLE_BCM_PCM_WBS
2188                 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz
2189                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
2190 #else
2191                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
2192                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
2193 #endif
2194 #endif
2195                 break;
2196             }
2197 #endif
2198 
2199 #ifdef ENABLE_SCO_OVER_PCM
2200             /* fall through */
2201 
2202         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
2203             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2204                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
2205                 log_info("BCM: Config PCM interface for I2S");
2206 #ifdef ENABLE_BCM_PCM_WBS
2207                 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
2208                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
2209 #else
2210                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
2211                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
2212 #endif
2213                 break;
2214             }
2215         case HCI_INIT_BCM_WRITE_PCM_DATA_FORMAT_PARAM:
2216             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2217                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_PCM_DATA_FORMAT_PARAM;
2218                 log_info("BCM: Config PCM Data format");
2219                 // msb first, fill bits 0, left justified
2220                 hci_send_cmd(&hci_bcm_write_pcm_data_format_param, 0, 0, 3, 3, 0);
2221                 break;
2222             }
2223 #ifdef HAVE_BCM_PCM2
2224         case HCI_INIT_BCM_PCM2_SETUP:
2225             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)) {
2226                 hci_stack->substate = HCI_INIT_W4_BCM_PCM2_SETUP;
2227                 uint8_t  op_mode = 0;  // Op_Mode = 0 = PCM, 1 = I2S
2228                 uint32_t pcm_clock_freq;
2229                 uint8_t  ch_0_period;
2230 #ifdef ENABLE_BCM_PCM_WBS
2231                 // 512 kHz, resample 8 kHz to 16 khz
2232                 pcm_clock_freq = 512000;
2233                 ch_0_period = 1;
2234 #else
2235                 // 256 khz, 8 khz output
2236                 pcm_clock_freq = 256000;
2237                 ch_0_period = 0;
2238 #endif
2239                 log_info("BCM: Config PCM2 - op mode %u, pcm clock %" PRIu32 ", ch0_period %u", op_mode, pcm_clock_freq, ch_0_period);
2240                 hci_send_cmd(&hci_bcm_pcm2_setup,
2241                              0x00, // Action = Write
2242                              0x00, // Test_Options = None
2243                              op_mode, // Op_Mode
2244                              0x1D, // Sync_and_Clock_Options Sync = Signal | Sync Output Enable | Generate PCM_CLK | Tristate When Idle
2245                              pcm_clock_freq, // PCM_Clock_Freq
2246                              0x01, // Sync_Signal_Width
2247                              0x0F, // Slot_Width
2248                              0x01, // NumberOfSlots
2249                              0x00, // Bank_0_Fill_Mode = 0s
2250                              0x00, // Bank_0_Number_of_Fill_Bits
2251                              0x00, // Bank_0_Programmable_Fill_Data
2252                              0x00, // Bank_1_Fill_Mode = 0s
2253                              0x00, // Bank_1_Number_of_Fill_Bits
2254                              0x00, // Bank_1_Programmable_Fill_Data
2255                              0x00, // Data_Justify_And_Bit_Order_Options = Left Justify
2256                              0x00, // Ch_0_Slot_Number
2257                              0x01, // Ch_1_Slot_Number
2258                              0x02, // Ch_2_Slot_Number
2259                              0x03, // Ch_3_Slot_Number
2260                              0x04, // Ch_4_Slot_Number
2261                              ch_0_period, // Ch_0_Period
2262                              0x00, // Ch_1_Period
2263                              0x00  // Ch_2_Period
2264                 );
2265                 break;
2266             }
2267 #endif
2268 #endif /* ENABLE_SCO_OVER_PCM */
2269 #endif /* ENABLE_CLASSIC */
2270 
2271 #ifdef ENABLE_BLE
2272             /* fall through */
2273 
2274         // LE INIT
2275         case HCI_INIT_LE_READ_BUFFER_SIZE:
2276             if (hci_le_supported()){
2277                 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
2278                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2)){
2279                     hci_send_cmd(&hci_le_read_buffer_size_v2);
2280                 } else {
2281                     hci_send_cmd(&hci_le_read_buffer_size);
2282                 }
2283                 break;
2284             }
2285 
2286             /* fall through */
2287 
2288         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
2289             // skip write le host if not supported (e.g. on LE only EM9301)
2290             if (hci_le_supported()
2291             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED)) {
2292                 // LE Supported Host = 1, Simultaneous Host = 0
2293                 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
2294                 hci_send_cmd(&hci_write_le_host_supported, 1, 0);
2295                 break;
2296             }
2297 
2298             /* fall through */
2299 
2300         case HCI_INIT_LE_SET_EVENT_MASK:
2301             if (hci_le_supported()){
2302                 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
2303 #ifdef ENABLE_LE_ENHANCED_CONNECTION_COMPLETE_EVENT
2304                 hci_send_cmd(&hci_le_set_event_mask, 0xffffffff, 0x0107); // all events from core v5.3
2305 #else
2306                 hci_send_cmd(&hci_le_set_event_mask, 0xfffffdff, 0x0007); // all events from core v5.3 without LE Enhanced Connection Complete
2307 #endif
2308                 break;
2309             }
2310 #endif
2311 
2312 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2313             /* fall through */
2314 
2315         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
2316             if (hci_le_supported()
2317             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH)) {
2318                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
2319                 hci_send_cmd(&hci_le_read_maximum_data_length);
2320                 break;
2321             }
2322 
2323             /* fall through */
2324 
2325         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
2326             if (hci_le_supported()
2327             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH)) {
2328                 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
2329                 hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
2330                 break;
2331             }
2332 #endif
2333 
2334 #ifdef ENABLE_LE_CENTRAL
2335             /* fall through */
2336 
2337         case HCI_INIT_READ_WHITE_LIST_SIZE:
2338             if (hci_le_supported()){
2339                 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
2340                 hci_send_cmd(&hci_le_read_white_list_size);
2341                 break;
2342             }
2343 
2344 #endif
2345 
2346 #ifdef ENABLE_LE_PERIPHERAL
2347 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
2348             /* fall through */
2349 
2350         case HCI_INIT_LE_READ_MAX_ADV_DATA_LEN:
2351             if (hci_le_extended_advertising_supported()){
2352                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_ADV_DATA_LEN;
2353                 hci_send_cmd(&hci_le_read_maximum_advertising_data_length);
2354                 break;
2355             }
2356 #endif
2357 #endif
2358             /* fall through */
2359 
2360 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2361     case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS:
2362             if (hci_le_supported()) {
2363                 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS;
2364                 hci_send_cmd(&hci_le_set_host_feature, 32, 1);
2365                 break;
2366             }
2367 #endif
2368 
2369             /* fall through */
2370 
2371         case HCI_INIT_DONE:
2372             hci_stack->substate = HCI_INIT_DONE;
2373             // main init sequence complete
2374 #ifdef ENABLE_CLASSIC
2375             // check if initial Classic GAP Tasks are completed
2376             if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) {
2377                 hci_run_gap_tasks_classic();
2378                 break;
2379             }
2380 #endif
2381 #ifdef ENABLE_BLE
2382 #ifdef ENABLE_LE_CENTRAL
2383             // check if initial LE GAP Tasks are completed
2384             if (hci_le_supported() && hci_stack->le_scanning_param_update) {
2385                 hci_run_general_gap_le();
2386                 break;
2387             }
2388 #endif
2389 #endif
2390             hci_init_done();
2391             break;
2392 
2393         default:
2394             return;
2395     }
2396 }
2397 
2398 static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
2399     bool command_completed = false;
2400     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
2401         uint16_t opcode = little_endian_read_16(packet,3);
2402         if (opcode == hci_stack->last_cmd_opcode){
2403             command_completed = true;
2404             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
2405         } else {
2406             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
2407         }
2408     }
2409 
2410     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
2411         uint8_t  status = packet[2];
2412         uint16_t opcode = little_endian_read_16(packet,4);
2413         if (opcode == hci_stack->last_cmd_opcode){
2414             if (status){
2415                 command_completed = true;
2416                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
2417             } else {
2418                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
2419             }
2420         } else {
2421             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
2422         }
2423     }
2424 #ifndef HAVE_HOST_CONTROLLER_API
2425     // Vendor == CSR
2426     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2427         // TODO: track actual command
2428         command_completed = true;
2429     }
2430 
2431     // Vendor == Toshiba
2432     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2433         // TODO: track actual command
2434         command_completed = true;
2435         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
2436         hci_stack->num_cmd_packets = 1;
2437     }
2438 #endif
2439 
2440     return command_completed;
2441 }
2442 
2443 static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
2444 
2445     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
2446 
2447     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
2448 
2449 #ifndef HAVE_HOST_CONTROLLER_API
2450 
2451     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
2452     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
2453     //
2454     // HCI Reset
2455     // Timeout 100 ms
2456     // HCI Reset
2457     // Command Complete Reset
2458     // HCI Read Local Version Information
2459     // Command Complete Reset - but we expected Command Complete Read Local Version Information
2460     // hang...
2461     //
2462     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
2463     if (!command_completed
2464             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2465             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
2466 
2467         uint16_t opcode = little_endian_read_16(packet,3);
2468         if (opcode == hci_reset.opcode){
2469             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
2470             return;
2471         }
2472     }
2473 
2474     // CSR & H5
2475     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
2476     if (!command_completed
2477             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2478             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
2479 
2480         uint16_t opcode = little_endian_read_16(packet,3);
2481         if (opcode == hci_reset.opcode){
2482             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
2483             return;
2484         }
2485     }
2486 
2487     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
2488     // fix: Correct substate and behave as command below
2489     if (command_completed){
2490         switch (hci_stack->substate){
2491             case HCI_INIT_SEND_RESET:
2492                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
2493                 break;
2494             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
2495                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
2496                 break;
2497             default:
2498                 break;
2499         }
2500     }
2501 
2502 #endif
2503 
2504     if (!command_completed) return;
2505 
2506     bool need_baud_change = false;
2507     bool need_addr_change = false;
2508 
2509 #ifndef HAVE_HOST_CONTROLLER_API
2510     need_baud_change = hci_stack->config
2511                         && hci_stack->chipset
2512                         && hci_stack->chipset->set_baudrate_command
2513                         && hci_stack->hci_transport->set_baudrate
2514                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
2515 
2516     need_addr_change = hci_stack->custom_bd_addr_set
2517                         && hci_stack->chipset
2518                         && hci_stack->chipset->set_bd_addr_command;
2519 #endif
2520 
2521     switch(hci_stack->substate){
2522 
2523 #ifndef HAVE_HOST_CONTROLLER_API
2524         case HCI_INIT_SEND_RESET:
2525             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
2526             // fix: just correct substate and behave as command below
2527 
2528             /* fall through */
2529 #endif
2530 
2531         case HCI_INIT_W4_SEND_RESET:
2532             btstack_run_loop_remove_timer(&hci_stack->timeout);
2533             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
2534             return;
2535 
2536 #ifndef HAVE_HOST_CONTROLLER_API
2537         case HCI_INIT_W4_SEND_BAUD_CHANGE:
2538             // for STLC2500D, baud rate change already happened.
2539             // for others, baud rate gets changed now
2540             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
2541                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2542                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
2543                 hci_stack->hci_transport->set_baudrate(baud_rate);
2544             }
2545             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2546             return;
2547         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
2548             btstack_run_loop_remove_timer(&hci_stack->timeout);
2549             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2550             return;
2551         case HCI_INIT_W4_CUSTOM_INIT:
2552             // repeat custom init
2553             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2554             return;
2555         case HCI_INIT_W4_CUSTOM_PRE_INIT:
2556             // repeat custom init
2557             hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
2558             return;
2559 #endif
2560 
2561         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
2562             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2563               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
2564                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
2565                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
2566                 return;
2567             }
2568             if (need_addr_change){
2569                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2570                 return;
2571             }
2572             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2573             return;
2574 #ifndef HAVE_HOST_CONTROLLER_API
2575         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
2576             if (need_baud_change){
2577                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2578                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
2579                 hci_stack->hci_transport->set_baudrate(baud_rate);
2580             }
2581             if (need_addr_change){
2582                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2583                 return;
2584             }
2585             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2586             return;
2587         case HCI_INIT_W4_SET_BD_ADDR:
2588             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
2589             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
2590             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
2591                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
2592                 return;
2593             }
2594             // skipping st warm boot
2595             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2596             return;
2597         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
2598             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2599             return;
2600 #endif
2601 
2602         case HCI_INIT_DONE:
2603             // set state if we came here by fall through
2604             hci_stack->substate = HCI_INIT_DONE;
2605             return;
2606 
2607         default:
2608             break;
2609     }
2610     hci_initializing_next_state();
2611 }
2612 
2613 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
2614     // CC2564C might emit Connection Complete for rejected incoming SCO connection
2615     // To prevent accidentally free'ing the HCI connection for the ACL connection,
2616     // check if we have been aware of the HCI connection
2617     switch (conn->state){
2618         case SENT_CREATE_CONNECTION:
2619         case RECEIVED_CONNECTION_REQUEST:
2620         case ACCEPTED_CONNECTION_REQUEST:
2621             break;
2622         default:
2623             return;
2624     }
2625 
2626     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
2627     bd_addr_t bd_address;
2628     (void)memcpy(&bd_address, conn->address, 6);
2629 
2630 #ifdef ENABLE_CLASSIC
2631     // cache needed data
2632     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
2633 #endif
2634 
2635     // connection failed, remove entry
2636     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2637     btstack_memory_hci_connection_free( conn );
2638 
2639 #ifdef ENABLE_CLASSIC
2640     // notify client if dedicated bonding
2641     if (notify_dedicated_bonding_failed){
2642         log_info("hci notify_dedicated_bonding_failed");
2643         hci_emit_dedicated_bonding_result(bd_address, status);
2644     }
2645 
2646     // if authentication error, also delete link key
2647     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
2648         gap_drop_link_key_for_bd_addr(bd_address);
2649     }
2650 #else
2651     UNUSED(status);
2652 #endif
2653 }
2654 
2655 #ifdef ENABLE_CLASSIC
2656 static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
2657     // SSP Controller
2658     if (features[6] & (1 << 3)){
2659         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
2660     }
2661     // eSCO
2662     if (features[3] & (1<<7)){
2663         conn->remote_supported_features[0] |= 1;
2664     }
2665     // Extended features
2666     if (features[7] & (1<<7)){
2667         conn->remote_supported_features[0] |= 2;
2668     }
2669     // SCO packet types
2670     conn->remote_supported_sco_packets = hci_sco_packet_types_for_features(features);
2671 }
2672 
2673 static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
2674     // SSP Host
2675     if (features[0] & (1 << 0)){
2676         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
2677     }
2678     // SC Host
2679     if (features[0] & (1 << 3)){
2680         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
2681     }
2682 }
2683 
2684 static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
2685     // SC Controller
2686     if (features[1] & (1 << 0)){
2687         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2688     }
2689 }
2690 
2691 static void hci_handle_remote_features_received(hci_connection_t * conn){
2692     conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE;
2693     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2694     log_info("Remote features %02x, bonding flags %" PRIx32, conn->remote_supported_features[0], conn->bonding_flags);
2695     if (conn->bonding_flags & BONDING_DEDICATED){
2696         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2697     }
2698 }
2699 static bool hci_remote_sc_enabled(hci_connection_t * connection){
2700     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2701     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2702 }
2703 
2704 #endif
2705 
2706 static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
2707     // handle BT initialization
2708     if (hci_stack->state == HCI_STATE_INITIALIZING) {
2709         hci_initializing_event_handler(packet, size);
2710     }
2711 
2712     // help with BT sleep
2713     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
2714         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
2715         && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2716         && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){
2717         hci_initializing_next_state();
2718     }
2719 }
2720 
2721 #ifdef ENABLE_CLASSIC
2722 static void hci_handle_mutual_authentication_completed(hci_connection_t * conn){
2723     // bonding complete if connection is authenticated (either initiated or BR/EDR SC)
2724     conn->requested_security_level = LEVEL_0;
2725     gap_security_level_t security_level = gap_security_level_for_connection(conn);
2726     hci_emit_security_level(conn->con_handle, security_level);
2727 
2728     // dedicated bonding
2729     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
2730         conn->bonding_flags &= ~BONDING_DEDICATED;
2731         conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS;
2732 #ifdef ENABLE_EXPLICIT_DEDICATED_BONDING_DISCONNECT
2733         // emit dedicated bonding complete, don't disconnect
2734         hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
2735 #else
2736         // request disconnect, event is emitted after disconnect
2737         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2738 #endif
2739     }
2740 }
2741 
2742 static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
2743     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2744     conn->encryption_key_size = encryption_key_size;
2745 
2746     // mutual authentication complete if authenticated and we have retrieved the encryption key size
2747     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
2748         hci_handle_mutual_authentication_completed(conn);
2749     } else {
2750         // otherwise trigger remote feature request and send authentication request
2751         hci_trigger_remote_features_for_connection(conn);
2752         if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) == 0) {
2753             conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2754         }
2755     }
2756 }
2757 #endif
2758 
2759 static void hci_store_local_supported_commands(const uint8_t * packet){
2760     // create mapping table
2761 #define X(name, offset, bit) { offset, bit },
2762     static struct {
2763         uint8_t byte_offset;
2764         uint8_t bit_position;
2765     } supported_hci_commands_map [] = {
2766         SUPPORTED_HCI_COMMANDS
2767     };
2768 #undef X
2769 
2770     // create names for debug purposes
2771 #ifdef ENABLE_LOG_DEBUG
2772 #define X(name, offset, bit) #name,
2773     static const char * command_names[] = {
2774         SUPPORTED_HCI_COMMANDS
2775     };
2776 #undef X
2777 #endif
2778 
2779     hci_stack->local_supported_commands = 0;
2780     const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1];
2781     uint16_t i;
2782     for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){
2783         if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){
2784 #ifdef ENABLE_LOG_DEBUG
2785             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);
2786 #else
2787             log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
2788 #endif
2789             hci_stack->local_supported_commands |= (1LU << i);
2790         }
2791     }
2792     log_info("Local supported commands summary %08" PRIx32, hci_stack->local_supported_commands);
2793 }
2794 
2795 static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2796     UNUSED(size);
2797 
2798     uint8_t status = 0;
2799     if( size > OFFSET_OF_DATA_IN_COMMAND_COMPLETE ) {
2800         status = hci_event_command_complete_get_return_parameters(packet)[0];
2801     }
2802     uint16_t manufacturer;
2803 #ifdef ENABLE_CLASSIC
2804     hci_connection_t * conn;
2805 #endif
2806 #if defined(ENABLE_CLASSIC) || (defined(ENABLE_BLE) && defined(ENABLE_LE_ISOCHRONOUS_STREAMS))
2807     hci_con_handle_t handle;
2808 #endif
2809 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2810     le_audio_cig_t * cig;
2811 #endif
2812 #if defined(ENABLE_BLE) && defined(ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
2813     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
2814 #endif
2815 
2816     // get num cmd packets - limit to 1 to reduce complexity
2817     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
2818 
2819     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2820     switch (opcode){
2821         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2822             if (status) break;
2823             // terminate, name 248 chars
2824             packet[6+248] = 0;
2825             log_info("local name: %s", &packet[6]);
2826             break;
2827         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
2828             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2829             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2830                 uint16_t acl_len = little_endian_read_16(packet, 6);
2831                 uint16_t sco_len = packet[8];
2832 
2833                 // determine usable ACL/SCO payload size
2834                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2835                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2836 
2837                 hci_stack->acl_packets_total_num = (uint8_t) btstack_min(little_endian_read_16(packet,  9), MAX_NR_CONTROLLER_ACL_BUFFERS);
2838                 hci_stack->sco_packets_total_num = (uint8_t) btstack_min(little_endian_read_16(packet, 11), MAX_NR_CONTROLLER_SCO_PACKETS);
2839 
2840                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2841                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
2842                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2843             }
2844             break;
2845         case HCI_OPCODE_HCI_READ_RSSI:
2846             if (status == ERROR_CODE_SUCCESS){
2847                 uint8_t event[5];
2848                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2849                 event[1] = 3;
2850                 (void)memcpy(&event[2], &packet[6], 3);
2851                 hci_emit_event(event, sizeof(event), 1);
2852             }
2853             break;
2854 #ifdef ENABLE_BLE
2855         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2:
2856             hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9);
2857             hci_stack->le_iso_packets_total_num = packet[11];
2858             log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u",
2859                      hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num);
2860 
2861             /* fall through */
2862 
2863         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2864             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2865             hci_stack->le_acl_packets_total_num = packet[8];
2866             // determine usable ACL payload size
2867             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
2868                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
2869             }
2870             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);
2871             break;
2872 #endif
2873 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2874         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2875             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2876             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2877             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);
2878             break;
2879 #endif
2880 #ifdef ENABLE_LE_CENTRAL
2881         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2882             hci_stack->le_whitelist_capacity = packet[6];
2883             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2884             break;
2885 #endif
2886 #ifdef ENABLE_LE_PERIPHERAL
2887 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
2888         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH:
2889             hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6);
2890             break;
2891         case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS:
2892             if (hci_stack->le_advertising_set_in_current_command != 0) {
2893                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2894                 hci_stack->le_advertising_set_in_current_command = 0;
2895                 if (advertising_set == NULL) break;
2896                 uint8_t adv_status = packet[6];
2897                 uint8_t tx_power   = packet[7];
2898                 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 };
2899                 if (adv_status == 0){
2900                     advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
2901                 }
2902                 hci_emit_event(event, sizeof(event), 1);
2903             }
2904             break;
2905         case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET:
2906             if (hci_stack->le_advertising_set_in_current_command != 0) {
2907                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2908                 hci_stack->le_advertising_set_in_current_command = 0;
2909                 if (advertising_set == NULL) break;
2910                 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, status };
2911                 if (status == 0){
2912                     btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set);
2913                 }
2914                 hci_emit_event(event, sizeof(event), 1);
2915             }
2916             break;
2917 #endif
2918 #endif
2919         case HCI_OPCODE_HCI_READ_BD_ADDR:
2920             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2921             log_info("Local Address, Status: 0x%02x: Addr: %s", status, bd_addr_to_str(hci_stack->local_bd_addr));
2922 #ifdef ENABLE_CLASSIC
2923             if (hci_stack->link_key_db){
2924                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
2925             }
2926 #endif
2927             break;
2928 #ifdef ENABLE_CLASSIC
2929         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
2930             hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
2931             break;
2932         case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE:
2933             if (status == ERROR_CODE_SUCCESS) {
2934                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC;
2935             } else {
2936                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2937             }
2938             break;
2939         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2940         case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE:
2941             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2942                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2943                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2944                 hci_emit_event(event, sizeof(event), 1);
2945             }
2946             break;
2947 #endif
2948         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
2949             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
2950 
2951 #ifdef ENABLE_CLASSIC
2952             // determine usable ACL packet types based on host buffer size and supported features
2953             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]);
2954             log_info("ACL Packet types %04x", hci_stack->usable_packet_types_acl);
2955             // determine usable SCO packet types based on supported features
2956             hci_stack->usable_packet_types_sco = hci_sco_packet_types_for_features(
2957                     &hci_stack->local_supported_features[0]);
2958             log_info("SCO Packet types %04x - eSCO %u", hci_stack->usable_packet_types_sco, hci_extended_sco_link_supported());
2959 #endif
2960             // Classic/LE
2961             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2962             break;
2963         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2964             manufacturer = little_endian_read_16(packet, 10);
2965             // map Cypress & Infineon to Broadcom
2966             switch (manufacturer){
2967                 case BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR:
2968                 case BLUETOOTH_COMPANY_ID_INFINEON_TECHNOLOGIES_AG:
2969                     log_info("Treat Cypress/Infineon as Broadcom");
2970                     manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2971                     little_endian_store_16(packet, 10, manufacturer);
2972                     break;
2973                 default:
2974                     break;
2975             }
2976             hci_stack->manufacturer = manufacturer;
2977             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2978             break;
2979         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2980             hci_store_local_supported_commands(packet);
2981             break;
2982 #ifdef ENABLE_CLASSIC
2983         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2984             if (status) return;
2985             hci_stack->synchronous_flow_control_enabled = 1;
2986             break;
2987         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2988             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2989             conn   = hci_connection_for_handle(handle);
2990             if (conn != NULL) {
2991                 uint8_t key_size = 0;
2992                 if (status == 0){
2993                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
2994                     log_info("Handle %04x key Size: %u", handle, key_size);
2995                 } else {
2996                     key_size = 1;
2997                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2998                 }
2999                 hci_handle_read_encryption_key_size_complete(conn, key_size);
3000             }
3001             break;
3002         // assert pairing complete event is emitted.
3003         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
3004         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
3005         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
3006         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
3007             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3008             // lookup connection by gap pairing addr
3009             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
3010             if (conn == NULL) break;
3011             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
3012             break;
3013 
3014 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3015         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
3016         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
3017             uint8_t event[67];
3018             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
3019             event[1] = 65;
3020             (void)memset(&event[2], 0, 65);
3021             if (status == ERROR_CODE_SUCCESS){
3022                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
3023                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
3024                     event[2] = 3;
3025                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
3026                 } else {
3027                     event[2] = 1;
3028                 }
3029             }
3030             hci_emit_event(event, sizeof(event), 0);
3031             break;
3032         }
3033 
3034         // note: only needed if user does not provide OOB data
3035         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
3036             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
3037             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
3038             if (conn == NULL) break;
3039             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
3040             break;
3041 #endif
3042 #endif
3043 #ifdef ENABLE_BLE
3044 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3045         case HCI_OPCODE_HCI_LE_SET_CIG_PARAMETERS:
3046             // lookup CIG
3047             cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
3048             if (cig != NULL){
3049                 uint8_t i = 0;
3050                 if (status == ERROR_CODE_SUCCESS){
3051                     // assign CIS handles to pre-allocated CIS
3052                     btstack_linked_list_iterator_t it;
3053                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3054                     while (btstack_linked_list_iterator_has_next(&it) && (i < cig->num_cis)) {
3055                         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3056                         if ((iso_stream->group_id == hci_stack->iso_active_operation_group_id) &&
3057                             (iso_stream->iso_type == HCI_ISO_TYPE_CIS)){
3058                             hci_con_handle_t cis_handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3+(2*i));
3059                             iso_stream->cis_handle  = cis_handle;
3060                             cig->cis_con_handles[i] = cis_handle;
3061                             i++;
3062                         }
3063                     }
3064                     cig->state = LE_AUDIO_CIG_STATE_W4_CIS_REQUEST;
3065                     hci_emit_cig_created(cig, status);
3066                 } else {
3067                     hci_emit_cig_created(cig, status);
3068                     btstack_linked_list_remove(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
3069                 }
3070             }
3071             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3072             break;
3073         case HCI_OPCODE_HCI_LE_CREATE_CIS:
3074             if (status != ERROR_CODE_SUCCESS){
3075                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3076             }
3077             break;
3078         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
3079             if (status != ERROR_CODE_SUCCESS){
3080                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3081             }
3082             break;
3083         case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: {
3084             // lookup BIG by state
3085             btstack_linked_list_iterator_t it;
3086             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
3087             while (btstack_linked_list_iterator_has_next(&it)) {
3088                 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
3089                 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
3090                     if (status == ERROR_CODE_SUCCESS){
3091                         big->state_vars.next_bis++;
3092                         if (big->state_vars.next_bis == big->num_bis){
3093                             big->state = LE_AUDIO_BIG_STATE_ACTIVE;
3094                             hci_emit_big_created(big, ERROR_CODE_SUCCESS);
3095                         } else {
3096                             big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
3097                         }
3098                     } else {
3099                         big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
3100                         big->state_vars.status = status;
3101                     }
3102                     return;
3103                 }
3104             }
3105             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
3106             while (btstack_linked_list_iterator_has_next(&it)) {
3107                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
3108                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
3109                     if (status == ERROR_CODE_SUCCESS){
3110                         big_sync->state_vars.next_bis++;
3111                         if (big_sync->state_vars.next_bis == big_sync->num_bis){
3112                             big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE;
3113                             hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS);
3114                         } else {
3115                             big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
3116                         }
3117                     } else {
3118                         big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
3119                         big_sync->state_vars.status = status;
3120                     }
3121                     return;
3122                 }
3123             }
3124             // Lookup CIS via active group operation
3125             if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
3126                 if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
3127                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3128 
3129                     // lookup CIS by state
3130                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3131                     while (btstack_linked_list_iterator_has_next(&it)){
3132                         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3133                         handle = iso_stream->cis_handle;
3134                         bool emit_cis_created = false;
3135                         switch (iso_stream->state){
3136                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT:
3137                                 if (status != ERROR_CODE_SUCCESS){
3138                                     emit_cis_created = true;
3139                                     break;
3140                                 }
3141                                 if (iso_stream->max_sdu_c_to_p > 0){
3142                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
3143                                 } else {
3144                                     emit_cis_created = true;
3145                                 }
3146                                 break;
3147                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT:
3148                                 emit_cis_created = true;
3149                                 break;
3150                             default:
3151                                 break;
3152                         }
3153                         if (emit_cis_created){
3154                             hci_cis_handle_created(iso_stream, status);
3155                         }
3156                     }
3157                 } else {
3158                     cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
3159                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3160                     if (cig != NULL) {
3161                         // emit cis created if all ISO Paths have been created
3162                         // assume we are central
3163                         uint8_t cis_index     = cig->state_vars.next_cis >> 1;
3164                         uint8_t cis_direction = cig->state_vars.next_cis & 1;
3165                         bool outgoing_needed  = cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
3166                         // if outgoing has been setup, or incoming was setup but outgoing not required
3167                         if ((cis_direction == 1) || (outgoing_needed == false)){
3168                             // lookup iso stream by cig/cis
3169                             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3170                             while (btstack_linked_list_iterator_has_next(&it)) {
3171                                 hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3172                                 if ((iso_stream->group_id == cig->cig_id) && (iso_stream->stream_id == cis_index)){
3173                                     hci_cis_handle_created(iso_stream, status);
3174                                 }
3175                             }
3176                         }
3177                         // next state
3178                         cig->state_vars.next_cis++;
3179                         cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
3180                     }
3181                 }
3182             }
3183             break;
3184         }
3185         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
3186             // lookup BIG by state
3187             btstack_linked_list_iterator_t it;
3188             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
3189             while (btstack_linked_list_iterator_has_next(&it)) {
3190                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
3191                 uint8_t big_handle = big_sync->big_handle;
3192                 switch (big_sync->state){
3193                     case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
3194                         btstack_linked_list_iterator_remove(&it);
3195                         hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
3196                         return;
3197                     default:
3198                         btstack_linked_list_iterator_remove(&it);
3199                         hci_emit_big_sync_stopped(big_handle);
3200                         return;
3201                 }
3202             }
3203             break;
3204         }
3205 #endif
3206 #endif
3207         default:
3208             break;
3209     }
3210 }
3211 
3212 static void handle_command_status_event(uint8_t * packet, uint16_t size) {
3213     UNUSED(size);
3214 
3215     // get num cmd packets - limit to 1 to reduce complexity
3216     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
3217 
3218     // get opcode and command status
3219     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
3220 
3221 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
3222     uint8_t status = hci_event_command_status_get_status(packet);
3223 #endif
3224 
3225 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3226     bd_addr_type_t addr_type;
3227     bd_addr_t addr;
3228 #endif
3229 
3230 #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
3231     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
3232 #endif
3233 
3234     switch (opcode){
3235 #ifdef ENABLE_CLASSIC
3236         case HCI_OPCODE_HCI_CREATE_CONNECTION:
3237         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
3238         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
3239 #endif
3240 #ifdef ENABLE_LE_CENTRAL
3241         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
3242 #endif
3243 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3244             addr_type = hci_stack->outgoing_addr_type;
3245             memcpy(addr, hci_stack->outgoing_addr, 6);
3246 
3247             // reset outgoing address info
3248             memset(hci_stack->outgoing_addr, 0, 6);
3249             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
3250 
3251             // on error
3252             if (status != ERROR_CODE_SUCCESS){
3253 #ifdef ENABLE_LE_CENTRAL
3254                 if (hci_is_le_connection_type(addr_type)){
3255                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3256                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3257                 }
3258 #endif
3259                 // error => outgoing connection failed
3260                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3261                 if (conn != NULL){
3262                     hci_handle_connection_failed(conn, status);
3263                 }
3264             }
3265             break;
3266 #endif
3267 #ifdef ENABLE_CLASSIC
3268         case HCI_OPCODE_HCI_INQUIRY:
3269             if (status == ERROR_CODE_SUCCESS) {
3270                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3271             } else {
3272                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3273             }
3274             break;
3275 #endif
3276 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3277         case HCI_OPCODE_HCI_LE_CREATE_CIS:
3278         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
3279             if (status == ERROR_CODE_SUCCESS){
3280                 hci_iso_stream_requested_confirm(HCI_ISO_GROUP_ID_INVALID);
3281             } else {
3282                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3283             }
3284             break;
3285 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
3286         default:
3287             break;
3288     }
3289 }
3290 
3291 #ifdef ENABLE_BLE
3292 static void hci_create_gap_connection_complete_event(const uint8_t * hci_event, uint8_t * gap_event) {
3293     gap_event[0] = HCI_EVENT_META_GAP;
3294     gap_event[1] = 36 - 2;
3295     gap_event[2] = GAP_SUBEVENT_LE_CONNECTION_COMPLETE;
3296     switch (hci_event_le_meta_get_subevent_code(hci_event)){
3297         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3298             memcpy(&gap_event[3], &hci_event[3], 11);
3299             memset(&gap_event[14], 0, 12);
3300             memcpy(&gap_event[26], &hci_event[14], 7);
3301             memset(&gap_event[33], 0xff, 3);
3302             break;
3303         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
3304             memcpy(&gap_event[3], &hci_event[3], 30);
3305             memset(&gap_event[33], 0xff, 3);
3306             break;
3307         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
3308             memcpy(&gap_event[3], &hci_event[3], 33);
3309             break;
3310         default:
3311             btstack_unreachable();
3312             break;
3313     }
3314 }
3315 
3316 static void hci_handle_le_connection_complete_event(const uint8_t * hci_event){
3317 	bd_addr_t addr;
3318 	bd_addr_type_t addr_type;
3319 	hci_connection_t * conn;
3320 
3321     // create GAP_SUBEVENT_LE_CONNECTION_COMPLETE
3322     uint8_t gap_event[36];
3323     hci_create_gap_connection_complete_event(hci_event, gap_event);
3324 
3325     // read fields
3326     uint8_t status = gap_subevent_le_connection_complete_get_status(gap_event);
3327     hci_role_t role = (hci_role_t) gap_subevent_le_connection_complete_get_role(gap_event);
3328     uint16_t conn_interval = gap_subevent_le_connection_complete_get_conn_interval(gap_event);
3329 
3330 	// Connection management
3331     gap_subevent_le_connection_complete_get_peer_address(gap_event, addr);
3332 	addr_type = (bd_addr_type_t) gap_subevent_le_connection_complete_get_peer_address_type(gap_event);
3333     log_info("LE Connection_complete (status=%u) type %u, %s", status, addr_type, bd_addr_to_str(addr));
3334 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3335 
3336 #ifdef ENABLE_LE_CENTRAL
3337 	// handle error: error is reported only to the initiator -> outgoing connection
3338 	if (status){
3339 
3340 		// handle cancelled outgoing connection
3341 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
3342 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
3343 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
3344 		if (status == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
3345 		    // reset state
3346             hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3347 			// get outgoing connection conn struct for direct connect
3348             if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
3349                 conn = gap_get_outgoing_le_connection();
3350                 conn->state = SEND_CREATE_CONNECTION;
3351             }
3352 		}
3353 
3354 		// free connection if cancelled by user (request == IDLE)
3355 		if ((conn != NULL) && (hci_stack->le_connecting_request == LE_CONNECTING_IDLE)){
3356 			// remove entry
3357 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3358 			btstack_memory_hci_connection_free( conn );
3359 		}
3360 		return;
3361 	}
3362 #endif
3363 
3364 	// on success, both hosts receive connection complete event
3365     if (role == HCI_ROLE_MASTER){
3366 #ifdef ENABLE_LE_CENTRAL
3367 		// if we're master, it was an outgoing connection
3368 		// note: no hci_connection_t object exists yet for connect with whitelist
3369 
3370         // if a identity addresses was used without enhanced connection complete event,
3371         // the connection complete event contains the current random address of the peer device.
3372         // This random address is needed in the case of a re-pairing
3373         if (hci_event_le_meta_get_subevent_code(hci_event) == HCI_SUBEVENT_LE_CONNECTION_COMPLETE){
3374             conn = gap_get_outgoing_le_connection();
3375             // if outgoing connection object is available, check if identity address was used.
3376             // if yes, track resolved random address and provide rpa
3377             // note: we don't update hci le subevent connection complete
3378             if (conn != NULL){
3379                 if (hci_is_le_identity_address_type(conn->address_type)){
3380                     memcpy(&gap_event[20], &gap_event[8], 6);
3381                     gap_event[7] = conn->address_type;
3382                     reverse_bd_addr(conn->address, &gap_event[8]);
3383                 }
3384             }
3385         }
3386 
3387         // we're done with it
3388         hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
3389         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3390 #endif
3391 	} else {
3392 #ifdef ENABLE_LE_PERIPHERAL
3393 		// if we're slave, it was an incoming connection, advertisements have stopped
3394         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
3395 #endif
3396 	}
3397 
3398 	// LE connections are auto-accepted, so just create a connection if there isn't one already
3399 	if (!conn){
3400 		conn = create_connection_for_bd_addr_and_type(addr, addr_type, role);
3401 	}
3402 
3403 	// no memory, sorry.
3404 	if (!conn){
3405 		return;
3406 	}
3407 
3408 	conn->state = OPEN;
3409 	conn->con_handle             = gap_subevent_le_connection_complete_get_connection_handle(gap_event);
3410     conn->le_connection_interval = conn_interval;
3411 
3412     // workaround: PAST doesn't work without LE Read Remote Features on PacketCraft Controller with LMP 568B
3413     conn->gap_connection_tasks = GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
3414 
3415 #ifdef ENABLE_LE_PERIPHERAL
3416 	if (role == HCI_ROLE_SLAVE){
3417 		hci_update_advertisements_enabled_for_current_roles();
3418 	}
3419 #endif
3420 
3421     // init unenhanced att bearer mtu
3422     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3423     conn->att_connection.mtu_exchanged = false;
3424 
3425     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
3426 
3427 	// restart timer
3428 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3429 	// btstack_run_loop_add_timer(&conn->timeout);
3430 
3431 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3432 
3433     // emit GAP_SUBEVENT_LE_CONNECTION_COMPLETE
3434     hci_emit_event(gap_event, sizeof(gap_event), 1);
3435 
3436     // emit BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3437 	hci_emit_nr_connections_changed();
3438 }
3439 #endif
3440 
3441 #ifdef ENABLE_CLASSIC
3442 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){
3443     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
3444     // LEVEL_4 is tested by l2cap
3445     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
3446     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
3447     if (level >= LEVEL_3){
3448         // MITM not possible without keyboard or display
3449         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3450         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3451 
3452         // MITM possible if one side has keyboard and the other has keyboard or display
3453         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3454         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3455 
3456         // MITM not possible if one side has only display and other side has no keyboard
3457         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3458         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3459     }
3460     // LEVEL 2 requires SSP, which is a given
3461     return true;
3462 }
3463 
3464 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
3465     // get requested security level
3466     gap_security_level_t requested_security_level = conn->requested_security_level;
3467     if (hci_stack->gap_secure_connections_only_mode){
3468         requested_security_level = LEVEL_4;
3469     }
3470 
3471     // assess security: LEVEL 4 requires SC
3472     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
3473     if ((requested_security_level == LEVEL_4) &&
3474         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
3475         !hci_remote_sc_enabled(conn)){
3476         log_info("Level 4 required, but SC not supported -> abort");
3477         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3478         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3479         return;
3480     }
3481 
3482     // assess bonding requirements: abort if remote in dedicated bonding mode but we are non-bonding
3483     // - GAP/MOD/NBON/BV-02-C
3484     // - GAP/DM/NBON/BV-01-C
3485     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3486         switch (conn->io_cap_response_auth_req){
3487             case SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING:
3488             case SSP_IO_AUTHREQ_MITM_PROTECTION_REQUIRED_DEDICATED_BONDING:
3489                 if (hci_stack->bondable == false){
3490                     log_info("Dedicated vs. non-bondable -> abort");
3491                     hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3492                     connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3493                     return;
3494                 }
3495             default:
3496                 break;
3497         }
3498     }
3499 
3500     // assess security based on io capabilities
3501     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3502         // responder: fully validate io caps of both sides as well as OOB data
3503         bool security_possible = false;
3504         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3505 
3506 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3507         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3508         // so we merge the OOB data availability
3509         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3510         if (conn->classic_oob_c_192 != NULL){
3511             have_oob_data |= 1;
3512         }
3513         if (conn->classic_oob_c_256 != NULL){
3514             have_oob_data |= 2;
3515         }
3516         // for up to Level 3, either P-192 as well as P-256 will do
3517         // 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
3518         // if remote does not SC, we should not receive P-256 data either
3519         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3520             security_possible = true;
3521         }
3522         // for Level 4, P-256 is needed
3523         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3524             security_possible = true;
3525         }
3526 #endif
3527 
3528         if (security_possible == false){
3529             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3530             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3531             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3532             return;
3533         }
3534     } else {
3535         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
3536 #ifndef ENABLE_CLASSIC_PAIRING_OOB
3537 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3538         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3539             log_info("Level 3+ required, but no input/output -> abort");
3540             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3541             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3542             return;
3543         }
3544 #endif
3545 #endif
3546     }
3547 
3548 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3549     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3550         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3551     } else {
3552         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3553     }
3554 #endif
3555 }
3556 
3557 #endif
3558 
3559 static void event_handler(uint8_t *packet, uint16_t size){
3560 
3561     uint16_t event_length = packet[1];
3562 
3563     // assert packet is complete
3564     if (size != (event_length + 2u)){
3565         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
3566         return;
3567     }
3568 
3569     hci_con_handle_t handle;
3570     hci_connection_t * conn;
3571     int i;
3572 
3573 #ifdef ENABLE_CLASSIC
3574     hci_link_type_t link_type;
3575     bd_addr_t addr;
3576     bd_addr_type_t addr_type;
3577 #endif
3578 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3579     hci_iso_stream_t * iso_stream;
3580     le_audio_big_t   * big;
3581     le_audio_big_sync_t * big_sync;
3582 #endif
3583 #if defined(ENABLE_LE_ISOCHRONOUS_STREAMS) || defined(ENABLE_LE_EXTENDED_ADVERTISING)
3584     btstack_linked_list_iterator_t it;
3585 #endif
3586 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3587     uint8_t advertising_handle;
3588 #endif
3589 
3590     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
3591 
3592     switch (hci_event_packet_get_type(packet)) {
3593 
3594         case HCI_EVENT_COMMAND_COMPLETE:
3595             handle_command_complete_event(packet, size);
3596             break;
3597 
3598         case HCI_EVENT_COMMAND_STATUS:
3599             handle_command_status_event(packet, size);
3600             break;
3601 
3602         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
3603             if (size < 3) return;
3604             uint16_t num_handles = packet[2];
3605             if (size != (3u + num_handles * 4u)) return;
3606 #ifdef ENABLE_CLASSIC
3607             bool notify_sco = false;
3608 #endif
3609 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3610             bool notify_iso = false;
3611 #endif
3612             uint16_t offset = 3;
3613             for (i=0; i<num_handles;i++){
3614                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
3615                 offset += 2u;
3616                 uint16_t num_packets = little_endian_read_16(packet, offset);
3617                 offset += 2u;
3618 
3619                 conn = hci_connection_for_handle(handle);
3620                 if (conn != NULL) {
3621 
3622                     if (conn->num_packets_sent >= num_packets) {
3623                         conn->num_packets_sent -= num_packets;
3624                     } else {
3625                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3626                         conn->num_packets_sent = 0;
3627                     }
3628                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3629 #ifdef ENABLE_CLASSIC
3630                     if (conn->address_type == BD_ADDR_TYPE_SCO){
3631                         notify_sco = true;
3632                     }
3633 #endif
3634                 }
3635 
3636 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
3637                 hci_controller_dump_packets();
3638 #endif
3639 
3640 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3641                 if (conn == NULL){
3642                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle);
3643                     if (iso_stream != NULL){
3644                         if (iso_stream->num_packets_sent >= num_packets) {
3645                             iso_stream->num_packets_sent -= num_packets;
3646                         } else {
3647                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3648                             iso_stream->num_packets_sent = 0;
3649                         }
3650                         if (iso_stream->iso_type == HCI_ISO_TYPE_BIS){
3651                             le_audio_big_t * big = hci_big_for_handle(iso_stream->group_id);
3652                             if (big != NULL){
3653                                 big->num_completed_timestamp_current_valid = true;
3654                                 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms();
3655                             }
3656                         }
3657                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3658                                  num_packets, handle, iso_stream->num_packets_sent);
3659                         notify_iso = true;
3660                     }
3661                 }
3662 #endif
3663             }
3664 
3665 #ifdef ENABLE_CLASSIC
3666             if (notify_sco){
3667                 hci_notify_if_sco_can_send_now();
3668             }
3669 #endif
3670 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3671             if (notify_iso){
3672                 hci_iso_notify_can_send_now();
3673             }
3674 #endif
3675             break;
3676         }
3677 
3678 #ifdef ENABLE_CLASSIC
3679         case HCI_EVENT_FLUSH_OCCURRED:
3680             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
3681             handle = hci_event_flush_occurred_get_handle(packet);
3682             conn = hci_connection_for_handle(handle);
3683             if (conn) {
3684                 log_info("Flush occurred, disconnect 0x%04x", handle);
3685                 conn->state = SEND_DISCONNECT;
3686             }
3687             break;
3688 
3689         case HCI_EVENT_INQUIRY_COMPLETE:
3690             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3691                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3692                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
3693                 hci_emit_event(event, sizeof(event), 1);
3694             }
3695             break;
3696         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3697             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3698                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3699             }
3700             break;
3701         case HCI_EVENT_CONNECTION_REQUEST:
3702             reverse_bd_addr(&packet[2], addr);
3703             link_type = (hci_link_type_t) packet[11];
3704 
3705             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
3706             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
3707                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
3708                 bd_addr_copy(hci_stack->decline_addr, addr);
3709                 break;
3710             }
3711 
3712             if (hci_stack->gap_classic_accept_callback != NULL){
3713                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3714                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
3715                     bd_addr_copy(hci_stack->decline_addr, addr);
3716                     break;
3717                 }
3718             }
3719 
3720             // TODO: eval COD 8-10
3721             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
3722             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
3723             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3724             if (!conn) {
3725                 conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_SLAVE);
3726             }
3727             if (!conn) {
3728                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
3729                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3730                 bd_addr_copy(hci_stack->decline_addr, addr);
3731                 hci_run();
3732                 // avoid event to higher layer
3733                 return;
3734             }
3735             conn->state = RECEIVED_CONNECTION_REQUEST;
3736             // store info about eSCO
3737             if (link_type == HCI_LINK_TYPE_ESCO){
3738                 conn->remote_supported_features[0] |= 1;
3739             }
3740             // propagate remote supported sco packet packets from existing ACL to new SCO connection
3741             if (addr_type == BD_ADDR_TYPE_SCO){
3742                 const hci_connection_t * acl_conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3743                 // ACL exists unless fuzzing
3744                 if (acl_conn != NULL) {
3745                     conn->remote_supported_sco_packets = acl_conn->remote_supported_sco_packets;
3746                 }
3747             }
3748             hci_run();
3749             break;
3750 
3751         case HCI_EVENT_CONNECTION_COMPLETE:
3752             // Connection management
3753             reverse_bd_addr(&packet[5], addr);
3754             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3755             addr_type = BD_ADDR_TYPE_ACL;
3756             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3757             if (conn) {
3758                 switch (conn->state){
3759                     // expected states
3760                     case ACCEPTED_CONNECTION_REQUEST:
3761                     case SENT_CREATE_CONNECTION:
3762                         break;
3763                     // unexpected state -> ignore
3764                     default:
3765                         // don't forward event to app
3766                         return;
3767                 }
3768                 if (!packet[2]){
3769                     conn->state = OPEN;
3770                     conn->con_handle = little_endian_read_16(packet, 3);
3771 
3772                     // trigger write supervision timeout if we're master
3773                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
3774                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
3775                     }
3776 
3777                     // trigger write automatic flush timeout
3778                     if (hci_stack->automatic_flush_timeout != 0){
3779                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
3780                     }
3781 
3782                     // restart timer
3783                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3784                     btstack_run_loop_add_timer(&conn->timeout);
3785 
3786                     // trigger remote features for dedicated bonding
3787                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3788                         hci_trigger_remote_features_for_connection(conn);
3789                     }
3790 
3791                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3792 
3793                     hci_emit_nr_connections_changed();
3794                 } else {
3795                     // connection failed
3796                     hci_handle_connection_failed(conn, packet[2]);
3797                 }
3798             }
3799             break;
3800 
3801         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3802             reverse_bd_addr(&packet[5], addr);
3803             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3804             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3805 
3806             // SCO exists unless fuzzer
3807             if (conn == NULL) break;
3808 
3809             if (packet[2] != ERROR_CODE_SUCCESS){
3810                 // connection failed, remove entry
3811                 hci_handle_connection_failed(conn, packet[2]);
3812                 break;
3813             }
3814 
3815             conn->state = OPEN;
3816             conn->con_handle = little_endian_read_16(packet, 3);
3817 
3818             // update sco payload length for eSCO connections
3819             if (hci_event_synchronous_connection_complete_get_tx_packet_length(packet) > 0){
3820                 conn->sco_payload_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet);
3821                 log_info("eSCO Complete, set payload len %u", conn->sco_payload_length);
3822             }
3823 
3824 #ifdef ENABLE_SCO_OVER_HCI
3825             // update SCO
3826             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3827                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3828             }
3829             // trigger can send now
3830             if (hci_have_usb_transport()){
3831                 hci_stack->sco_can_send_now = true;
3832             }
3833 
3834             // setup implict sco flow control
3835             conn->sco_tx_ready = 0;
3836             conn->sco_tx_active  = 0;
3837             conn->sco_established_ms = btstack_run_loop_get_time_ms();
3838 
3839 #endif
3840 #ifdef HAVE_SCO_TRANSPORT
3841             // configure sco transport
3842             if (hci_stack->sco_transport != NULL){
3843                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3844                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3845             }
3846 #endif
3847             break;
3848 
3849         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3850             handle = little_endian_read_16(packet, 3);
3851             conn = hci_connection_for_handle(handle);
3852             if (!conn) break;
3853             if (!packet[2]){
3854                 const uint8_t * features = &packet[5];
3855                 hci_handle_remote_features_page_0(conn, features);
3856 
3857                 // read extended features if possible
3858                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
3859                 && ((conn->remote_supported_features[0] & 2) != 0)) {
3860                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
3861                     break;
3862                 }
3863             }
3864             hci_handle_remote_features_received(conn);
3865             break;
3866 
3867         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3868             handle = little_endian_read_16(packet, 3);
3869             conn = hci_connection_for_handle(handle);
3870             if (!conn) break;
3871             // status = ok, page = 1
3872             if (!packet[2]) {
3873                 uint8_t page_number = packet[5];
3874                 uint8_t maximum_page_number = packet[6];
3875                 const uint8_t * features = &packet[7];
3876                 bool done = false;
3877                 switch (page_number){
3878                     case 1:
3879                         hci_handle_remote_features_page_1(conn, features);
3880                         if (maximum_page_number >= 2){
3881                             // get Secure Connections (Controller) from Page 2 if available
3882                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
3883                         } else {
3884                             // otherwise, assume SC (Controller) == SC (Host)
3885                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
3886                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
3887                             }
3888                             done = true;
3889                         }
3890                         break;
3891                     case 2:
3892                         hci_handle_remote_features_page_2(conn, features);
3893                         done = true;
3894                         break;
3895                     default:
3896                         break;
3897                 }
3898                 if (!done) break;
3899             }
3900             hci_handle_remote_features_received(conn);
3901             break;
3902 
3903         case HCI_EVENT_LINK_KEY_REQUEST:
3904 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
3905             hci_event_link_key_request_get_bd_addr(packet, addr);
3906             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3907             if (!conn) break;
3908 
3909             // lookup link key in db if not cached
3910             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
3911                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
3912             }
3913 
3914             // response sent by hci_run()
3915             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
3916 #endif
3917             break;
3918 
3919         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
3920             hci_event_link_key_request_get_bd_addr(packet, addr);
3921             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3922             if (!conn) break;
3923 
3924             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
3925 
3926             // CVE-2020-26555: ignore NULL link key
3927             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
3928             if (btstack_is_null(&packet[8], 16)) break;
3929 
3930             link_key_type_t link_key_type = (link_key_type_t)packet[24];
3931             // Change Connection Encryption keeps link key type
3932             if (link_key_type != CHANGED_COMBINATION_KEY){
3933                 conn->link_key_type = link_key_type;
3934             }
3935 
3936             // cache link key. link keys stored in little-endian format for legacy reasons
3937             memcpy(&conn->link_key, &packet[8], 16);
3938 
3939             // only store link key:
3940             // - if bondable enabled
3941             if (hci_stack->bondable == false) break;
3942             // - if security level sufficient
3943             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
3944             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
3945             break;
3946         }
3947 
3948         case HCI_EVENT_PIN_CODE_REQUEST:
3949             hci_event_pin_code_request_get_bd_addr(packet, addr);
3950             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3951             if (!conn) break;
3952 
3953             hci_pairing_started(conn, false);
3954             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
3955             if (!hci_stack->bondable ){
3956                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3957                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3958                 hci_run();
3959                 return;
3960             }
3961             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3962             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3963                 log_info("Level 4 required, but SC not supported -> abort");
3964                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3965                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3966                 hci_run();
3967                 return;
3968             }
3969             break;
3970 
3971         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
3972             hci_event_io_capability_response_get_bd_addr(packet, addr);
3973             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3974             if (!conn) break;
3975 
3976             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
3977             hci_pairing_started(conn, true);
3978             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3979             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3980 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3981             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3982 #endif
3983             break;
3984 
3985         case HCI_EVENT_IO_CAPABILITY_REQUEST:
3986             hci_event_io_capability_response_get_bd_addr(packet, addr);
3987             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3988             if (!conn) break;
3989 
3990             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
3991             hci_connection_timestamp(conn);
3992             hci_pairing_started(conn, true);
3993             break;
3994 
3995 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3996         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
3997             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
3998             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3999             if (!conn) break;
4000 
4001             hci_connection_timestamp(conn);
4002 
4003             hci_pairing_started(conn, true);
4004 
4005             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
4006             break;
4007 #endif
4008 
4009         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
4010             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
4011             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4012             if (!conn) break;
4013             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
4014                 if (hci_stack->ssp_auto_accept){
4015                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4016                 };
4017             } else {
4018                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
4019                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4020                 // don't forward event to app
4021                 hci_run();
4022                 return;
4023             }
4024             break;
4025 
4026         case HCI_EVENT_USER_PASSKEY_REQUEST:
4027             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
4028             if (hci_stack->ssp_auto_accept){
4029                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4030             };
4031             break;
4032 
4033         case HCI_EVENT_MODE_CHANGE:
4034             handle = hci_event_mode_change_get_handle(packet);
4035             conn = hci_connection_for_handle(handle);
4036             if (!conn) break;
4037             conn->connection_mode = hci_event_mode_change_get_mode(packet);
4038             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
4039             break;
4040 #endif
4041 
4042         case HCI_EVENT_ENCRYPTION_CHANGE:
4043         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
4044             handle = hci_event_encryption_change_get_connection_handle(packet);
4045             conn = hci_connection_for_handle(handle);
4046             if (!conn) break;
4047             if (hci_event_encryption_change_get_status(packet) == ERROR_CODE_SUCCESS) {
4048                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
4049                 if (encryption_enabled){
4050                     if (hci_is_le_connection(conn)){
4051                         // For LE, we accept connection as encrypted
4052                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
4053                     }
4054 #ifdef ENABLE_CLASSIC
4055                     else {
4056 
4057                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
4058                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
4059                         bool connected_uses_aes_ccm = encryption_enabled == 2;
4060                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
4061 #ifdef ENABLE_TESTING_SUPPORT
4062                             // The following tests require to reject L2CAP connection as SC has been disabled on the remote
4063                             // - GAP/SEC/SEM/BI-31-C
4064                             // - GAP/SEC/SEM/BI-32-C
4065                             // - GAP/SEC/SEM/BI-33-C
4066 
4067                             // Our release code (aggressively) disconnects the HCI connection, without a chance to respond to PTS
4068                             // To pass the tests, we only downgrade the link key type instead of the more secure disconnect
4069                             link_key_type_t new_link_key_type = UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
4070                             if (conn->link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256){
4071                                 new_link_key_type = AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
4072                             }
4073                             log_info("SC during pairing, but only E0 now -> downgrade link key type from %u to %u",
4074                                      conn->link_key_type, new_link_key_type);
4075                             conn->link_key_type = new_link_key_type;
4076 #else
4077                             log_info("SC during pairing, but only E0 now -> abort");
4078                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
4079                             break;
4080 #endif
4081                         }
4082 
4083 #ifdef ENABLE_MUTUAL_AUTHENTICATION_FOR_LEGACY_SECURE_CONNECTIONS
4084                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
4085                         if (connected_uses_aes_ccm){
4086                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4087                         }
4088 #else
4089                         // We consider even Legacy Secure Connections as authenticated as BTstack mandates encryption
4090                         // with encryption key size > hci_stack->gap_required_encyrption_key_size
4091                         // for all operations that require any security. See BIAS attacks.
4092                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4093 #endif
4094                         // validate encryption key size
4095                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
4096                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
4097                             // already got encryption key size
4098                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
4099                         } else {
4100                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
4101                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
4102                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4103                             } else {
4104                                 // if not, pretend everything is perfect
4105                                 hci_handle_read_encryption_key_size_complete(conn, 16);
4106                             }
4107                         }
4108                     }
4109 #endif
4110                 } else {
4111                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
4112                 }
4113             } else {
4114 #ifdef ENABLE_CLASSIC
4115                 if (!hci_is_le_connection(conn)){
4116                     uint8_t status = hci_event_encryption_change_get_status(packet);
4117                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
4118                         conn->bonding_flags &= ~BONDING_DEDICATED;
4119                         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
4120                         conn->bonding_status = status;
4121                     }
4122                     // trigger security update -> level 0
4123                     hci_handle_mutual_authentication_completed(conn);
4124                 }
4125 #endif
4126             }
4127 
4128             break;
4129 
4130 #ifdef ENABLE_CLASSIC
4131         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
4132             handle = hci_event_authentication_complete_get_connection_handle(packet);
4133             conn = hci_connection_for_handle(handle);
4134             if (!conn) break;
4135 
4136             // clear authentication active flag
4137             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
4138             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
4139 
4140             // authenticated only if auth status == 0
4141             if (hci_event_authentication_complete_get_status(packet) == 0){
4142                 // authenticated
4143                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4144 
4145                 // If not already encrypted, start encryption
4146                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
4147                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4148                     break;
4149                 }
4150             }
4151 
4152             // emit updated security level (will be 0 if not authenticated)
4153             hci_handle_mutual_authentication_completed(conn);
4154             break;
4155 
4156         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
4157             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
4158             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4159             if (!conn) break;
4160 
4161             // treat successfully paired connection as authenticated
4162             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
4163                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4164             }
4165 
4166             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
4167             break;
4168 #endif
4169 
4170         // HCI_EVENT_DISCONNECTION_COMPLETE
4171         // has been split, to first notify stack before shutting connection down
4172         // see end of function, too.
4173         case HCI_EVENT_DISCONNECTION_COMPLETE:
4174             if (packet[2]) break;   // status != 0
4175             handle = little_endian_read_16(packet, 3);
4176             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
4177             if (hci_stack->acl_fragmentation_total_size > 0u) {
4178                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4179                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
4180                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
4181                     hci_stack->acl_fragmentation_total_size = 0;
4182                     hci_stack->acl_fragmentation_pos = 0;
4183                     if (release_buffer){
4184                         hci_release_packet_buffer();
4185                     }
4186                 }
4187             }
4188 
4189 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4190             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
4191             if (hci_stack->iso_fragmentation_total_size > 0u) {
4192                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4193                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
4194                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
4195                     hci_stack->iso_fragmentation_total_size = 0;
4196                     hci_stack->iso_fragmentation_pos = 0;
4197                     if (release_buffer){
4198                         hci_release_packet_buffer();
4199                     }
4200                 }
4201             }
4202 
4203             // finalize iso stream for CIS handle
4204             iso_stream = hci_iso_stream_for_con_handle(handle);
4205             if (iso_stream != NULL){
4206                 hci_iso_stream_finalize(iso_stream);
4207                 break;
4208             }
4209 
4210             // finalize iso stream(s) for ACL handle
4211             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4212             while (btstack_linked_list_iterator_has_next(&it)){
4213                 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4214                 if (iso_stream->acl_handle == handle ) {
4215                     hci_iso_stream_finalize(iso_stream);
4216                 }
4217             }
4218 #endif
4219 
4220 #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
4221             if ((handle != HCI_CON_HANDLE_INVALID) && (handle == hci_stack->hci_command_con_handle)){
4222                 // we did not receive a HCI Command Complete or HCI Command Status event for the disconnected connection
4223                 // if needed, we could also track the hci command opcode and simulate a hci command complete with status
4224                 // but the connection has failed anyway, so for now, we only set the num hci commands back to 1
4225                 log_info("Disconnect for conn handle 0x%04x in pending HCI command, assume command failed", handle);
4226                 hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4227                 hci_stack->num_cmd_packets = 1;
4228             }
4229 #endif
4230 
4231             conn = hci_connection_for_handle(handle);
4232             if (!conn) break;
4233 #ifdef ENABLE_CLASSIC
4234             // pairing failed if it was ongoing
4235             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4236 #endif
4237 
4238             // emit dedicatd bonding event
4239             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
4240                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
4241             }
4242 
4243             // mark connection for shutdown, stop timers, reset state
4244             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
4245             hci_connection_stop_timer(conn);
4246             hci_connection_init(conn);
4247 
4248 #ifdef ENABLE_BLE
4249 #ifdef ENABLE_LE_PERIPHERAL
4250             // re-enable advertisements for le connections if active
4251             if (hci_is_le_connection(conn)){
4252                 hci_update_advertisements_enabled_for_current_roles();
4253             }
4254 #endif
4255 #endif
4256             break;
4257 
4258         case HCI_EVENT_HARDWARE_ERROR:
4259             log_error("Hardware Error: 0x%02x", packet[2]);
4260             if (hci_stack->hardware_error_callback){
4261                 (*hci_stack->hardware_error_callback)(packet[2]);
4262             } else {
4263                 // if no special requests, just reboot stack
4264                 hci_power_control_off();
4265                 hci_power_control_on();
4266             }
4267             break;
4268 
4269 #ifdef ENABLE_CLASSIC
4270         case HCI_EVENT_ROLE_CHANGE:
4271             if (packet[2]) break;   // status != 0
4272             reverse_bd_addr(&packet[3], addr);
4273             addr_type = BD_ADDR_TYPE_ACL;
4274             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4275             if (!conn) break;
4276             conn->role = (hci_role_t) packet[9];
4277             break;
4278 #endif
4279 
4280         case HCI_EVENT_TRANSPORT_PACKET_SENT:
4281             // release packet buffer only for asynchronous transport and if there are not further fragments
4282             if (hci_transport_synchronous()) {
4283                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
4284                 return; // instead of break: to avoid re-entering hci_run()
4285             }
4286             hci_stack->acl_fragmentation_tx_active = 0;
4287 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4288             hci_stack->iso_fragmentation_tx_active = 0;
4289             if (hci_stack->iso_fragmentation_total_size) break;
4290 #endif
4291             if (hci_stack->acl_fragmentation_total_size) break;
4292 
4293             // release packet buffer without HCI_EVENT_TRANSPORT_PACKET_SENT (as it will be later)
4294             btstack_assert(hci_stack->hci_packet_buffer_reserved);
4295             hci_stack->hci_packet_buffer_reserved = false;
4296 
4297 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4298             hci_iso_notify_can_send_now();
4299 #endif
4300             // L2CAP receives this event via the hci_emit_event below
4301 
4302 #ifdef ENABLE_CLASSIC
4303             // For SCO, we do the can_send_now_check here
4304             hci_notify_if_sco_can_send_now();
4305 #endif
4306             break;
4307 
4308 #ifdef ENABLE_CLASSIC
4309         case HCI_EVENT_SCO_CAN_SEND_NOW:
4310             // For SCO, we do the can_send_now_check here
4311             hci_stack->sco_can_send_now = true;
4312             hci_notify_if_sco_can_send_now();
4313             return;
4314 
4315         // explode inquriy results for easier consumption
4316         case HCI_EVENT_INQUIRY_RESULT:
4317         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4318         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4319             gap_inquiry_explode(packet, size);
4320             break;
4321 #endif
4322 
4323 #ifdef ENABLE_BLE
4324         case HCI_EVENT_LE_META:
4325             switch (packet[2]){
4326 #ifdef ENABLE_LE_CENTRAL
4327                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
4328                     if (!hci_stack->le_scanning_enabled) break;
4329                     le_handle_advertisement_report(packet, size);
4330                     break;
4331 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4332                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
4333                     if (!hci_stack->le_scanning_enabled) break;
4334                     le_handle_extended_advertisement_report(packet, size);
4335                     break;
4336                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
4337                     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
4338                     hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE;
4339                     break;
4340                 case HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED:
4341                     advertising_handle = hci_subevent_le_advertising_set_terminated_get_advertising_handle(packet);
4342                     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4343                     while (btstack_linked_list_iterator_has_next(&it)) {
4344                         le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
4345                         if (advertising_set->advertising_handle == advertising_handle){
4346                             advertising_set->state &= ~(LE_ADVERTISEMENT_STATE_ACTIVE | LE_ADVERTISEMENT_STATE_ENABLED);
4347                         }
4348                     }
4349                     break;
4350 #endif
4351 #endif
4352                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
4353                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
4354                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
4355                     hci_handle_le_connection_complete_event(packet);
4356                     break;
4357 
4358                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
4359                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
4360                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
4361                     conn = hci_connection_for_handle(handle);
4362                     if (!conn) break;
4363                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
4364                     break;
4365 
4366                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
4367                     // connection
4368                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
4369                     conn = hci_connection_for_handle(handle);
4370                     if (conn) {
4371                         // read arguments
4372                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
4373                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
4374                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
4375                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
4376 
4377                         // validate against current connection parameter range
4378                         le_connection_parameter_range_t existing_range;
4379                         gap_get_connection_parameter_range(&existing_range);
4380                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4381                         if (update_parameter){
4382                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
4383                             conn->le_conn_interval_min = le_conn_interval_min;
4384                             conn->le_conn_interval_max = le_conn_interval_max;
4385                             conn->le_conn_latency = le_conn_latency;
4386                             conn->le_supervision_timeout = le_supervision_timeout;
4387                         } else {
4388                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
4389                         }
4390                     }
4391                     break;
4392 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
4393                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
4394                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
4395                     conn = hci_connection_for_handle(handle);
4396                     if (conn) {
4397                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
4398                     }
4399                     break;
4400 #endif
4401 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4402                 case HCI_SUBEVENT_LE_CIS_REQUEST:
4403                     // incoming CIS request, allocate iso stream object and cache metadata
4404                     iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_ISO_STREAM_W4_USER,
4405                                                        hci_subevent_le_cis_request_get_cig_id(packet),
4406                                                        hci_subevent_le_cis_request_get_cis_id(packet));
4407                     // if there's no memory, gap_cis_accept/gap_cis_reject will fail
4408                     if (iso_stream != NULL){
4409                         iso_stream->cis_handle = hci_subevent_le_cis_request_get_cis_connection_handle(packet);
4410                         iso_stream->acl_handle = hci_subevent_le_cis_request_get_acl_connection_handle(packet);
4411                     }
4412                     break;
4413                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
4414                     if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
4415                         handle = hci_subevent_le_cis_established_get_connection_handle(packet);
4416                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
4417                         iso_stream = hci_iso_stream_for_con_handle(handle);
4418                         btstack_assert(iso_stream != NULL);
4419                         // track connection info
4420                         iso_stream->number_of_subevents  = hci_subevent_le_cis_established_get_nse(packet);
4421                         iso_stream->burst_number_c_to_p  = hci_subevent_le_cis_established_get_bn_c_to_p(packet);
4422                         iso_stream->burst_number_p_to_c  = hci_subevent_le_cis_established_get_bn_p_to_c(packet);
4423                         iso_stream->flush_timeout_c_to_p = hci_subevent_le_cis_established_get_ft_c_to_p(packet);
4424                         iso_stream->flush_timeout_p_to_c = hci_subevent_le_cis_established_get_ft_p_to_c(packet);
4425                         iso_stream->max_sdu_c_to_p       = hci_subevent_le_cis_established_get_max_pdu_c_to_p(packet);
4426                         iso_stream->max_sdu_p_to_c       = hci_subevent_le_cis_established_get_max_pdu_p_to_c(packet);
4427                         iso_stream->iso_interval_1250us  = hci_subevent_le_cis_established_get_iso_interval(packet);
4428                         if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
4429                             // CIS Accept by Peripheral
4430                             if (status == ERROR_CODE_SUCCESS){
4431                                 if (iso_stream->max_sdu_p_to_c > 0){
4432                                     // we're peripheral and we will send data
4433                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT;
4434                                 } else {
4435                                     // we're peripheral and we will only receive data
4436                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
4437                                 }
4438                             } else {
4439                                 hci_cis_handle_created(iso_stream, status);
4440                             }
4441                             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4442                         } else {
4443                             // CIG Setup by Central
4444                             le_audio_cig_t * cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
4445                             btstack_assert(cig != NULL);
4446                             // update iso stream state
4447                             if (status == ERROR_CODE_SUCCESS){
4448                                 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4449                             } else {
4450                                 iso_stream->state = HCI_ISO_STREAM_STATE_IDLE;
4451                             }
4452                             // update cig state
4453                             uint8_t i;
4454                             for (i=0;i<cig->num_cis;i++){
4455                                 if (cig->cis_con_handles[i] == handle){
4456                                     cig->cis_setup_active[i] = false;
4457                                     if (status == ERROR_CODE_SUCCESS){
4458                                         cig->cis_established[i] = true;
4459                                     } else {
4460                                         hci_cis_handle_created(iso_stream, status);
4461                                     }
4462                                 }
4463                             }
4464 
4465                             // trigger iso path setup if complete
4466                             bool cis_setup_active = false;
4467                             for (i=0;i<cig->num_cis;i++){
4468                                 cis_setup_active |= cig->cis_setup_active[i];
4469                             }
4470                             if (cis_setup_active == false){
4471                                 cig->state_vars.next_cis = 0;
4472                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
4473                                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4474                             }
4475                         }
4476                     }
4477                     break;
4478                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
4479                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4480                     big = hci_big_for_handle(packet[4]);
4481                     if (big != NULL){
4482                         uint8_t status = packet[3];
4483                         if (status == ERROR_CODE_SUCCESS){
4484                             // store bis_con_handles and trigger iso path setup
4485                             uint8_t num_bis = btstack_min(big->num_bis, packet[20]);
4486                             uint8_t i;
4487                             for (i=0;i<num_bis;i++){
4488                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4489                                 big->bis_con_handles[i] = bis_handle;
4490                                 // assign bis handle
4491                                 btstack_linked_list_iterator_t it;
4492                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4493                                 while (btstack_linked_list_iterator_has_next(&it)){
4494                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4495                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4496                                         (iso_stream->group_id == big->big_handle)){
4497                                         iso_stream->cis_handle = bis_handle;
4498                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4499                                         break;
4500                                     }
4501                                 }
4502                             }
4503                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4504                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4505                                 big->state_vars.next_bis = 0;
4506                             }
4507                         } else {
4508                             // create BIG failed or has been stopped by us
4509                             hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
4510                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4511                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
4512                                 hci_emit_big_created(big, status);
4513                             } else {
4514                                 hci_emit_big_terminated(big);
4515                             }
4516                         }
4517                     }
4518                     break;
4519                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4520                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4521                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
4522                     if (big != NULL){
4523                         // finalize associated ISO streams
4524                         btstack_linked_list_iterator_t it;
4525                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4526                         while (btstack_linked_list_iterator_has_next(&it)){
4527                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4528                             if (iso_stream->group_id == big->big_handle){
4529                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->cis_handle);
4530                                 btstack_linked_list_iterator_remove(&it);
4531                                 btstack_memory_hci_iso_stream_free(iso_stream);
4532                             }
4533                         }
4534                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
4535                         switch (big->state){
4536                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
4537                                 hci_emit_big_created(big, big->state_vars.status);
4538                                 break;
4539                             default:
4540                                 hci_emit_big_terminated(big);
4541                                 break;
4542                         }
4543                     }
4544                     break;
4545                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4546                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4547                     big_sync = hci_big_sync_for_handle(packet[4]);
4548                     if (big_sync != NULL){
4549                         uint8_t status = packet[3];
4550                         uint8_t big_handle = packet[4];
4551                         if (status == ERROR_CODE_SUCCESS){
4552                             // store bis_con_handles and trigger iso path setup
4553                             uint8_t num_bis = btstack_min(big_sync->num_bis, packet[16]);
4554                             uint8_t i;
4555                             for (i=0;i<num_bis;i++){
4556                                 hci_con_handle_t bis_handle = little_endian_read_16(packet, 17 + (2 * i));
4557                                 big_sync->bis_con_handles[i] = bis_handle;
4558                                 // setup iso_stream_t
4559                                 btstack_linked_list_iterator_t it;
4560                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4561                                 while (btstack_linked_list_iterator_has_next(&it)){
4562                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4563                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
4564                                         (iso_stream->group_id == big_sync->big_handle)){
4565                                         iso_stream->cis_handle = bis_handle;
4566                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4567                                         break;
4568                                     }
4569                                 }
4570                             }
4571                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4572                                 // trigger iso path setup
4573                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4574                                 big_sync->state_vars.next_bis = 0;
4575                             }
4576                         } else {
4577                             // create BIG Sync failed or has been stopped by us
4578                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4579                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4580                                 hci_emit_big_sync_created(big_sync, status);
4581                             } else {
4582                                 hci_emit_big_sync_stopped(big_handle);
4583                             }
4584                         }
4585                     }
4586                     break;
4587                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4588                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4589                     big_sync = hci_big_sync_for_handle(packet[4]);
4590                     if (big_sync != NULL){
4591                         uint8_t big_handle = packet[4];
4592                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4593                         hci_emit_big_sync_stopped(big_handle);
4594                     }
4595                     break;
4596 #endif
4597                 default:
4598                     break;
4599             }
4600             break;
4601 #endif
4602         case HCI_EVENT_VENDOR_SPECIFIC:
4603             // Vendor specific commands often create vendor specific event instead of num completed packets
4604             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
4605             switch (hci_stack->manufacturer){
4606                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
4607                     hci_stack->num_cmd_packets = 1;
4608                     break;
4609                 default:
4610                     break;
4611             }
4612             break;
4613         default:
4614             break;
4615     }
4616 
4617     handle_event_for_current_stack_state(packet, size);
4618 
4619     // notify upper stack
4620 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
4621 
4622     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4623     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4624 		handle = little_endian_read_16(packet, 3);
4625 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4626 		// discard connection if app did not trigger a reconnect in the event handler
4627 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
4628 			hci_shutdown_connection(aConn);
4629 		}
4630 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
4631         hci_controller_dump_packets();
4632 #endif
4633     }
4634 
4635 	// execute main loop
4636 	hci_run();
4637 }
4638 
4639 #ifdef ENABLE_CLASSIC
4640 
4641 static void sco_handler(uint8_t * packet, uint16_t size){
4642     // lookup connection struct
4643     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
4644     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
4645     if (!conn) return;
4646 
4647 #ifdef ENABLE_SCO_OVER_HCI
4648     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4649     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4650         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4651             packet[2] = 0x3c;
4652             memmove(&packet[3], &packet[23], 63);
4653             size = 63;
4654         }
4655     }
4656 
4657     if (hci_have_usb_transport()){
4658         // Nothing to do
4659     } else {
4660         // 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);
4661         if (hci_stack->synchronous_flow_control_enabled == 0){
4662             // ignore received SCO packets for the first 10 ms, then allow for max two HCI_SCO_2EV3_SIZE packets
4663             uint16_t max_sco_packets = btstack_min(2 * HCI_SCO_2EV3_SIZE / conn->sco_payload_length, hci_stack->sco_packets_total_num);
4664             if (conn->sco_tx_active == 0){
4665                 if (btstack_time_delta(btstack_run_loop_get_time_ms(), conn->sco_established_ms) > 10){
4666                     conn->sco_tx_active = 1;
4667                     conn->sco_tx_ready = max_sco_packets;
4668                     log_info("Start SCO sending, %u packets", conn->sco_tx_ready);
4669                     hci_notify_if_sco_can_send_now();
4670                 }
4671             } else {
4672                 if (conn->sco_tx_ready < max_sco_packets){
4673                     conn->sco_tx_ready++;
4674                 }
4675                 hci_notify_if_sco_can_send_now();
4676             }
4677         }
4678     }
4679 #endif
4680 
4681     // deliver to app
4682     if (hci_stack->sco_packet_handler) {
4683         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
4684     }
4685 
4686 #ifdef HAVE_SCO_TRANSPORT
4687     // We can send one packet for each received packet
4688     conn->sco_tx_ready++;
4689     hci_notify_if_sco_can_send_now();
4690 #endif
4691 
4692 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4693     conn->num_packets_completed++;
4694     hci_stack->host_completed_packets = 1;
4695     hci_run();
4696 #endif
4697 }
4698 #endif
4699 
4700 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
4701 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4702     // propagate ISO packets received as ACL
4703     hci_iso_stream_t * iso_stream = NULL;
4704     if ((packet_type == HCI_ACL_DATA_PACKET) && (size >= HCI_ACL_HEADER_SIZE)){
4705         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
4706         iso_stream = hci_iso_stream_for_con_handle(con_handle);
4707         if (iso_stream != NULL){
4708             packet_type = HCI_ISO_DATA_PACKET;
4709         }
4710     }
4711 #endif
4712 
4713     hci_dump_packet(packet_type, 1, packet, size);
4714     switch (packet_type) {
4715         case HCI_EVENT_PACKET:
4716             event_handler(packet, size);
4717             break;
4718         case HCI_ACL_DATA_PACKET:
4719             acl_handler(packet, size);
4720             break;
4721 #ifdef ENABLE_CLASSIC
4722         case HCI_SCO_DATA_PACKET:
4723             sco_handler(packet, size);
4724             break;
4725 #endif
4726 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4727         case HCI_ISO_DATA_PACKET:
4728             if ((iso_stream == NULL) && (size >= HCI_ISO_HEADER_SIZE)){
4729                 hci_con_handle_t con_handle = READ_ISO_CONNECTION_HANDLE(packet);
4730                 iso_stream = hci_iso_stream_for_con_handle(con_handle);
4731             }
4732             hci_iso_packet_handler(iso_stream, packet, size);
4733             break;
4734 #endif
4735         default:
4736             break;
4737     }
4738 }
4739 
4740 /**
4741  * @brief Add event packet handler.
4742  */
4743 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4744     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4745 }
4746 
4747 /**
4748  * @brief Remove event packet handler.
4749  */
4750 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
4751     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4752 }
4753 
4754 /** Register HCI packet handlers */
4755 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4756     hci_stack->acl_packet_handler = handler;
4757 }
4758 
4759 #ifdef ENABLE_CLASSIC
4760 /**
4761  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
4762  */
4763 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
4764     hci_stack->sco_packet_handler = handler;
4765 }
4766 #endif
4767 
4768 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4769 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
4770     hci_stack->iso_packet_handler = handler;
4771 }
4772 #endif
4773 
4774 static void hci_state_reset(void){
4775     // no connections yet
4776     hci_stack->connections = NULL;
4777 
4778     // keep discoverable/connectable as this has been requested by the client(s)
4779     // hci_stack->discoverable = 0;
4780     // hci_stack->connectable = 0;
4781     // hci_stack->bondable = 1;
4782     // hci_stack->own_addr_type = 0;
4783 
4784     // buffer is free
4785     hci_stack->hci_packet_buffer_reserved = false;
4786 
4787     // no pending cmds
4788     hci_stack->decline_reason = 0;
4789 
4790     hci_stack->secure_connections_active = false;
4791 
4792 #ifdef ENABLE_CLASSIC
4793     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
4794     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
4795 
4796     hci_stack->gap_tasks_classic =
4797             GAP_TASK_SET_DEFAULT_LINK_POLICY |
4798             GAP_TASK_SET_CLASS_OF_DEVICE |
4799             GAP_TASK_SET_LOCAL_NAME |
4800             GAP_TASK_SET_EIR_DATA |
4801             GAP_TASK_WRITE_SCAN_ENABLE |
4802             GAP_TASK_WRITE_PAGE_TIMEOUT;
4803 #endif
4804 
4805 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4806     hci_stack->classic_read_local_oob_data = false;
4807     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4808 #endif
4809 
4810     // LE
4811 #ifdef ENABLE_BLE
4812     memset(hci_stack->le_random_address, 0, 6);
4813     hci_stack->le_random_address_set = 0;
4814 #endif
4815 #ifdef ENABLE_LE_CENTRAL
4816     hci_stack->le_scanning_active  = false;
4817     hci_stack->le_scanning_param_update = true;
4818     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4819     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4820     hci_stack->le_whitelist_capacity = 0;
4821 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4822     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
4823 #endif
4824 #endif
4825 #ifdef ENABLE_LE_PERIPHERAL
4826     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4827     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4828         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4829     }
4830     if (hci_stack->le_advertisements_data != NULL){
4831         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4832     }
4833 #endif
4834 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4835     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION;
4836 #endif
4837 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4838     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4839     hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID;
4840 #endif
4841 #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
4842     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4843 #endif
4844 }
4845 
4846 #ifdef ENABLE_CLASSIC
4847 /**
4848  * @brief Configure Bluetooth hardware control. Has to be called before power on.
4849  */
4850 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
4851     // store and open remote device db
4852     hci_stack->link_key_db = link_key_db;
4853     if (hci_stack->link_key_db) {
4854         hci_stack->link_key_db->open();
4855     }
4856 }
4857 #endif
4858 
4859 void hci_init(const hci_transport_t *transport, const void *config){
4860 
4861 #ifdef HAVE_MALLOC
4862     if (!hci_stack) {
4863         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
4864     }
4865 #else
4866     hci_stack = &hci_stack_static;
4867 #endif
4868     memset(hci_stack, 0, sizeof(hci_stack_t));
4869 
4870     // reference to use transport layer implementation
4871     hci_stack->hci_transport = transport;
4872 
4873     // reference to used config
4874     hci_stack->config = config;
4875 
4876     // setup pointer for outgoing packet buffer
4877     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
4878 
4879     // max acl payload size defined in config.h
4880     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4881 
4882     // register packet handlers with transport
4883     transport->register_packet_handler(&packet_handler);
4884 
4885     hci_stack->state = HCI_STATE_OFF;
4886 
4887     // class of device
4888     hci_stack->class_of_device = 0x007a020c; // Smartphone
4889 
4890     // bondable by default
4891     hci_stack->bondable = 1;
4892 
4893 #ifdef ENABLE_CLASSIC
4894     // classic name
4895     hci_stack->local_name = default_classic_name;
4896 
4897     // Master slave policy
4898     hci_stack->master_slave_policy = 1;
4899 
4900     // Allow Role Switch
4901     hci_stack->allow_role_switch = 1;
4902 
4903     // Default / minimum security level = 2
4904     hci_stack->gap_security_level = LEVEL_2;
4905 
4906     // Default Security Mode 4
4907     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
4908 
4909     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4910     hci_stack->gap_required_encyrption_key_size = 7;
4911 
4912     // Link Supervision Timeout
4913     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4914 
4915     // All ACL packet types are enabledh
4916     hci_stack->enabled_packet_types_acl = ACL_PACKET_TYPES_ALL;
4917 #endif
4918 
4919     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
4920     hci_stack->ssp_enable = 1;
4921     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
4922     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4923     hci_stack->ssp_auto_accept = 1;
4924 
4925     // Secure Connections: enable (requires support from Controller)
4926     hci_stack->secure_connections_enable = true;
4927 
4928     // voice setting - signed 16 bit pcm data with CVSD over the air
4929     hci_stack->sco_voice_setting = 0x60;
4930 
4931 #ifdef ENABLE_BLE
4932     hci_stack->le_connection_scan_interval = 0x0060;   //    60 ms
4933     hci_stack->le_connection_scan_window   = 0x0030;    //   30 ms
4934     hci_stack->le_connection_interval_min  = 0x0008;    //   10 ms
4935     hci_stack->le_connection_interval_max  = 0x0018;    //   30 ms
4936     hci_stack->le_connection_latency       =      4;    //    4
4937     hci_stack->le_supervision_timeout      = 0x0048;    //  720 ms
4938     hci_stack->le_minimum_ce_length        =      0;    //    0 ms
4939     hci_stack->le_maximum_ce_length        =      0;    //    0 ms
4940 #endif
4941 
4942 #ifdef ENABLE_LE_CENTRAL
4943     hci_stack->le_connection_phys          =   0x01;    // LE 1M PHY
4944 
4945     // default LE Scanning
4946     hci_stack->le_scan_type     =  0x01; // active
4947     hci_stack->le_scan_interval = 0x1e0; // 300 ms
4948     hci_stack->le_scan_window   =  0x30; //  30 ms
4949     hci_stack->le_scan_phys     =  0x01; // LE 1M PHY
4950 #endif
4951 
4952 #ifdef ENABLE_LE_PERIPHERAL
4953     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4954 
4955     // default advertising parameters from Core v5.4 -- needed to use random address without prior adv setup
4956     hci_stack->le_advertisements_interval_min =                         0x0800;
4957     hci_stack->le_advertisements_interval_max =                         0x0800;
4958     hci_stack->le_advertisements_type =                                      0;
4959     hci_stack->le_own_addr_type =                       BD_ADDR_TYPE_LE_PUBLIC;
4960     hci_stack->le_advertisements_direct_address_type =  BD_ADDR_TYPE_LE_PUBLIC;
4961     hci_stack->le_advertisements_channel_map =                            0x07;
4962     hci_stack->le_advertisements_filter_policy =                             0;
4963 #endif
4964 
4965     // connection parameter range used to answer connection parameter update requests in l2cap
4966     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4967     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4968     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4969     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4970     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4971     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4972 
4973 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4974     hci_stack->iso_packets_to_queue = 1;
4975 #endif
4976 
4977 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4978     hci_stack->le_privacy_mode = LE_PRIVACY_MODE_DEVICE;
4979 #endif
4980 
4981     hci_state_reset();
4982 }
4983 
4984 void hci_deinit(void){
4985     btstack_run_loop_remove_timer(&hci_stack->timeout);
4986 #ifdef HAVE_MALLOC
4987     if (hci_stack) {
4988         free(hci_stack);
4989     }
4990 #endif
4991     hci_stack = NULL;
4992 
4993 #ifdef ENABLE_CLASSIC
4994     disable_l2cap_timeouts = 0;
4995 #endif
4996 }
4997 
4998 /**
4999  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
5000  */
5001 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
5002     hci_stack->chipset = chipset_driver;
5003 
5004     // reset chipset driver - init is also called on power_up
5005     if (hci_stack->chipset && hci_stack->chipset->init){
5006         hci_stack->chipset->init(hci_stack->config);
5007     }
5008 }
5009 
5010 void hci_enable_custom_pre_init(void){
5011     hci_stack->chipset_pre_init = true;
5012 }
5013 
5014 /**
5015  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
5016  */
5017 void hci_set_control(const btstack_control_t *hardware_control){
5018     // references to used control implementation
5019     hci_stack->control = hardware_control;
5020     // init with transport config
5021     hardware_control->init(hci_stack->config);
5022 }
5023 
5024 static void hci_discard_connections(void){
5025     btstack_linked_list_iterator_t it;
5026     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5027     while (btstack_linked_list_iterator_has_next(&it)){
5028         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
5029         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
5030         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
5031         hci_shutdown_connection(connection);
5032     }
5033 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5034     while (hci_stack->iso_streams != NULL){
5035         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
5036     }
5037 #endif
5038 }
5039 
5040 void hci_close(void){
5041 
5042 #ifdef ENABLE_CLASSIC
5043     // close remote device db
5044     if (hci_stack->link_key_db) {
5045         hci_stack->link_key_db->close();
5046     }
5047 #endif
5048 
5049     hci_discard_connections();
5050 
5051     hci_power_control(HCI_POWER_OFF);
5052 
5053 #ifdef HAVE_MALLOC
5054     free(hci_stack);
5055 #endif
5056     hci_stack = NULL;
5057 }
5058 
5059 #ifdef HAVE_SCO_TRANSPORT
5060 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
5061     hci_stack->sco_transport = sco_transport;
5062     sco_transport->register_packet_handler(&packet_handler);
5063 }
5064 #endif
5065 
5066 #ifdef ENABLE_CLASSIC
5067 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
5068     // validate ranage and set
5069     if (encryption_key_size < 7)  return;
5070     if (encryption_key_size > 16) return;
5071     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
5072 }
5073 
5074 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
5075     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
5076         hci_stack->gap_security_mode = security_mode;
5077         return ERROR_CODE_SUCCESS;
5078     } else {
5079         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
5080     }
5081 }
5082 
5083 gap_security_mode_t gap_get_security_mode(void){
5084     return hci_stack->gap_security_mode;
5085 }
5086 
5087 void gap_set_security_level(gap_security_level_t security_level){
5088     hci_stack->gap_security_level = security_level;
5089 }
5090 
5091 gap_security_level_t gap_get_security_level(void){
5092     if (hci_stack->gap_secure_connections_only_mode){
5093         return LEVEL_4;
5094     }
5095     return hci_stack->gap_security_level;
5096 }
5097 
5098 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
5099     hci_stack->gap_minimal_service_security_level = security_level;
5100 }
5101 
5102 void gap_set_secure_connections_only_mode(bool enable){
5103     hci_stack->gap_secure_connections_only_mode = enable;
5104 }
5105 
5106 bool gap_get_secure_connections_only_mode(void){
5107     return hci_stack->gap_secure_connections_only_mode;
5108 }
5109 #endif
5110 
5111 #ifdef ENABLE_CLASSIC
5112 void gap_set_class_of_device(uint32_t class_of_device){
5113     hci_stack->class_of_device = class_of_device;
5114     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
5115     hci_run();
5116 }
5117 
5118 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
5119     hci_stack->default_link_policy_settings = default_link_policy_settings;
5120     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
5121     hci_run();
5122 }
5123 
5124 void gap_set_allow_role_switch(bool allow_role_switch){
5125     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
5126 }
5127 
5128 uint8_t hci_get_allow_role_switch(void){
5129     return  hci_stack->allow_role_switch;
5130 }
5131 
5132 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
5133     hci_stack->link_supervision_timeout = link_supervision_timeout;
5134 }
5135 
5136 void gap_enable_link_watchdog(uint16_t timeout_ms){
5137     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
5138 }
5139 
5140 uint16_t hci_automatic_flush_timeout(void){
5141     return hci_stack->automatic_flush_timeout;
5142 }
5143 
5144 void hci_disable_l2cap_timeout_check(void){
5145     disable_l2cap_timeouts = 1;
5146 }
5147 #endif
5148 
5149 #ifndef HAVE_HOST_CONTROLLER_API
5150 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
5151 void hci_set_bd_addr(bd_addr_t addr){
5152     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
5153     hci_stack->custom_bd_addr_set = 1;
5154 }
5155 #endif
5156 
5157 // State-Module-Driver overview
5158 // state                    module  low-level
5159 // HCI_STATE_OFF             off      close
5160 // HCI_STATE_INITIALIZING,   on       open
5161 // HCI_STATE_WORKING,        on       open
5162 // HCI_STATE_HALTING,        on       open
5163 // HCI_STATE_SLEEPING,    off/sleep   close
5164 // HCI_STATE_FALLING_ASLEEP  on       open
5165 
5166 static int hci_power_control_on(void){
5167 
5168     // power on
5169     int err = 0;
5170     if (hci_stack->control && hci_stack->control->on){
5171         err = (*hci_stack->control->on)();
5172     }
5173     if (err){
5174         log_error( "POWER_ON failed");
5175         hci_emit_hci_open_failed();
5176         return err;
5177     }
5178 
5179     // int chipset driver
5180     if (hci_stack->chipset && hci_stack->chipset->init){
5181         hci_stack->chipset->init(hci_stack->config);
5182     }
5183 
5184     // init transport
5185     if (hci_stack->hci_transport->init){
5186         hci_stack->hci_transport->init(hci_stack->config);
5187     }
5188 
5189     // open transport
5190     err = hci_stack->hci_transport->open();
5191     if (err){
5192         log_error( "HCI_INIT failed, turning Bluetooth off again");
5193         if (hci_stack->control && hci_stack->control->off){
5194             (*hci_stack->control->off)();
5195         }
5196         hci_emit_hci_open_failed();
5197         return err;
5198     }
5199     return 0;
5200 }
5201 
5202 static void hci_power_control_off(void){
5203 
5204     log_info("hci_power_control_off");
5205 
5206     // close low-level device
5207     hci_stack->hci_transport->close();
5208 
5209     log_info("hci_power_control_off - hci_transport closed");
5210 
5211     // power off
5212     if (hci_stack->control && hci_stack->control->off){
5213         (*hci_stack->control->off)();
5214     }
5215 
5216     log_info("hci_power_control_off - control closed");
5217 
5218     hci_stack->state = HCI_STATE_OFF;
5219 }
5220 
5221 static void hci_power_control_sleep(void){
5222 
5223     log_info("hci_power_control_sleep");
5224 
5225 #if 0
5226     // don't close serial port during sleep
5227 
5228     // close low-level device
5229     hci_stack->hci_transport->close(hci_stack->config);
5230 #endif
5231 
5232     // sleep mode
5233     if (hci_stack->control && hci_stack->control->sleep){
5234         (*hci_stack->control->sleep)();
5235     }
5236 
5237     hci_stack->state = HCI_STATE_SLEEPING;
5238 }
5239 
5240 static int hci_power_control_wake(void){
5241 
5242     log_info("hci_power_control_wake");
5243 
5244     // wake on
5245     if (hci_stack->control && hci_stack->control->wake){
5246         (*hci_stack->control->wake)();
5247     }
5248 
5249 #if 0
5250     // open low-level device
5251     int err = hci_stack->hci_transport->open(hci_stack->config);
5252     if (err){
5253         log_error( "HCI_INIT failed, turning Bluetooth off again");
5254         if (hci_stack->control && hci_stack->control->off){
5255             (*hci_stack->control->off)();
5256         }
5257         hci_emit_hci_open_failed();
5258         return err;
5259     }
5260 #endif
5261 
5262     return 0;
5263 }
5264 
5265 static void hci_power_enter_initializing_state(void){
5266     // set up state machine
5267     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
5268     hci_stack->hci_packet_buffer_reserved = false;
5269     hci_stack->state = HCI_STATE_INITIALIZING;
5270 
5271 #ifndef HAVE_HOST_CONTROLLER_API
5272     if (hci_stack->chipset_pre_init) {
5273         hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
5274     } else
5275 #endif
5276     {
5277         hci_stack->substate = HCI_INIT_SEND_RESET;
5278     }
5279 }
5280 
5281 static void hci_power_enter_halting_state(void){
5282 #ifdef ENABLE_BLE
5283     // drop entries scheduled for removal, mark others for re-adding
5284     btstack_linked_list_iterator_t it;
5285     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5286     while (btstack_linked_list_iterator_has_next(&it)){
5287         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5288         if ((entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)) == LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5289             btstack_linked_list_iterator_remove(&it);
5290             btstack_memory_whitelist_entry_free(entry);
5291         } else {
5292             entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5293         }
5294     }
5295 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5296     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
5297     const uint8_t mask = LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5298     while (btstack_linked_list_iterator_has_next(&it)){
5299         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
5300         if ((entry->state & mask) == LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER) {
5301             btstack_linked_list_iterator_remove(&it);
5302             btstack_memory_periodic_advertiser_list_entry_free(entry);
5303         } else {
5304             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5305             continue;
5306         }
5307     }
5308 #endif
5309 #endif
5310     // see hci_run
5311     hci_stack->state = HCI_STATE_HALTING;
5312     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
5313     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
5314     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
5315     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5316     btstack_run_loop_add_timer(&hci_stack->timeout);
5317 }
5318 
5319 // returns error
5320 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
5321     int err;
5322     switch (power_mode){
5323         case HCI_POWER_ON:
5324             err = hci_power_control_on();
5325             if (err != 0) {
5326                 log_error("hci_power_control_on() error %d", err);
5327                 return err;
5328             }
5329             hci_power_enter_initializing_state();
5330             break;
5331         case HCI_POWER_OFF:
5332             // do nothing
5333             break;
5334         case HCI_POWER_SLEEP:
5335             // do nothing (with SLEEP == OFF)
5336             break;
5337         default:
5338             btstack_assert(false);
5339             break;
5340     }
5341     return ERROR_CODE_SUCCESS;
5342 }
5343 
5344 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
5345     switch (power_mode){
5346         case HCI_POWER_ON:
5347             // do nothing
5348             break;
5349         case HCI_POWER_OFF:
5350             // no connections yet, just turn it off
5351             hci_power_control_off();
5352             break;
5353         case HCI_POWER_SLEEP:
5354             // no connections yet, just turn it off
5355             hci_power_control_sleep();
5356             break;
5357         default:
5358             btstack_assert(false);
5359             break;
5360     }
5361     return ERROR_CODE_SUCCESS;
5362 }
5363 
5364 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
5365     switch (power_mode){
5366         case HCI_POWER_ON:
5367             // do nothing
5368             break;
5369         case HCI_POWER_OFF:
5370             hci_power_enter_halting_state();
5371             break;
5372         case HCI_POWER_SLEEP:
5373             // see hci_run
5374             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5375             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5376             break;
5377         default:
5378             btstack_assert(false);
5379             break;
5380     }
5381     return ERROR_CODE_SUCCESS;
5382 }
5383 
5384 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
5385     switch (power_mode){
5386         case HCI_POWER_ON:
5387             hci_power_enter_initializing_state();
5388             break;
5389         case HCI_POWER_OFF:
5390             // do nothing
5391             break;
5392         case HCI_POWER_SLEEP:
5393             // see hci_run
5394             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
5395             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
5396             break;
5397         default:
5398             btstack_assert(false);
5399             break;
5400     }
5401     return ERROR_CODE_SUCCESS;
5402 }
5403 
5404 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
5405     switch (power_mode){
5406         case HCI_POWER_ON:
5407             hci_power_enter_initializing_state();
5408             break;
5409         case HCI_POWER_OFF:
5410             hci_power_enter_halting_state();
5411             break;
5412         case HCI_POWER_SLEEP:
5413             // do nothing
5414             break;
5415         default:
5416             btstack_assert(false);
5417             break;
5418     }
5419     return ERROR_CODE_SUCCESS;
5420 }
5421 
5422 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
5423     int err;
5424     switch (power_mode){
5425         case HCI_POWER_ON:
5426             err = hci_power_control_wake();
5427             if (err) return err;
5428             hci_power_enter_initializing_state();
5429             break;
5430         case HCI_POWER_OFF:
5431             hci_power_enter_halting_state();
5432             break;
5433         case HCI_POWER_SLEEP:
5434             // do nothing
5435             break;
5436         default:
5437             btstack_assert(false);
5438             break;
5439     }
5440     return ERROR_CODE_SUCCESS;
5441 }
5442 
5443 int hci_power_control(HCI_POWER_MODE power_mode){
5444     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
5445     btstack_run_loop_remove_timer(&hci_stack->timeout);
5446     int err = 0;
5447     switch (hci_stack->state){
5448         case HCI_STATE_OFF:
5449             err = hci_power_control_state_off(power_mode);
5450             break;
5451         case HCI_STATE_INITIALIZING:
5452             err = hci_power_control_state_initializing(power_mode);
5453             break;
5454         case HCI_STATE_WORKING:
5455             err = hci_power_control_state_working(power_mode);
5456             break;
5457         case HCI_STATE_HALTING:
5458             err = hci_power_control_state_halting(power_mode);
5459             break;
5460         case HCI_STATE_FALLING_ASLEEP:
5461             err = hci_power_control_state_falling_asleep(power_mode);
5462             break;
5463         case HCI_STATE_SLEEPING:
5464             err = hci_power_control_state_sleeping(power_mode);
5465             break;
5466         default:
5467             btstack_assert(false);
5468             break;
5469     }
5470     if (err != 0){
5471         return err;
5472     }
5473 
5474     // create internal event
5475 	hci_emit_state();
5476 
5477 	// trigger next/first action
5478 	hci_run();
5479 
5480     return 0;
5481 }
5482 
5483 
5484 static void hci_halting_run(void) {
5485 
5486     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5487 
5488     hci_connection_t *connection;
5489 #ifdef ENABLE_BLE
5490 #ifdef ENABLE_LE_PERIPHERAL
5491     bool stop_advertismenets;
5492 #endif
5493 #endif
5494 
5495     switch (hci_stack->substate) {
5496         case HCI_HALTING_CLASSIC_STOP:
5497 #ifdef ENABLE_CLASSIC
5498             if (!hci_can_send_command_packet_now()) return;
5499 
5500             if (hci_stack->connectable || hci_stack->discoverable){
5501                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5502                 hci_send_cmd(&hci_write_scan_enable, 0);
5503                 return;
5504             }
5505 #endif
5506             /* fall through */
5507 
5508         case HCI_HALTING_LE_ADV_STOP:
5509             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
5510 
5511 #ifdef ENABLE_BLE
5512 #ifdef ENABLE_LE_PERIPHERAL
5513             if (!hci_can_send_command_packet_now()) return;
5514 
5515             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5516 
5517 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5518             if (hci_le_extended_advertising_supported()){
5519 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5520                 btstack_linked_list_iterator_t it;
5521                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5522                 // stop all periodic advertisements and check if an extended set is active
5523                 while (btstack_linked_list_iterator_has_next(&it)){
5524                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5525                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5526                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5527                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
5528                         return;
5529                     }
5530                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5531                         stop_advertismenets = true;
5532                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5533                     }
5534                 }
5535 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5536                 if (stop_advertismenets){
5537                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5538                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5539                     return;
5540                 }
5541             } else
5542 #else /* ENABLE_LE_PERIPHERAL */
5543             {
5544                 if (stop_advertismenets) {
5545                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5546                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5547                     return;
5548                 }
5549             }
5550 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5551 #endif  /* ENABLE_LE_PERIPHERAL */
5552 #endif  /* ENABLE_BLE */
5553 
5554             /* fall through */
5555 
5556         case HCI_HALTING_LE_SCAN_STOP:
5557             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5558             if (!hci_can_send_command_packet_now()) return;
5559 
5560 #ifdef ENABLE_BLE
5561 #ifdef ENABLE_LE_CENTRAL
5562             if (hci_stack->le_scanning_active){
5563                 hci_le_scan_stop();
5564                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5565                 return;
5566             }
5567 #endif
5568 #endif
5569 
5570             /* fall through */
5571 
5572         case HCI_HALTING_DISCONNECT_ALL:
5573             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5574             if (!hci_can_send_command_packet_now()) return;
5575 
5576             // close all open connections
5577             connection = (hci_connection_t *) hci_stack->connections;
5578             if (connection) {
5579                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5580 
5581                 log_info("HCI_STATE_HALTING, connection %p, handle %u, state %u", connection, con_handle, connection->state);
5582 
5583                 // check state
5584                 switch(connection->state) {
5585                     case SENT_DISCONNECT:
5586                     case RECEIVED_DISCONNECTION_COMPLETE:
5587                         // wait until connection is gone
5588                         return;
5589                     default:
5590                         break;
5591                 }
5592 
5593                 // finally, send the disconnect command
5594                 connection->state = SENT_DISCONNECT;
5595                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5596                 return;
5597             }
5598 
5599 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5600             // stop BIGs and BIG Syncs
5601             if (hci_stack->le_audio_bigs != NULL){
5602                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5603                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5604                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5605                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5606                 return;
5607             }
5608             if (hci_stack->le_audio_big_syncs != NULL){
5609                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5610                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5611                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5612                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5613                 return;
5614             }
5615 #endif
5616 
5617             btstack_run_loop_remove_timer(&hci_stack->timeout);
5618 
5619             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5620             log_info("HCI_STATE_HALTING: wait 50 ms");
5621             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5622             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5623             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5624             btstack_run_loop_add_timer(&hci_stack->timeout);
5625             break;
5626 
5627         case HCI_HALTING_W4_CLOSE_TIMER:
5628             // keep waiting
5629             break;
5630 
5631         case HCI_HALTING_CLOSE:
5632             // close left over connections (that had not been properly closed before)
5633             hci_stack->substate = HCI_HALTING_CLOSE_DISCARDING_CONNECTIONS;
5634             hci_discard_connections();
5635 
5636             log_info("HCI_STATE_HALTING, calling off");
5637 
5638             // switch mode
5639             hci_power_control_off();
5640 
5641             log_info("HCI_STATE_HALTING, emitting state");
5642             hci_emit_state();
5643             log_info("HCI_STATE_HALTING, done");
5644             break;
5645 
5646         default:
5647             break;
5648     }
5649 };
5650 
5651 static void hci_falling_asleep_run(void){
5652     hci_connection_t * connection;
5653     switch(hci_stack->substate) {
5654         case HCI_FALLING_ASLEEP_DISCONNECT:
5655             log_info("HCI_STATE_FALLING_ASLEEP");
5656             // close all open connections
5657             connection =  (hci_connection_t *) hci_stack->connections;
5658             if (connection){
5659 
5660                 // send disconnect
5661                 if (!hci_can_send_command_packet_now()) return;
5662 
5663                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5664                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5665 
5666                 // send disconnected event right away - causes higher layer connections to get closed, too.
5667                 hci_shutdown_connection(connection);
5668                 return;
5669             }
5670 
5671             if (hci_classic_supported()){
5672                 // disable page and inquiry scan
5673                 if (!hci_can_send_command_packet_now()) return;
5674 
5675                 log_info("HCI_STATE_HALTING, disabling inq scans");
5676                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5677 
5678                 // continue in next sub state
5679                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5680                 break;
5681             }
5682 
5683             /* fall through */
5684 
5685             case HCI_FALLING_ASLEEP_COMPLETE:
5686                 log_info("HCI_STATE_HALTING, calling sleep");
5687                 // switch mode
5688                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5689                 hci_emit_state();
5690                 break;
5691 
5692                 default:
5693                     break;
5694     }
5695 }
5696 
5697 #ifdef ENABLE_CLASSIC
5698 
5699 static void hci_update_scan_enable(void){
5700     // 2 = page scan, 1 = inq scan
5701     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5702     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5703     hci_run();
5704 }
5705 
5706 void gap_discoverable_control(uint8_t enable){
5707     if (enable) enable = 1; // normalize argument
5708 
5709     if (hci_stack->discoverable == enable){
5710         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5711         return;
5712     }
5713 
5714     hci_stack->discoverable = enable;
5715     hci_update_scan_enable();
5716 }
5717 
5718 void gap_connectable_control(uint8_t enable){
5719     if (enable) enable = 1; // normalize argument
5720 
5721     // don't emit event
5722     if (hci_stack->connectable == enable) return;
5723 
5724     hci_stack->connectable = enable;
5725     hci_update_scan_enable();
5726 }
5727 #endif
5728 
5729 void gap_local_bd_addr(bd_addr_t address_buffer){
5730     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5731 }
5732 
5733 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5734 static void hci_host_num_completed_packets(void){
5735 
5736     // create packet manually as arrays are not supported and num_commands should not get reduced
5737     hci_reserve_packet_buffer();
5738     uint8_t * packet = hci_get_outgoing_packet_buffer();
5739 
5740     uint16_t size = 0;
5741     uint16_t num_handles = 0;
5742     packet[size++] = 0x35;
5743     packet[size++] = 0x0c;
5744     size++;  // skip param len
5745     size++;  // skip num handles
5746 
5747     // add { handle, packets } entries
5748     btstack_linked_item_t * it;
5749     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5750         hci_connection_t * connection = (hci_connection_t *) it;
5751         if (connection->num_packets_completed){
5752             little_endian_store_16(packet, size, connection->con_handle);
5753             size += 2;
5754             little_endian_store_16(packet, size, connection->num_packets_completed);
5755             size += 2;
5756             //
5757             num_handles++;
5758             connection->num_packets_completed = 0;
5759         }
5760     }
5761 
5762     packet[2] = size - 3;
5763     packet[3] = num_handles;
5764 
5765     hci_stack->host_completed_packets = 0;
5766 
5767     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5768     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5769 
5770     // release packet buffer for synchronous transport implementations
5771     if (hci_transport_synchronous()){
5772         hci_release_packet_buffer();
5773         hci_emit_transport_packet_sent();
5774     }
5775 }
5776 #endif
5777 
5778 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5779     UNUSED(ds);
5780     hci_stack->substate = HCI_HALTING_CLOSE;
5781     hci_halting_run();
5782 }
5783 
5784 static bool hci_run_acl_fragments(void){
5785     if (hci_stack->acl_fragmentation_total_size > 0u) {
5786         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5787         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5788         if (connection) {
5789             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5790                 hci_send_acl_packet_fragments(connection);
5791                 return true;
5792             }
5793         } else {
5794             // connection gone -> discard further fragments
5795             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5796             hci_stack->acl_fragmentation_total_size = 0;
5797             hci_stack->acl_fragmentation_pos = 0;
5798         }
5799     }
5800     return false;
5801 }
5802 
5803 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5804 static bool hci_run_iso_fragments(void){
5805     if (hci_stack->iso_fragmentation_total_size > 0u) {
5806         // TODO: flow control
5807         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5808             hci_send_iso_packet_fragments();
5809             return true;
5810         }
5811     }
5812     return false;
5813 }
5814 #endif
5815 
5816 #ifdef ENABLE_CLASSIC
5817 
5818 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5819 static bool hci_classic_operation_active(void) {
5820     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5821         return true;
5822     }
5823     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5824         return true;
5825     }
5826     btstack_linked_item_t * it;
5827     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5828         hci_connection_t *connection = (hci_connection_t *) it;
5829         switch (connection->state) {
5830             case SENT_CREATE_CONNECTION:
5831             case SENT_CANCEL_CONNECTION:
5832             case SENT_DISCONNECT:
5833                 return true;
5834             default:
5835                 break;
5836         }
5837     }
5838     return false;
5839 }
5840 #endif
5841 
5842 static bool hci_run_general_gap_classic(void){
5843 
5844     // assert stack is working and classic is active
5845     if (hci_classic_supported() == false)      return false;
5846     if (hci_stack->state != HCI_STATE_WORKING) return false;
5847 
5848     // decline incoming connections
5849     if (hci_stack->decline_reason){
5850         uint8_t reason = hci_stack->decline_reason;
5851         hci_stack->decline_reason = 0;
5852         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5853         return true;
5854     }
5855 
5856     if (hci_stack->gap_tasks_classic != 0){
5857         hci_run_gap_tasks_classic();
5858         return true;
5859     }
5860 
5861     // start/stop inquiry
5862     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5863 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5864         if (hci_classic_operation_active() == false)
5865 #endif
5866         {
5867             uint8_t duration = hci_stack->inquiry_state;
5868             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5869             if (hci_stack->inquiry_max_period_length != 0){
5870                 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);
5871             } else {
5872                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5873             }
5874             return true;
5875         }
5876     }
5877     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5878         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5879         hci_send_cmd(&hci_inquiry_cancel);
5880         return true;
5881     }
5882 
5883     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5884         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5885         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5886         return true;
5887     }
5888 
5889     // remote name request
5890     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5891 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5892         if (hci_classic_operation_active() == false)
5893 #endif
5894         {
5895             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5896             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5897                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5898             return true;
5899         }
5900     }
5901 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5902     // Local OOB data
5903     if (hci_stack->classic_read_local_oob_data){
5904         hci_stack->classic_read_local_oob_data = false;
5905         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5906             hci_send_cmd(&hci_read_local_extended_oob_data);
5907         } else {
5908             hci_send_cmd(&hci_read_local_oob_data);
5909         }
5910     }
5911 #endif
5912     // pairing
5913     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5914         uint8_t state = hci_stack->gap_pairing_state;
5915         uint8_t pin_code[PIN_CODE_LEN];
5916         switch (state){
5917             case GAP_PAIRING_STATE_SEND_PIN:
5918                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5919                 memset(pin_code, 0, 16);
5920                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5921                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5922                 break;
5923             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5924                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5925                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5926                 break;
5927             case GAP_PAIRING_STATE_SEND_PASSKEY:
5928                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5929                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5930                 break;
5931             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5932                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5933                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5934                 break;
5935             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5936                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5937                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5938                 break;
5939             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5940                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5941                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5942                 break;
5943             default:
5944                 break;
5945         }
5946         return true;
5947     }
5948     return false;
5949 }
5950 #endif
5951 
5952 #ifdef ENABLE_BLE
5953 
5954 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5955 static uint8_t hci_le_num_phys(uint8_t phys){
5956     const uint8_t num_bits_set[] = { 0, 1, 1, 2, 1, 2, 2, 3 };
5957     btstack_assert(phys);
5958     return num_bits_set[phys];
5959 }
5960 #endif
5961 
5962 #ifdef ENABLE_LE_CENTRAL
5963 static void hci_le_scan_stop(void){
5964 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5965     if (hci_le_extended_advertising_supported()) {
5966             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5967     } else
5968 #endif
5969     {
5970         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5971     }
5972 }
5973 
5974 static void
5975 hci_send_le_create_connection(uint8_t initiator_filter_policy, bd_addr_type_t address_type, uint8_t *address) {
5976 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5977     if (hci_le_extended_advertising_supported()) {
5978         // prepare arrays for all phys (LE Coded, LE 1M, LE 2M PHY)
5979         uint16_t le_connection_scan_interval[3];
5980         uint16_t le_connection_scan_window[3];
5981         uint16_t le_connection_interval_min[3];
5982         uint16_t le_connection_interval_max[3];
5983         uint16_t le_connection_latency[3];
5984         uint16_t le_supervision_timeout[3];
5985         uint16_t le_minimum_ce_length[3];
5986         uint16_t le_maximum_ce_length[3];
5987 
5988         uint8_t i;
5989         uint8_t num_phys = hci_le_num_phys(hci_stack->le_connection_phys);
5990         for (i=0;i<num_phys;i++){
5991             le_connection_scan_interval[i] = hci_stack->le_connection_scan_interval;
5992             le_connection_scan_window[i]   = hci_stack->le_connection_scan_window;
5993             le_connection_interval_min[i]  = hci_stack->le_connection_interval_min;
5994             le_connection_interval_max[i]  = hci_stack->le_connection_interval_max;
5995             le_connection_latency[i]       = hci_stack->le_connection_latency;
5996             le_supervision_timeout[i]      = hci_stack->le_supervision_timeout;
5997             le_minimum_ce_length[i]        = hci_stack->le_minimum_ce_length;
5998             le_maximum_ce_length[i]        = hci_stack->le_maximum_ce_length;
5999         }
6000         hci_send_cmd(&hci_le_extended_create_connection,
6001                      initiator_filter_policy,
6002                      hci_stack->le_connection_own_addr_type,   // our addr type:
6003                      address_type,                  // peer address type
6004                      address,                       // peer bd addr
6005                      hci_stack->le_connection_phys, // initiating PHY
6006                      le_connection_scan_interval,   // conn scan interval
6007                      le_connection_scan_window,     // conn scan windows
6008                      le_connection_interval_min,    // conn interval min
6009                      le_connection_interval_max,    // conn interval max
6010                      le_connection_latency,         // conn latency
6011                      le_supervision_timeout,        // conn latency
6012                      le_minimum_ce_length,          // min ce length
6013                      le_maximum_ce_length           // max ce length
6014         );
6015     } else
6016 #endif
6017     {
6018         hci_send_cmd(&hci_le_create_connection,
6019                      hci_stack->le_connection_scan_interval,  // conn scan interval
6020                      hci_stack->le_connection_scan_window,    // conn scan windows
6021                      initiator_filter_policy,                 // don't use whitelist
6022                      address_type,                            // peer address type
6023                      address,                                 // peer bd addr
6024                      hci_stack->le_connection_own_addr_type,  // our addr type:
6025                      hci_stack->le_connection_interval_min,   // conn interval min
6026                      hci_stack->le_connection_interval_max,   // conn interval max
6027                      hci_stack->le_connection_latency,        // conn latency
6028                      hci_stack->le_supervision_timeout,       // conn latency
6029                      hci_stack->le_minimum_ce_length,         // min ce length
6030                      hci_stack->le_maximum_ce_length          // max ce length
6031         );
6032     }
6033 }
6034 #endif
6035 
6036 #ifdef ENABLE_LE_PERIPHERAL
6037 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6038 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
6039     uint8_t  operation = 0;
6040     if (pos == 0){
6041         // first fragment or complete data
6042         operation |= 1;
6043     }
6044     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
6045         // last fragment or complete data
6046         operation |= 2;
6047     }
6048     return operation;
6049 }
6050 #endif
6051 #endif
6052 
6053 static bool hci_run_general_gap_le(void){
6054 
6055     btstack_linked_list_iterator_t lit;
6056 
6057 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6058     if (hci_stack->le_resolvable_private_address_update_s > 0){
6059         uint16_t update_s = hci_stack->le_resolvable_private_address_update_s;
6060         hci_stack->le_resolvable_private_address_update_s = 0;
6061         hci_send_cmd(&hci_le_set_resolvable_private_address_timeout, update_s);
6062         return true;
6063     }
6064 #endif
6065 
6066     // Phase 1: collect what to stop
6067 
6068 #ifdef ENABLE_LE_CENTRAL
6069     bool scanning_stop = false;
6070     bool connecting_stop = false;
6071 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6072 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6073     bool periodic_sync_stop = false;
6074 #endif
6075 #endif
6076 #endif
6077 
6078 #ifdef ENABLE_LE_PERIPHERAL
6079     bool advertising_stop = false;
6080 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6081     le_advertising_set_t * advertising_stop_set = NULL;
6082 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6083     bool periodic_advertising_stop = false;
6084 #endif
6085 #endif
6086 #endif
6087 
6088     // check if own address changes
6089     uint8_t address_change_mask = LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
6090     bool random_address_change = (hci_stack->le_advertisements_todo & address_change_mask) != 0;
6091 
6092     // check if whitelist needs modification
6093     bool whitelist_modification_pending = false;
6094     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6095     while (btstack_linked_list_iterator_has_next(&lit)){
6096         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6097         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
6098             whitelist_modification_pending = true;
6099             break;
6100         }
6101     }
6102 
6103     // check if resolving list needs modification
6104     bool resolving_list_modification_pending = false;
6105 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6106     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
6107 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
6108         resolving_list_modification_pending = true;
6109     }
6110 #endif
6111 
6112 #ifdef ENABLE_LE_CENTRAL
6113 
6114 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6115     // check if periodic advertiser list needs modification
6116     bool periodic_list_modification_pending = false;
6117     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6118     while (btstack_linked_list_iterator_has_next(&lit)){
6119         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6120         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
6121             periodic_list_modification_pending = true;
6122             break;
6123         }
6124     }
6125 #endif
6126 
6127     // scanning control
6128     if (hci_stack->le_scanning_active) {
6129         // stop if:
6130         // - parameter change required
6131         // - it's disabled
6132         // - whitelist change required but used for scanning
6133         // - resolving list modified
6134         // - own address changes
6135         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
6136         if ((hci_stack->le_scanning_param_update) ||
6137             !hci_stack->le_scanning_enabled ||
6138             (scanning_uses_whitelist && whitelist_modification_pending) ||
6139             resolving_list_modification_pending ||
6140             random_address_change){
6141 
6142             scanning_stop = true;
6143         }
6144     }
6145 
6146     // connecting control
6147     bool connecting_with_whitelist;
6148     switch (hci_stack->le_connecting_state){
6149         case LE_CONNECTING_DIRECT:
6150         case LE_CONNECTING_WHITELIST:
6151             // stop connecting if:
6152             // - connecting uses white and whitelist modification pending
6153             // - if it got disabled
6154             // - resolving list modified
6155             // - own address changes
6156             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
6157             if ((connecting_with_whitelist && whitelist_modification_pending) ||
6158                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
6159                 resolving_list_modification_pending ||
6160                 random_address_change) {
6161 
6162                 connecting_stop = true;
6163             }
6164             break;
6165         default:
6166             break;
6167     }
6168 
6169 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6170 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6171     // periodic sync control
6172     bool sync_with_advertiser_list;
6173     switch(hci_stack->le_periodic_sync_state){
6174         case LE_CONNECTING_DIRECT:
6175         case LE_CONNECTING_WHITELIST:
6176             // stop sync if:
6177             // - sync with advertiser list and advertiser list modification pending
6178             // - if it got disabled
6179             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
6180             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
6181                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
6182                 periodic_sync_stop = true;
6183             }
6184             break;
6185         default:
6186             break;
6187     }
6188 #endif
6189 #endif
6190 
6191 #endif /* ENABLE_LE_CENTRAL */
6192 
6193 #ifdef ENABLE_LE_PERIPHERAL
6194     // le advertisement control
6195     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
6196         // stop if:
6197         // - parameter change required
6198         // - random address used in advertising and changes
6199         // - it's disabled
6200         // - whitelist change required but used for advertisement filter policy
6201         // - resolving list modified
6202         // - own address changes
6203         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
6204         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
6205         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
6206         if (advertising_change ||
6207             (advertising_uses_random_address && random_address_change) ||
6208             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
6209             (advertising_uses_whitelist && whitelist_modification_pending) ||
6210             resolving_list_modification_pending ||
6211             random_address_change) {
6212 
6213             advertising_stop = true;
6214         }
6215     }
6216 
6217 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6218     if (hci_le_extended_advertising_supported() && (advertising_stop == false)){
6219         btstack_linked_list_iterator_t it;
6220         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6221         while (btstack_linked_list_iterator_has_next(&it)){
6222             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6223             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
6224                 // stop if:
6225                 // - parameter change required
6226                 // - random address used in connectable advertising and changes
6227                 // - it's disabled
6228                 // - whitelist change required but used for advertisement filter policy
6229                 // - resolving list modified
6230                 // - own address changes
6231                 // - advertisement set will be removed
6232                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
6233                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
6234                 bool advertising_uses_random_address =
6235                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
6236                         advertising_connectable;
6237                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
6238                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
6239                 bool advertising_set_random_address_change =
6240                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
6241                 bool advertising_set_will_be_removed =
6242                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
6243                 if (advertising_parameter_change ||
6244                     (advertising_uses_random_address && advertising_set_random_address_change) ||
6245                     (advertising_enabled == false) ||
6246                     (advertising_uses_whitelist && whitelist_modification_pending) ||
6247                     resolving_list_modification_pending ||
6248                     advertising_set_will_be_removed) {
6249 
6250                     advertising_stop = true;
6251                     advertising_stop_set = advertising_set;
6252                     break;
6253                 }
6254             }
6255 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6256             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
6257                 // stop if:
6258                 // - it's disabled
6259                 // - parameter change required
6260                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
6261                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
6262                 if ((periodic_enabled == false) || periodic_parameter_change){
6263                     periodic_advertising_stop = true;
6264                     advertising_stop_set = advertising_set;
6265                 }
6266             }
6267 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6268         }
6269     }
6270 #endif
6271 
6272 #endif
6273 
6274 
6275     // Phase 2: stop everything that should be off during modifications
6276 
6277 
6278     // 2.1 Outgoing connection
6279 #ifdef ENABLE_LE_CENTRAL
6280     if (connecting_stop){
6281         hci_send_cmd(&hci_le_create_connection_cancel);
6282         return true;
6283     }
6284 #endif
6285 
6286     // 2.2 Scanning
6287 #ifdef ENABLE_LE_CENTRAL
6288     if (scanning_stop){
6289         hci_stack->le_scanning_active = false;
6290         hci_le_scan_stop();
6291         return true;
6292     }
6293 
6294     // 2.3 Periodic Sync
6295 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6296     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
6297         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
6298         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
6299         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
6300         return true;
6301     }
6302 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6303     if (periodic_sync_stop){
6304         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
6305         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
6306         return true;
6307     }
6308 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6309 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6310 #endif /* ENABLE_LE_CENTRAL */
6311 
6312     // 2.4 Advertising: legacy, extended, periodic
6313 #ifdef ENABLE_LE_PERIPHERAL
6314     if (advertising_stop){
6315 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6316         if (hci_le_extended_advertising_supported()) {
6317             uint8_t advertising_stop_handle;
6318             if (advertising_stop_set != NULL){
6319                 advertising_stop_handle = advertising_stop_set->advertising_handle;
6320                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6321             } else {
6322                 advertising_stop_handle = 0;
6323                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6324             }
6325             const uint8_t advertising_handles[] = { advertising_stop_handle };
6326             const uint16_t durations[] = { 0 };
6327             const uint16_t max_events[] = { 0 };
6328             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
6329         } else
6330 #endif
6331         {
6332             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6333             hci_send_cmd(&hci_le_set_advertise_enable, 0);
6334         }
6335         return true;
6336     }
6337 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6338 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6339     if (periodic_advertising_stop){
6340         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6341         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
6342         return true;
6343     }
6344 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6345 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6346 #endif /* ENABLE_LE_PERIPHERAL */
6347 
6348 
6349     // Phase 3: modify
6350 
6351     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY) {
6352         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
6353         // GAP Privacy, notify clients upon upcoming random address change
6354         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
6355         gap_privacy_clients_notify(hci_stack->le_random_address);
6356     }
6357 
6358     // - wait until privacy update completed
6359     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PRIVACY_PENDING) != 0){
6360         return false;
6361     }
6362 
6363     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS){
6364         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6365         hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
6366 #ifdef ENABLE_LE_SET_ADV_PARAMS_ON_RANDOM_ADDRESS_CHANGE
6367         // workaround: on some Controllers, address in advertisements is updated only after next dv params set
6368         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6369 #endif
6370         return true;
6371     }
6372 
6373 #ifdef ENABLE_LE_CENTRAL
6374     if (hci_stack->le_scanning_param_update){
6375         hci_stack->le_scanning_param_update = false;
6376 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6377         if (hci_le_extended_advertising_supported()){
6378             // prepare arrays for all phys (LE Coded and LE 1M PHY)
6379             uint8_t  scan_types[2];
6380             uint16_t scan_intervals[2];
6381             uint16_t scan_windows[2];
6382 
6383             uint8_t i;
6384             uint8_t num_phys = hci_le_num_phys(hci_stack->le_scan_phys);
6385             for (i=0;i<num_phys;i++){
6386                 scan_types[i]     = hci_stack->le_scan_type;
6387                 scan_intervals[i] = hci_stack->le_scan_interval;
6388                 scan_windows[i]   = hci_stack->le_scan_window;
6389             }
6390             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
6391                          hci_stack->le_scan_filter_policy, hci_stack->le_scan_phys, scan_types, scan_intervals, scan_windows);
6392         } else
6393 #endif
6394         {
6395             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
6396                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
6397         }
6398         return true;
6399     }
6400 #endif
6401 
6402 #ifdef ENABLE_LE_PERIPHERAL
6403     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
6404         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6405         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
6406 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6407         if (hci_le_extended_advertising_supported()){
6408             // map advertisment type to advertising event properties
6409             uint16_t adv_event_properties = 0;
6410             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
6411             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
6412                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
6413             }
6414             hci_stack->le_advertising_set_in_current_command = 0;
6415             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6416                          0,
6417                          adv_event_properties,
6418                          hci_stack->le_advertisements_interval_min,
6419                          hci_stack->le_advertisements_interval_max,
6420                          hci_stack->le_advertisements_channel_map,
6421                          hci_stack->le_advertisements_own_addr_type,
6422                          hci_stack->le_advertisements_direct_address_type,
6423                          hci_stack->le_advertisements_direct_address,
6424                          hci_stack->le_advertisements_filter_policy,
6425                          0x7f,  // tx power: no preference
6426                          0x01,  // primary adv phy: LE 1M
6427                          0,     // secondary adv max skip
6428                          0x01,  // secondary adv phy
6429                          0,     // adv sid
6430                          0      // scan request notification
6431                          );
6432         } else
6433 #endif
6434         {
6435             hci_send_cmd(&hci_le_set_advertising_parameters,
6436                          hci_stack->le_advertisements_interval_min,
6437                          hci_stack->le_advertisements_interval_max,
6438                          hci_stack->le_advertisements_type,
6439                          hci_stack->le_advertisements_own_addr_type,
6440                          hci_stack->le_advertisements_direct_address_type,
6441                          hci_stack->le_advertisements_direct_address,
6442                          hci_stack->le_advertisements_channel_map,
6443                          hci_stack->le_advertisements_filter_policy);
6444         }
6445         return true;
6446     }
6447 
6448 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6449     // assumption: only set if extended advertising is supported
6450     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0) != 0){
6451         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
6452         hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
6453         return true;
6454     }
6455 #endif
6456 
6457     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
6458         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6459         uint8_t adv_data_clean[31];
6460         memset(adv_data_clean, 0, sizeof(adv_data_clean));
6461         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
6462                      hci_stack->le_advertisements_data_len);
6463         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
6464 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6465         if (hci_le_extended_advertising_supported()){
6466             hci_stack->le_advertising_set_in_current_command = 0;
6467             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
6468         } else
6469 #endif
6470         {
6471             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
6472         }
6473         return true;
6474     }
6475 
6476     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
6477         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6478         uint8_t scan_data_clean[31];
6479         memset(scan_data_clean, 0, sizeof(scan_data_clean));
6480         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
6481                      hci_stack->le_scan_response_data_len);
6482         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6483 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6484         if (hci_le_extended_advertising_supported()){
6485             hci_stack->le_advertising_set_in_current_command = 0;
6486             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6487         } else
6488 #endif
6489         {
6490             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6491         }
6492         return true;
6493     }
6494 
6495 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6496     if (hci_le_extended_advertising_supported()) {
6497         btstack_linked_list_iterator_t it;
6498         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6499         while (btstack_linked_list_iterator_has_next(&it)){
6500             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6501             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6502                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6503                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6504                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6505                 return true;
6506             }
6507             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6508                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6509                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6510                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6511                              advertising_set->advertising_handle,
6512                              advertising_set->extended_params.advertising_event_properties,
6513                              advertising_set->extended_params.primary_advertising_interval_min,
6514                              advertising_set->extended_params.primary_advertising_interval_max,
6515                              advertising_set->extended_params.primary_advertising_channel_map,
6516                              advertising_set->extended_params.own_address_type,
6517                              advertising_set->extended_params.peer_address_type,
6518                              advertising_set->extended_params.peer_address,
6519                              advertising_set->extended_params.advertising_filter_policy,
6520                              advertising_set->extended_params.advertising_tx_power,
6521                              advertising_set->extended_params.primary_advertising_phy,
6522                              advertising_set->extended_params.secondary_advertising_max_skip,
6523                              advertising_set->extended_params.secondary_advertising_phy,
6524                              advertising_set->extended_params.advertising_sid,
6525                              advertising_set->extended_params.scan_request_notification_enable
6526                 );
6527                 return true;
6528             }
6529             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
6530                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
6531                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
6532                 return true;
6533             }
6534             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6535                 uint16_t pos = advertising_set->adv_data_pos;
6536                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6537                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6538                 if ((operation & 0x02) != 0){
6539                     // last fragment or complete data
6540                     operation |= 2;
6541                     advertising_set->adv_data_pos = 0;
6542                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6543                 } else {
6544                     advertising_set->adv_data_pos += data_to_upload;
6545                 }
6546                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6547                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6548                 return true;
6549             }
6550             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6551                 uint16_t pos = advertising_set->scan_data_pos;
6552                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6553                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6554                 if ((operation & 0x02) != 0){
6555                     advertising_set->scan_data_pos = 0;
6556                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6557                 } else {
6558                     advertising_set->scan_data_pos += data_to_upload;
6559                 }
6560                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6561                 hci_send_cmd(&hci_le_set_extended_scan_response_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
6562                 return true;
6563             }
6564 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6565             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
6566                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
6567                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6568                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
6569                              advertising_set->advertising_handle,
6570                              advertising_set->periodic_params.periodic_advertising_interval_min,
6571                              advertising_set->periodic_params.periodic_advertising_interval_max,
6572                              advertising_set->periodic_params.periodic_advertising_properties);
6573                 return true;
6574             }
6575             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
6576                 uint16_t pos = advertising_set->periodic_data_pos;
6577                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
6578                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6579                 if ((operation & 0x02) != 0){
6580                     // last fragment or complete data
6581                     operation |= 2;
6582                     advertising_set->periodic_data_pos = 0;
6583                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
6584                 } else {
6585                     advertising_set->periodic_data_pos += data_to_upload;
6586                 }
6587                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6588                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
6589                 return true;
6590             }
6591 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6592         }
6593     }
6594 #endif
6595 
6596 #endif
6597 
6598 #ifdef ENABLE_LE_CENTRAL
6599     // if connect with whitelist was active and is not cancelled yet, wait until next time
6600     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
6601 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6602     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
6603     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
6604 #endif
6605 #endif
6606 
6607     // LE Whitelist Management
6608     if (whitelist_modification_pending){
6609         // add/remove entries
6610         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6611         while (btstack_linked_list_iterator_has_next(&lit)){
6612             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6613 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
6614 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6615                 entry->state &= ~LE_WHITELIST_ON_CONTROLLER;
6616                 bd_addr_type_t address_type = entry->address_type;
6617                 bd_addr_t address;
6618                 memcpy(address, entry->address, 6);
6619                 if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) == 0){
6620                     // remove from whitelist if not scheduled for re-addition
6621                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6622                     btstack_memory_whitelist_entry_free(entry);
6623                 }
6624 				hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
6625 				return true;
6626 			}
6627             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
6628 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
6629                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
6630                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
6631                 return true;
6632             }
6633         }
6634     }
6635 
6636 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6637     // LE Resolving List Management
6638     if (resolving_list_modification_pending) {
6639 		uint16_t i;
6640         uint8_t null_16[16];
6641         uint8_t local_irk_flipped[16];
6642         const uint8_t *local_irk;
6643 		switch (hci_stack->le_resolving_list_state) {
6644 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
6645 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6646 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
6647 				return true;
6648 			case LE_RESOLVING_LIST_READ_SIZE:
6649 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
6650 				hci_send_cmd(&hci_le_read_resolving_list_size);
6651 				return true;
6652 			case LE_RESOLVING_LIST_SEND_CLEAR:
6653 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SET_IRK;
6654 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6655 							  sizeof(hci_stack->le_resolving_list_add_entries));
6656                 (void) memset(hci_stack->le_resolving_list_set_privacy_mode, 0xff,
6657                               sizeof(hci_stack->le_resolving_list_set_privacy_mode));
6658 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6659 							  sizeof(hci_stack->le_resolving_list_remove_entries));
6660 				hci_send_cmd(&hci_le_clear_resolving_list);
6661 				return true;
6662             case LE_RESOLVING_LIST_SET_IRK:
6663                 // set IRK used by RPA for undirected advertising
6664                 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
6665                 local_irk = gap_get_persistent_irk();
6666                 reverse_128(local_irk, local_irk_flipped);
6667                 memset(null_16, 0, sizeof(null_16));
6668                 hci_send_cmd(&hci_le_add_device_to_resolving_list, BD_ADDR_TYPE_LE_PUBLIC, null_16,
6669                              null_16, local_irk_flipped);
6670                 return true;
6671 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
6672                 // first remove old entries
6673 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6674 					uint8_t offset = i >> 3;
6675 					uint8_t mask = 1 << (i & 7);
6676 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
6677 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
6678 					bd_addr_t peer_identity_addreses;
6679 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6680 					sm_key_t peer_irk;
6681 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6682 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6683 
6684 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6685 					// trigger whitelist entry 'update' (work around for controller bug)
6686 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6687 					while (btstack_linked_list_iterator_has_next(&lit)) {
6688 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6689 						if (entry->address_type != peer_identity_addr_type) continue;
6690 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6691 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6692 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6693 					}
6694 #endif
6695 
6696 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6697 								 peer_identity_addreses);
6698 					return true;
6699 				}
6700 
6701                 // then add new entries
6702 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6703 					uint8_t offset = i >> 3;
6704 					uint8_t mask = 1 << (i & 7);
6705 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
6706 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
6707 					bd_addr_t peer_identity_addreses;
6708 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6709 					sm_key_t peer_irk;
6710 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
6711 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6712                     if (btstack_is_null(peer_irk, 16)) continue;
6713 					local_irk = gap_get_persistent_irk();
6714 					// command uses format specifier 'P' that stores 16-byte value without flip
6715 					uint8_t peer_irk_flipped[16];
6716 					reverse_128(local_irk, local_irk_flipped);
6717 					reverse_128(peer_irk, peer_irk_flipped);
6718 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6719 								 peer_irk_flipped, local_irk_flipped);
6720 					return true;
6721 				}
6722 
6723                 // finally, set privacy mode
6724                 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6725                     uint8_t offset = i >> 3;
6726                     uint8_t mask = 1 << (i & 7);
6727                     if ((hci_stack->le_resolving_list_set_privacy_mode[offset] & mask) == 0) continue;
6728                     hci_stack->le_resolving_list_set_privacy_mode[offset] &= ~mask;
6729                     if (hci_stack->le_privacy_mode == LE_PRIVACY_MODE_NETWORK) {
6730                         // Network Privacy Mode is default
6731                         continue;
6732                     }
6733                     bd_addr_t peer_identity_address;
6734                     int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6735                     sm_key_t peer_irk;
6736                     le_device_db_info(i, &peer_identity_addr_type, peer_identity_address, peer_irk);
6737                     if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6738                     if (btstack_is_null(peer_irk, 16)) continue;
6739                     // command uses format specifier 'P' that stores 16-byte value without flip
6740                     uint8_t peer_irk_flipped[16];
6741                     reverse_128(peer_irk, peer_irk_flipped);
6742                     hci_send_cmd(&hci_le_set_privacy_mode, peer_identity_addr_type, peer_identity_address, hci_stack->le_privacy_mode);
6743                     return true;
6744                 }
6745 				break;
6746 
6747 			default:
6748 				break;
6749 		}
6750         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6751 	}
6752 #endif
6753 
6754 #ifdef ENABLE_LE_CENTRAL
6755 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6756     // LE Whitelist Management
6757     if (periodic_list_modification_pending){
6758         // add/remove entries
6759         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6760         while (btstack_linked_list_iterator_has_next(&lit)){
6761             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6762             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6763                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6764                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6765                 return true;
6766             }
6767             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6768                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6769                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
6770                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6771                 return true;
6772             }
6773             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6774                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6775                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6776             }
6777         }
6778     }
6779 #endif
6780 #endif
6781 
6782 #ifdef ENABLE_LE_CENTRAL
6783 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6784 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6785     if (hci_stack->le_past_set_default_params){
6786         hci_stack->le_past_set_default_params = false;
6787         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
6788                      hci_stack->le_past_mode,
6789                      hci_stack->le_past_skip,
6790                      hci_stack->le_past_sync_timeout,
6791                      hci_stack->le_past_cte_type);
6792         return true;
6793     }
6794 #endif
6795 #endif
6796 #endif
6797 
6798     // post-pone all actions until stack is fully working
6799     if (hci_stack->state != HCI_STATE_WORKING) return false;
6800 
6801     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6802     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6803 
6804     // Phase 4: restore state
6805 
6806 #ifdef ENABLE_LE_CENTRAL
6807     // re-start scanning
6808     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6809         hci_stack->le_scanning_active = true;
6810 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6811         if (hci_le_extended_advertising_supported()){
6812             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
6813         } else
6814 #endif
6815         {
6816             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
6817         }
6818         return true;
6819     }
6820 #endif
6821 
6822 #ifdef ENABLE_LE_CENTRAL
6823     // re-start connecting
6824     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6825         bd_addr_t null_addr;
6826         memset(null_addr, 0, 6);
6827         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6828         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6829         hci_send_le_create_connection(1, 0, null_addr);
6830         return true;
6831     }
6832 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6833     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6834         switch(hci_stack->le_periodic_sync_request){
6835             case LE_CONNECTING_DIRECT:
6836             case LE_CONNECTING_WHITELIST:
6837                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6838                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6839                              hci_stack->le_periodic_sync_options,
6840                              hci_stack->le_periodic_sync_advertising_sid,
6841                              hci_stack->le_periodic_sync_advertiser_address_type,
6842                              hci_stack->le_periodic_sync_advertiser_address,
6843                              hci_stack->le_periodic_sync_skip,
6844                              hci_stack->le_periodic_sync_timeout,
6845                              hci_stack->le_periodic_sync_cte_type);
6846                 return true;
6847             default:
6848                 break;
6849         }
6850     }
6851 #endif
6852 #endif
6853 
6854 #ifdef ENABLE_LE_PERIPHERAL
6855     // re-start advertising
6856     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6857         // check if advertisements should be enabled given
6858         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6859         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6860 
6861 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6862         if (hci_le_extended_advertising_supported()){
6863             const uint8_t advertising_handles[] = { 0 };
6864             const uint16_t durations[] = { 0 };
6865             const uint16_t max_events[] = { 0 };
6866             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6867         } else
6868 #endif
6869         {
6870             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6871         }
6872         return true;
6873     }
6874 
6875 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6876     if (hci_le_extended_advertising_supported()) {
6877         btstack_linked_list_iterator_t it;
6878         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6879         while (btstack_linked_list_iterator_has_next(&it)) {
6880             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6881             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6882                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6883                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6884                 const uint16_t durations[] = { advertising_set->enable_timeout };
6885                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6886                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6887                 return true;
6888             }
6889 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6890             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6891                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6892                 uint8_t enable = 1;
6893                 if (advertising_set->periodic_include_adi){
6894                     enable |= 2;
6895                 }
6896                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6897                 return true;
6898             }
6899 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6900         }
6901     }
6902 #endif
6903 #endif
6904 
6905     return false;
6906 }
6907 
6908 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6909 static bool hci_run_iso_tasks(void){
6910     btstack_linked_list_iterator_t it;
6911 
6912     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
6913         return false;
6914     }
6915 
6916     // BIG
6917     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6918     while (btstack_linked_list_iterator_has_next(&it)){
6919         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6920         switch (big->state){
6921             case LE_AUDIO_BIG_STATE_CREATE:
6922                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
6923                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6924                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6925                 hci_send_cmd(&hci_le_create_big,
6926                              big->params->big_handle,
6927                              big->params->advertising_handle,
6928                              big->params->num_bis,
6929                              big->params->sdu_interval_us,
6930                              big->params->max_sdu,
6931                              big->params->max_transport_latency_ms,
6932                              big->params->rtn,
6933                              big->params->phy,
6934                              big->params->packing,
6935                              big->params->framing,
6936                              big->params->encryption,
6937                              big->params->broadcast_code);
6938                 return true;
6939             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6940                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6941                 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);
6942                 return true;
6943             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6944                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6945                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6946                 return true;
6947             case LE_AUDIO_BIG_STATE_TERMINATE:
6948                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6949                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6950                 return true;
6951             default:
6952                 break;
6953         }
6954     }
6955 
6956     // BIG Sync
6957     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6958     while (btstack_linked_list_iterator_has_next(&it)){
6959         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6960         switch (big_sync->state){
6961             case LE_AUDIO_BIG_STATE_CREATE:
6962                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
6963                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
6964                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6965                 hci_send_cmd(&hci_le_big_create_sync,
6966                              big_sync->params->big_handle,
6967                              big_sync->params->sync_handle,
6968                              big_sync->params->encryption,
6969                              big_sync->params->broadcast_code,
6970                              big_sync->params->mse,
6971                              big_sync->params->big_sync_timeout_10ms,
6972                              big_sync->params->num_bis,
6973                              big_sync->params->bis_indices);
6974                 return true;
6975             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6976                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6977                 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);
6978                 return true;
6979             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6980                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6981                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6982                 return true;
6983             case LE_AUDIO_BIG_STATE_TERMINATE:
6984                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6985                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6986                 return true;
6987             default:
6988                 break;
6989         }
6990     }
6991 
6992     // CIG
6993     bool cig_active;
6994     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
6995     while (btstack_linked_list_iterator_has_next(&it)) {
6996         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
6997         uint8_t i;
6998         // Set CIG Parameters
6999         uint8_t cis_id[MAX_NR_CIS];
7000         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
7001         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
7002         uint8_t phy_c_to_p[MAX_NR_CIS];
7003         uint8_t phy_p_to_c[MAX_NR_CIS];
7004         uint8_t rtn_c_to_p[MAX_NR_CIS];
7005         uint8_t rtn_p_to_c[MAX_NR_CIS];
7006         switch (cig->state) {
7007             case LE_AUDIO_CIG_STATE_CREATE:
7008                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7009                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7010                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
7011                 le_audio_cig_params_t * params = cig->params;
7012                 for (i = 0; i < params->num_cis; i++) {
7013                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
7014                     cis_id[i]         = cis_params->cis_id;
7015                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
7016                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
7017                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
7018                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
7019                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
7020                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
7021                 }
7022                 hci_send_cmd(&hci_le_set_cig_parameters,
7023                              cig->cig_id,
7024                              params->sdu_interval_c_to_p,
7025                              params->sdu_interval_p_to_c,
7026                              params->worst_case_sca,
7027                              params->packing,
7028                              params->framing,
7029                              params->max_transport_latency_c_to_p,
7030                              params->max_transport_latency_p_to_c,
7031                              params->num_cis,
7032                              cis_id,
7033                              max_sdu_c_to_p,
7034                              max_sdu_p_to_c,
7035                              phy_c_to_p,
7036                              phy_p_to_c,
7037                              rtn_c_to_p,
7038                              rtn_p_to_c
7039                 );
7040                 return true;
7041             case LE_AUDIO_CIG_STATE_CREATE_CIS:
7042                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7043                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7044                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
7045                 for (i=0;i<cig->num_cis;i++){
7046                     cig->cis_setup_active[i] = true;
7047                 }
7048                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
7049                 return true;
7050             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
7051                 while (cig->state_vars.next_cis < (cig->num_cis * 2)){
7052                     // find next path to setup
7053                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
7054                     if (cig->cis_established[cis_index] == false) {
7055                         continue;
7056                     }
7057                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
7058                     bool setup = true;
7059                     if (cis_direction == 0){
7060                         // 0 - input - host to controller
7061                         // we are central => central to peripheral
7062                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
7063                     } else {
7064                         // 1 - output - controller to host
7065                         // we are central => peripheral to central
7066                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
7067                     }
7068                     if (setup){
7069                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7070                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7071                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
7072                         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);
7073                         return true;
7074                     }
7075                     cig->state_vars.next_cis++;
7076                 }
7077                 // emit done
7078                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
7079                 break;
7080             case LE_AUDIO_CIG_STATE_REMOVE:
7081                 // check if CIG Active
7082                 cig_active = false;
7083                 for (i = 0; i < cig->num_cis; i++) {
7084                     if (cig->cis_con_handles[i] != HCI_CON_HANDLE_INVALID){
7085                         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
7086                         if (stream != NULL){
7087                             cig_active = true;
7088                             break;
7089                         }
7090                     }
7091                 }
7092                 if (cig_active == false){
7093                     btstack_linked_list_iterator_remove(&it);
7094                     hci_send_cmd(&hci_le_remove_cig, cig->cig_id);
7095                     return true;
7096                 }
7097             default:
7098                 break;
7099         }
7100     }
7101 
7102     // CIS Accept/Reject/Setup ISO Path/Close
7103     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
7104     while (btstack_linked_list_iterator_has_next(&it)) {
7105         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
7106         hci_con_handle_t con_handle;
7107         switch (iso_stream->state){
7108             case HCI_ISO_STREAM_W2_ACCEPT:
7109                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
7110                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7111                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7112                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->cis_handle);
7113                 return true;
7114             case HCI_ISO_STREAM_W2_REJECT:
7115                 con_handle = iso_stream->cis_handle;
7116                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7117                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7118                 hci_iso_stream_finalize(iso_stream);
7119                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
7120                 return true;
7121             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
7122                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7123                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7124                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
7125                 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);
7126                 break;
7127             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
7128                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7129                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7130                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT;
7131                 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);
7132                 break;
7133             case HCI_ISO_STREAM_STATE_W2_CLOSE:
7134                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_DISCONNECTED;
7135                 hci_send_cmd(&hci_disconnect, iso_stream->cis_handle);
7136                 break;
7137             default:
7138                 break;
7139         }
7140     }
7141 
7142     return false;
7143 }
7144 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
7145 #endif
7146 
7147 static bool hci_run_general_pending_commands(void){
7148     btstack_linked_item_t * it;
7149     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7150         hci_connection_t * connection = (hci_connection_t *) it;
7151 
7152         switch(connection->state){
7153             case SEND_CREATE_CONNECTION:
7154                 switch(connection->address_type){
7155 #ifdef ENABLE_CLASSIC
7156                     case BD_ADDR_TYPE_ACL:
7157                         log_info("sending hci_create_connection");
7158                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
7159                         break;
7160 #endif
7161                     default:
7162 #ifdef ENABLE_BLE
7163 #ifdef ENABLE_LE_CENTRAL
7164                         log_info("sending hci_le_create_connection");
7165                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
7166                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
7167                         hci_send_le_create_connection(0, connection->address_type, connection->address);
7168                         connection->state = SENT_CREATE_CONNECTION;
7169 #endif
7170 #endif
7171                         break;
7172                 }
7173                 return true;
7174 
7175 #ifdef ENABLE_CLASSIC
7176             case RECEIVED_CONNECTION_REQUEST:
7177                 if (connection->address_type == BD_ADDR_TYPE_ACL){
7178                     log_info("sending hci_accept_connection_request");
7179                     connection->state = ACCEPTED_CONNECTION_REQUEST;
7180                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
7181                     return true;
7182                 }
7183                 break;
7184 #endif
7185             case SEND_DISCONNECT:
7186                 connection->state = SENT_DISCONNECT;
7187                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7188                 return true;
7189 
7190             default:
7191                 break;
7192         }
7193 
7194         // no further commands if connection is about to get shut down
7195         if (connection->state == SENT_DISCONNECT) continue;
7196 
7197 #ifdef ENABLE_CLASSIC
7198 
7199         // Handling link key request requires remote supported features
7200         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
7201             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
7202             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
7203 
7204             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
7205             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
7206             if (have_link_key && security_level_sufficient){
7207                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
7208             } else {
7209                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
7210             }
7211             return true;
7212         }
7213 
7214         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
7215             log_info("denying to pin request");
7216             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
7217             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
7218             return true;
7219         }
7220 
7221         // security assessment requires remote features
7222         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
7223             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
7224             hci_ssp_assess_security_on_io_cap_request(connection);
7225             // 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
7226         }
7227 
7228         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
7229             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7230             // set authentication requirements:
7231             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
7232             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
7233             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
7234             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
7235                 authreq |= 1;
7236             }
7237             bool bonding = hci_stack->bondable;
7238             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
7239                 // if we have received IO Cap Response, we're in responder role
7240                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7241                 if (bonding && !remote_bonding){
7242                     log_info("Remote not bonding, dropping local flag");
7243                     bonding = false;
7244                 }
7245             }
7246             if (bonding){
7247                 if (connection->bonding_flags & BONDING_DEDICATED){
7248                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7249                 } else {
7250                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
7251                 }
7252             }
7253             uint8_t have_oob_data = 0;
7254 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7255             if (connection->classic_oob_c_192 != NULL){
7256                     have_oob_data |= 1;
7257             }
7258             if (connection->classic_oob_c_256 != NULL){
7259                 have_oob_data |= 2;
7260             }
7261 #endif
7262             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
7263             return true;
7264         }
7265 
7266         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
7267             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
7268             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
7269             return true;
7270         }
7271 
7272 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7273         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
7274             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
7275             const uint8_t zero[16] = { 0 };
7276             const uint8_t * r_192 = zero;
7277             const uint8_t * c_192 = zero;
7278             const uint8_t * r_256 = zero;
7279             const uint8_t * c_256 = zero;
7280             // verify P-256 OOB
7281             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
7282                 c_256 = connection->classic_oob_c_256;
7283                 if (connection->classic_oob_r_256 != NULL) {
7284                     r_256 = connection->classic_oob_r_256;
7285                 }
7286             }
7287             // verify P-192 OOB
7288             if ((connection->classic_oob_c_192 != NULL)) {
7289                 c_192 = connection->classic_oob_c_192;
7290                 if (connection->classic_oob_r_192 != NULL) {
7291                     r_192 = connection->classic_oob_r_192;
7292                 }
7293             }
7294 
7295             // assess security
7296             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
7297             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
7298             if (need_level_4 && !can_reach_level_4){
7299                 log_info("Level 4 required, but not possible -> abort");
7300                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
7301                 // send oob negative reply
7302                 c_256 = NULL;
7303                 c_192 = NULL;
7304             }
7305 
7306             // Reply
7307             if (c_256 != zero) {
7308                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
7309             } else if (c_192 != zero){
7310                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
7311             } else {
7312                 hci_stack->classic_oob_con_handle = connection->con_handle;
7313                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
7314             }
7315             return true;
7316         }
7317 #endif
7318 
7319         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
7320             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
7321             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
7322             return true;
7323         }
7324 
7325         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
7326             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
7327             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
7328             return true;
7329         }
7330 
7331         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
7332             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
7333             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
7334             return true;
7335         }
7336 
7337         if ((connection->bonding_flags & (BONDING_DISCONNECT_DEDICATED_DONE | BONDING_DEDICATED_DEFER_DISCONNECT)) == BONDING_DISCONNECT_DEDICATED_DONE){
7338             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
7339             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
7340             connection->state = SENT_DISCONNECT;
7341             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7342             return true;
7343         }
7344 
7345         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
7346             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
7347             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
7348             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
7349             return true;
7350         }
7351 
7352         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
7353             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
7354             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
7355             return true;
7356         }
7357 
7358         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
7359             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
7360             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
7361             return true;
7362         }
7363 
7364         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
7365             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7366             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
7367             return true;
7368         }
7369 
7370         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
7371             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
7372             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
7373             return true;
7374         }
7375 
7376         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
7377             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
7378             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
7379             return true;
7380         }
7381 #endif
7382 
7383         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
7384             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
7385 #ifdef ENABLE_CLASSIC
7386             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
7387 #endif
7388             if (connection->state != SENT_DISCONNECT){
7389                 connection->state = SENT_DISCONNECT;
7390                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
7391                 return true;
7392             }
7393         }
7394 
7395 #ifdef ENABLE_CLASSIC
7396         uint16_t sniff_min_interval;
7397         switch (connection->sniff_min_interval){
7398             case 0:
7399                 break;
7400             case 0xffff:
7401                 connection->sniff_min_interval = 0;
7402                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
7403                 return true;
7404             default:
7405                 sniff_min_interval = connection->sniff_min_interval;
7406                 connection->sniff_min_interval = 0;
7407                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
7408                 return true;
7409         }
7410 
7411         if (connection->sniff_subrating_max_latency != 0xffff){
7412             uint16_t max_latency = connection->sniff_subrating_max_latency;
7413             connection->sniff_subrating_max_latency = 0;
7414             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
7415             return true;
7416         }
7417 
7418         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
7419             uint8_t service_type = (uint8_t) connection->qos_service_type;
7420             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
7421             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);
7422             return true;
7423         }
7424 
7425         if (connection->request_role != HCI_ROLE_INVALID){
7426             hci_role_t role = connection->request_role;
7427             connection->request_role = HCI_ROLE_INVALID;
7428             hci_send_cmd(&hci_switch_role_command, connection->address, role);
7429             return true;
7430         }
7431 #endif
7432 
7433         if (connection->gap_connection_tasks != 0){
7434 #ifdef ENABLE_CLASSIC
7435             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
7436                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
7437                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
7438                 return true;
7439             }
7440             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
7441                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
7442                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
7443                 return true;
7444             }
7445 #endif
7446             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
7447                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
7448                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
7449                 return true;
7450             }
7451 #ifdef ENABLE_BLE
7452             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
7453                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
7454                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
7455                 return true;
7456             }
7457 #endif
7458         }
7459 
7460 #ifdef ENABLE_BLE
7461         switch (connection->le_con_parameter_update_state){
7462             // response to L2CAP CON PARAMETER UPDATE REQUEST
7463             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
7464                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7465                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
7466                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7467                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7468                 return true;
7469             case CON_PARAMETER_UPDATE_REPLY:
7470                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7471                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
7472                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7473                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7474                 return true;
7475             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
7476                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
7477                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
7478                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
7479                 return true;
7480             default:
7481                 break;
7482         }
7483         if (connection->le_phy_update_all_phys != 0xffu){
7484             uint8_t all_phys = connection->le_phy_update_all_phys;
7485             connection->le_phy_update_all_phys = 0xff;
7486             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);
7487             return true;
7488         }
7489 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7490         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
7491             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
7492             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
7493             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
7494             return true;
7495         }
7496         if (connection->le_past_advertising_handle != 0xff){
7497             uint8_t advertising_handle = connection->le_past_advertising_handle;
7498             connection->le_past_advertising_handle = 0xff;
7499             hci_send_cmd(&hci_le_periodic_advertising_set_info_transfer, connection->con_handle, connection->le_past_service_data, advertising_handle);
7500             return true;
7501         }
7502 #endif
7503 #endif
7504     }
7505     return false;
7506 }
7507 
7508 static void hci_run(void){
7509 
7510     // stack state sub statemachines
7511     switch (hci_stack->state) {
7512         case HCI_STATE_INITIALIZING:
7513             hci_initializing_run();
7514             break;
7515         case HCI_STATE_HALTING:
7516             hci_halting_run();
7517             break;
7518         case HCI_STATE_FALLING_ASLEEP:
7519             hci_falling_asleep_run();
7520             break;
7521         default:
7522             break;
7523     }
7524 
7525     // allow to run after initialization to working transition
7526     if (hci_stack->state != HCI_STATE_WORKING){
7527         return;
7528     }
7529 
7530     bool done;
7531 
7532     // send continuation fragments first, as they block the prepared packet buffer
7533     done = hci_run_acl_fragments();
7534     if (done) return;
7535 
7536 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7537     done = hci_run_iso_fragments();
7538     if (done) return;
7539 #endif
7540 
7541 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7542     // send host num completed packets next as they don't require num_cmd_packets > 0
7543     if (!hci_can_send_comand_packet_transport()) return;
7544     if (hci_stack->host_completed_packets){
7545         hci_host_num_completed_packets();
7546         return;
7547     }
7548 #endif
7549 
7550     if (!hci_can_send_command_packet_now()) return;
7551 
7552     // global/non-connection oriented commands
7553 
7554 
7555 #ifdef ENABLE_CLASSIC
7556     // general gap classic
7557     done = hci_run_general_gap_classic();
7558     if (done) return;
7559 #endif
7560 
7561 #ifdef ENABLE_BLE
7562     // general gap le
7563     done = hci_run_general_gap_le();
7564     if (done) return;
7565 
7566 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
7567     // ISO related tasks, e.g. BIG create/terminate/sync
7568     done = hci_run_iso_tasks();
7569     if (done) return;
7570 #endif
7571 #endif
7572 
7573     // send pending HCI commands
7574     hci_run_general_pending_commands();
7575 }
7576 
7577 #ifdef ENABLE_CLASSIC
7578 static void hci_set_sco_payload_length_for_flipped_packet_types(hci_connection_t * hci_connection, uint16_t flipped_packet_types){
7579     // bits 6-9 are 'don't use'
7580     uint16_t packet_types = flipped_packet_types ^ 0x03c0;
7581 
7582     // restrict packet types to local and remote supported
7583     packet_types &= hci_connection->remote_supported_sco_packets & hci_stack->usable_packet_types_sco;
7584     hci_connection->sco_payload_length = hci_sco_payload_length_for_packet_types(packet_types);
7585     log_info("Possible SCO packet types 0x%04x => payload length %u", packet_types, hci_connection->sco_payload_length);
7586 }
7587 #endif
7588 
7589 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
7590     // house-keeping
7591 
7592 #ifdef ENABLE_CLASSIC
7593     bd_addr_t addr;
7594     hci_connection_t * conn;
7595 #endif
7596 #ifdef ENABLE_LE_CENTRAL
7597     uint8_t initiator_filter_policy;
7598 #endif
7599 
7600     uint16_t opcode = little_endian_read_16(packet, 0);
7601     switch (opcode) {
7602         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
7603             hci_stack->loopback_mode = packet[3];
7604             break;
7605 
7606 #ifdef ENABLE_CLASSIC
7607         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7608             reverse_bd_addr(&packet[3], addr);
7609             log_info("Create_connection to %s", bd_addr_to_str(addr));
7610 
7611             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
7612             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
7613                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
7614                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
7615             }
7616 
7617             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7618             if (!conn) {
7619                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
7620                 if (!conn) {
7621                     // notify client that alloc failed
7622                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7623                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
7624                 }
7625                 conn->state = SEND_CREATE_CONNECTION;
7626             }
7627 
7628             log_info("conn state %u", conn->state);
7629             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7630             switch (conn->state) {
7631                 // if connection active exists
7632                 case OPEN:
7633                     // and OPEN, emit connection complete command
7634                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
7635                     // packet not sent to controller
7636                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7637                 case RECEIVED_DISCONNECTION_COMPLETE:
7638                     // create connection triggered in disconnect complete event, let's do it now
7639                     break;
7640                 case SEND_CREATE_CONNECTION:
7641 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
7642                     if (hci_classic_operation_active()){
7643                         return ERROR_CODE_SUCCESS;
7644                     }
7645 #endif
7646                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7647                     break;
7648                 default:
7649                     // otherwise, just ignore as it is already in the open process
7650                     // packet not sent to controller
7651                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7652             }
7653             conn->state = SENT_CREATE_CONNECTION;
7654 
7655             // track outgoing connection
7656             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
7657             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7658             break;
7659 
7660         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
7661             conn = hci_connection_for_handle(little_endian_read_16(packet, 3));
7662             if (conn == NULL) {
7663                 // neither SCO nor ACL connection for con handle
7664                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7665             } else {
7666                 uint16_t remote_supported_sco_packets;
7667                 switch (conn->address_type){
7668                     case BD_ADDR_TYPE_ACL:
7669                         // assert SCO connection does not exit
7670                         if (hci_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO) != NULL){
7671                             return ERROR_CODE_COMMAND_DISALLOWED;
7672                         }
7673                         // cache remote sco packet types
7674                         remote_supported_sco_packets = conn->remote_supported_sco_packets;
7675 
7676                         // allocate connection struct
7677                         conn = create_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO,
7678                                                                       HCI_ROLE_MASTER);
7679                         if (!conn) {
7680                             return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7681                         }
7682                         conn->remote_supported_sco_packets = remote_supported_sco_packets;
7683                         break;
7684                     case BD_ADDR_TYPE_SCO:
7685                         // update of existing SCO connection
7686                         break;
7687                     default:
7688                         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7689                 }
7690             }
7691 
7692             // conn refers to hci connection of type sco now
7693 
7694             conn->state = SENT_CREATE_CONNECTION;
7695 
7696             // track outgoing connection to handle command status with error
7697             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7698             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7699 
7700             // setup_synchronous_connection? Voice setting at offset 22
7701             // TODO: compare to current setting if sco connection already active
7702             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7703 
7704             // derive sco payload length from packet types
7705             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 18));
7706             break;
7707 
7708         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
7709             // get SCO connection
7710             reverse_bd_addr(&packet[3], addr);
7711             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
7712             if (conn == NULL){
7713                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7714             }
7715 
7716             conn->state = ACCEPTED_CONNECTION_REQUEST;
7717 
7718             // track outgoing connection to handle command status with error
7719             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7720             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
7721 
7722             // accept_synchronous_connection? Voice setting at offset 18
7723             // TODO: compare to current setting if sco connection already active
7724             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7725 
7726             // derive sco payload length from packet types
7727             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 22));
7728             break;
7729 #endif
7730 
7731 #ifdef ENABLE_BLE
7732 #ifdef ENABLE_LE_CENTRAL
7733         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7734             // white list used?
7735             initiator_filter_policy = packet[7];
7736             switch (initiator_filter_policy) {
7737                 case 0:
7738                     // whitelist not used
7739                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7740                     break;
7741                 case 1:
7742                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7743                     break;
7744                 default:
7745                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7746                     break;
7747             }
7748             // track outgoing connection
7749             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer address type
7750             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
7751             break;
7752 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7753         case HCI_OPCODE_HCI_LE_EXTENDED_CREATE_CONNECTION:
7754             // white list used?
7755             initiator_filter_policy = packet[3];
7756             switch (initiator_filter_policy) {
7757                 case 0:
7758                     // whitelist not used
7759                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7760                     break;
7761                 case 1:
7762                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7763                     break;
7764                 default:
7765                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7766                     break;
7767             }
7768             // track outgoing connection
7769             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[5]; // peer address type
7770             reverse_bd_addr( &packet[6], hci_stack->outgoing_addr); // peer address
7771             break;
7772 #endif
7773         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
7774             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
7775             break;
7776 #endif
7777 #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
7778         case HCI_OPCODE_HCI_LE_CONNECTION_UPDATE:
7779         case HCI_OPCODE_HCI_LE_READ_REMOTE_USED_FEATURES:
7780         case HCI_OPCODE_HCI_LE_START_ENCRYPTION:
7781         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_REQUEST_REPLY:
7782         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_NEGATIVE_REPLY:
7783         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY:
7784         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY:
7785         case HCI_OPCODE_HCI_LE_SET_DATA_LENGTH:
7786         case HCI_OPCODE_HCI_LE_READ_PHY:
7787         case HCI_OPCODE_HCI_LE_SET_PHY:
7788             // conection handle is first command parameter
7789             hci_stack->hci_command_con_handle = little_endian_read_16(packet, 3);
7790             break;
7791 #endif
7792 #endif /* ENABLE_BLE */
7793         default:
7794             break;
7795     }
7796 
7797     hci_stack->num_cmd_packets--;
7798 
7799     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
7800     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7801     if (err != 0){
7802         return ERROR_CODE_HARDWARE_FAILURE;
7803     }
7804     return ERROR_CODE_SUCCESS;
7805 }
7806 
7807 // disconnect because of security block
7808 void hci_disconnect_security_block(hci_con_handle_t con_handle){
7809     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7810     if (!connection) return;
7811     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
7812 }
7813 
7814 
7815 // Configure Secure Simple Pairing
7816 
7817 #ifdef ENABLE_CLASSIC
7818 
7819 // enable will enable SSP during init
7820 void gap_ssp_set_enable(int enable){
7821     hci_stack->ssp_enable = enable;
7822 }
7823 
7824 static int hci_local_ssp_activated(void){
7825     return gap_ssp_supported() && hci_stack->ssp_enable;
7826 }
7827 
7828 // if set, BTstack will respond to io capability request using authentication requirement
7829 void gap_ssp_set_io_capability(int io_capability){
7830     hci_stack->ssp_io_capability = io_capability;
7831 }
7832 void gap_ssp_set_authentication_requirement(int authentication_requirement){
7833     hci_stack->ssp_authentication_requirement = authentication_requirement;
7834 }
7835 
7836 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
7837 void gap_ssp_set_auto_accept(int auto_accept){
7838     hci_stack->ssp_auto_accept = auto_accept;
7839 }
7840 
7841 void gap_secure_connections_enable(bool enable){
7842     hci_stack->secure_connections_enable = enable;
7843 }
7844 bool gap_secure_connections_active(void){
7845     return hci_stack->secure_connections_active;
7846 }
7847 
7848 #endif
7849 
7850 // va_list part of hci_send_cmd
7851 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
7852     if (!hci_can_send_command_packet_now()){
7853         log_error("hci_send_cmd called but cannot send packet now");
7854         return ERROR_CODE_COMMAND_DISALLOWED;
7855     }
7856 
7857     // for HCI INITIALIZATION
7858     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
7859     hci_stack->last_cmd_opcode = cmd->opcode;
7860 
7861     hci_reserve_packet_buffer();
7862     uint8_t * packet = hci_stack->hci_packet_buffer;
7863     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
7864     uint8_t status = hci_send_cmd_packet(packet, size);
7865 
7866     // release packet buffer on error or for synchronous transport implementations
7867     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7868         hci_release_packet_buffer();
7869     }
7870 
7871     return status;
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