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