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