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