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