xref: /btstack/src/hci.c (revision 4bf33d8249d7bd61d6c2cf6fa19cc2f9c266f944)
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         case HCI_INIT_DONE:
2156             hci_stack->substate = HCI_INIT_DONE;
2157             // main init sequence complete
2158 #ifdef ENABLE_CLASSIC
2159             // check if initial Classic GAP Tasks are completed
2160             if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) {
2161                 hci_run_gap_tasks_classic();
2162                 break;
2163             }
2164 #endif
2165 #ifdef ENABLE_BLE
2166 #ifdef ENABLE_LE_CENTRAL
2167             // check if initial LE GAP Tasks are completed
2168             if (hci_le_supported() && hci_stack->le_scanning_param_update) {
2169                 hci_run_general_gap_le();
2170                 break;
2171             }
2172 #endif
2173 #endif
2174             hci_init_done();
2175             break;
2176 
2177         default:
2178             return;
2179     }
2180 }
2181 
2182 static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
2183     bool command_completed = false;
2184     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
2185         uint16_t opcode = little_endian_read_16(packet,3);
2186         if (opcode == hci_stack->last_cmd_opcode){
2187             command_completed = true;
2188             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
2189         } else {
2190             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
2191         }
2192     }
2193 
2194     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
2195         uint8_t  status = packet[2];
2196         uint16_t opcode = little_endian_read_16(packet,4);
2197         if (opcode == hci_stack->last_cmd_opcode){
2198             if (status){
2199                 command_completed = true;
2200                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
2201             } else {
2202                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
2203             }
2204         } else {
2205             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
2206         }
2207     }
2208 #ifndef HAVE_HOST_CONTROLLER_API
2209     // Vendor == CSR
2210     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2211         // TODO: track actual command
2212         command_completed = true;
2213     }
2214 
2215     // Vendor == Toshiba
2216     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2217         // TODO: track actual command
2218         command_completed = true;
2219         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
2220         hci_stack->num_cmd_packets = 1;
2221     }
2222 #endif
2223 
2224     return command_completed;
2225 }
2226 
2227 static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
2228 
2229     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
2230 
2231     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
2232 
2233 #ifndef HAVE_HOST_CONTROLLER_API
2234 
2235     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
2236     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
2237     //
2238     // HCI Reset
2239     // Timeout 100 ms
2240     // HCI Reset
2241     // Command Complete Reset
2242     // HCI Read Local Version Information
2243     // Command Complete Reset - but we expected Command Complete Read Local Version Information
2244     // hang...
2245     //
2246     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
2247     if (!command_completed
2248             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2249             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
2250 
2251         uint16_t opcode = little_endian_read_16(packet,3);
2252         if (opcode == hci_reset.opcode){
2253             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
2254             return;
2255         }
2256     }
2257 
2258     // CSR & H5
2259     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
2260     if (!command_completed
2261             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2262             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
2263 
2264         uint16_t opcode = little_endian_read_16(packet,3);
2265         if (opcode == hci_reset.opcode){
2266             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
2267             return;
2268         }
2269     }
2270 
2271     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
2272     // fix: Correct substate and behave as command below
2273     if (command_completed){
2274         switch (hci_stack->substate){
2275             case HCI_INIT_SEND_RESET:
2276                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
2277                 break;
2278             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
2279                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
2280                 break;
2281             default:
2282                 break;
2283         }
2284     }
2285 
2286 #endif
2287 
2288     if (!command_completed) return;
2289 
2290     bool need_baud_change = false;
2291     bool need_addr_change = false;
2292 
2293 #ifndef HAVE_HOST_CONTROLLER_API
2294     need_baud_change = hci_stack->config
2295                         && hci_stack->chipset
2296                         && hci_stack->chipset->set_baudrate_command
2297                         && hci_stack->hci_transport->set_baudrate
2298                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
2299 
2300     need_addr_change = hci_stack->custom_bd_addr_set
2301                         && hci_stack->chipset
2302                         && hci_stack->chipset->set_bd_addr_command;
2303 #endif
2304 
2305     switch(hci_stack->substate){
2306 
2307 #ifndef HAVE_HOST_CONTROLLER_API
2308         case HCI_INIT_SEND_RESET:
2309             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
2310             // fix: just correct substate and behave as command below
2311 
2312             /* fall through */
2313 #endif
2314 
2315         case HCI_INIT_W4_SEND_RESET:
2316             btstack_run_loop_remove_timer(&hci_stack->timeout);
2317             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
2318             return;
2319 
2320 #ifndef HAVE_HOST_CONTROLLER_API
2321         case HCI_INIT_W4_SEND_BAUD_CHANGE:
2322             // for STLC2500D, baud rate change already happened.
2323             // for others, baud rate gets changed now
2324             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
2325                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2326                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
2327                 hci_stack->hci_transport->set_baudrate(baud_rate);
2328             }
2329             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2330             return;
2331         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
2332             btstack_run_loop_remove_timer(&hci_stack->timeout);
2333             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2334             return;
2335         case HCI_INIT_W4_CUSTOM_INIT:
2336             // repeat custom init
2337             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2338             return;
2339 #endif
2340 
2341         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
2342             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2343               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
2344                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
2345                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
2346                 return;
2347             }
2348             if (need_addr_change){
2349                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2350                 return;
2351             }
2352             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2353             return;
2354 #ifndef HAVE_HOST_CONTROLLER_API
2355         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
2356             if (need_baud_change){
2357                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2358                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
2359                 hci_stack->hci_transport->set_baudrate(baud_rate);
2360             }
2361             if (need_addr_change){
2362                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2363                 return;
2364             }
2365             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2366             return;
2367         case HCI_INIT_W4_SET_BD_ADDR:
2368             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
2369             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
2370             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
2371                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
2372                 return;
2373             }
2374             // skipping st warm boot
2375             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2376             return;
2377         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
2378             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2379             return;
2380 #endif
2381 
2382         case HCI_INIT_DONE:
2383             // set state if we came here by fall through
2384             hci_stack->substate = HCI_INIT_DONE;
2385             return;
2386 
2387         default:
2388             break;
2389     }
2390     hci_initializing_next_state();
2391 }
2392 
2393 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
2394     // CC2564C might emit Connection Complete for rejected incoming SCO connection
2395     // To prevent accidentally free'ing the HCI connection for the ACL connection,
2396     // check if we have been aware of the HCI connection
2397     switch (conn->state){
2398         case SENT_CREATE_CONNECTION:
2399         case RECEIVED_CONNECTION_REQUEST:
2400             break;
2401         default:
2402             return;
2403     }
2404 
2405     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
2406     bd_addr_t bd_address;
2407     (void)memcpy(&bd_address, conn->address, 6);
2408 
2409 #ifdef ENABLE_CLASSIC
2410     // cache needed data
2411     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
2412 #endif
2413 
2414     // connection failed, remove entry
2415     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2416     btstack_memory_hci_connection_free( conn );
2417 
2418 #ifdef ENABLE_CLASSIC
2419     // notify client if dedicated bonding
2420     if (notify_dedicated_bonding_failed){
2421         log_info("hci notify_dedicated_bonding_failed");
2422         hci_emit_dedicated_bonding_result(bd_address, status);
2423     }
2424 
2425     // if authentication error, also delete link key
2426     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
2427         gap_drop_link_key_for_bd_addr(bd_address);
2428     }
2429 #else
2430     UNUSED(status);
2431 #endif
2432 }
2433 
2434 #ifdef ENABLE_CLASSIC
2435 static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
2436     // SSP Controller
2437     if (features[6] & (1 << 3)){
2438         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
2439     }
2440     // eSCO
2441     if (features[3] & (1<<7)){
2442         conn->remote_supported_features[0] |= 1;
2443     }
2444     // Extended features
2445     if (features[7] & (1<<7)){
2446         conn->remote_supported_features[0] |= 2;
2447     }
2448 }
2449 
2450 static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
2451     // SSP Host
2452     if (features[0] & (1 << 0)){
2453         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
2454     }
2455     // SC Host
2456     if (features[0] & (1 << 3)){
2457         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
2458     }
2459 }
2460 
2461 static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
2462     // SC Controller
2463     if (features[1] & (1 << 0)){
2464         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2465     }
2466 }
2467 
2468 static void hci_handle_remote_features_received(hci_connection_t * conn){
2469     conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE;
2470     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2471     log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags);
2472     if (conn->bonding_flags & BONDING_DEDICATED){
2473         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2474     }
2475 }
2476 static bool hci_remote_sc_enabled(hci_connection_t * connection){
2477     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2478     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2479 }
2480 
2481 #endif
2482 
2483 static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
2484     // handle BT initialization
2485     if (hci_stack->state == HCI_STATE_INITIALIZING) {
2486         hci_initializing_event_handler(packet, size);
2487     }
2488 
2489     // help with BT sleep
2490     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
2491         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
2492         && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2493         && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){
2494         hci_initializing_next_state();
2495     }
2496 }
2497 
2498 #ifdef ENABLE_CLASSIC
2499 static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
2500     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2501     conn->encryption_key_size = encryption_key_size;
2502     gap_security_level_t security_level = gap_security_level_for_connection(conn);
2503 
2504     // trigger disconnect for dedicated bonding, skip emit security level as disconnect is pending
2505     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
2506         conn->bonding_flags &= ~BONDING_DEDICATED;
2507         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2508         conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS;
2509         return;
2510     }
2511 
2512     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
2513         conn->requested_security_level = LEVEL_0;
2514         hci_emit_security_level(conn->con_handle, security_level);
2515         return;
2516     }
2517 
2518     // Request remote features if not already done
2519     hci_trigger_remote_features_for_connection(conn);
2520 
2521     // Request Authentication if not already done
2522     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
2523     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2524 }
2525 #endif
2526 
2527 static void hci_store_local_supported_commands(const uint8_t * packet){
2528     // create mapping table
2529 #define X(name, offset, bit) { offset, bit },
2530     static struct {
2531         uint8_t byte_offset;
2532         uint8_t bit_position;
2533     } supported_hci_commands_map [] = {
2534         SUPPORTED_HCI_COMMANDS
2535     };
2536 #undef X
2537 
2538     // create names for debug purposes
2539 #ifdef ENABLE_LOG_DEBUG
2540 #define X(name, offset, bit) #name,
2541     static const char * command_names[] = {
2542         SUPPORTED_HCI_COMMANDS
2543     };
2544 #undef X
2545 #endif
2546 
2547     hci_stack->local_supported_commands = 0;
2548     const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1];
2549     uint16_t i;
2550     for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){
2551         if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){
2552 #ifdef ENABLE_LOG_DEBUG
2553             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);
2554 #else
2555             log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
2556 #endif
2557             hci_stack->local_supported_commands |= (1LU << i);
2558         }
2559     }
2560     log_info("Local supported commands summary %04x", hci_stack->local_supported_commands);
2561 }
2562 
2563 static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2564     UNUSED(size);
2565 
2566     uint16_t manufacturer;
2567 #ifdef ENABLE_CLASSIC
2568     hci_con_handle_t handle;
2569     hci_connection_t * conn;
2570 #endif
2571 #if defined(ENABLE_CLASSIC) || (defined(ENABLE_BLE) && defined(ENABLE_LE_ISOCHRONOUS_STREAMS))
2572     uint8_t status;
2573 #endif
2574     // get num cmd packets - limit to 1 to reduce complexity
2575     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
2576 
2577     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2578     switch (opcode){
2579         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2580             if (packet[5]) break;
2581             // terminate, name 248 chars
2582             packet[6+248] = 0;
2583             log_info("local name: %s", &packet[6]);
2584             break;
2585         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
2586             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2587             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2588                 uint16_t acl_len = little_endian_read_16(packet, 6);
2589                 uint16_t sco_len = packet[8];
2590 
2591                 // determine usable ACL/SCO payload size
2592                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2593                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2594 
2595                 hci_stack->acl_packets_total_num = (uint8_t) little_endian_read_16(packet, 9);
2596                 hci_stack->sco_packets_total_num = (uint8_t) little_endian_read_16(packet, 11);
2597 
2598                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2599                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
2600                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2601             }
2602             break;
2603         case HCI_OPCODE_HCI_READ_RSSI:
2604             if (packet[5] == ERROR_CODE_SUCCESS){
2605                 uint8_t event[5];
2606                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2607                 event[1] = 3;
2608                 (void)memcpy(&event[2], &packet[6], 3);
2609                 hci_emit_event(event, sizeof(event), 1);
2610             }
2611             break;
2612 #ifdef ENABLE_BLE
2613         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2:
2614             hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9);
2615             hci_stack->le_iso_packets_total_num = packet[11];
2616             log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u",
2617                      hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num);
2618 
2619             /* fall through */
2620 
2621         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2622             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2623             hci_stack->le_acl_packets_total_num = packet[8];
2624             // determine usable ACL payload size
2625             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
2626                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
2627             }
2628             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);
2629             break;
2630 #endif
2631 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2632         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2633             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2634             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2635             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);
2636             break;
2637 #endif
2638 #ifdef ENABLE_LE_CENTRAL
2639         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2640             hci_stack->le_whitelist_capacity = packet[6];
2641             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2642             break;
2643 #endif
2644 #ifdef ENABLE_LE_PERIPHERAL
2645 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
2646         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH:
2647             hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6);
2648             break;
2649         case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS:
2650             if (hci_stack->le_advertising_set_in_current_command != 0) {
2651                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2652                 hci_stack->le_advertising_set_in_current_command = 0;
2653                 if (advertising_set == NULL) break;
2654                 uint8_t adv_status = packet[6];
2655                 uint8_t tx_power   = packet[7];
2656                 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 };
2657                 if (adv_status == 0){
2658                     advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
2659                 }
2660                 hci_emit_event(event, sizeof(event), 1);
2661             }
2662             break;
2663         case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET:
2664             if (hci_stack->le_advertising_set_in_current_command != 0) {
2665                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2666                 hci_stack->le_advertising_set_in_current_command = 0;
2667                 if (advertising_set == NULL) break;
2668                 uint8_t adv_status = packet[5];
2669                 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, adv_status };
2670                 if (adv_status == 0){
2671                     btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set);
2672                 }
2673                 hci_emit_event(event, sizeof(event), 1);
2674             }
2675             break;
2676 #endif
2677 #endif
2678         case HCI_OPCODE_HCI_READ_BD_ADDR:
2679             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2680             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));
2681 #ifdef ENABLE_CLASSIC
2682             if (hci_stack->link_key_db){
2683                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
2684             }
2685 #endif
2686             break;
2687 #ifdef ENABLE_CLASSIC
2688         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
2689             hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
2690             break;
2691         case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE:
2692             status = hci_event_command_complete_get_return_parameters(packet)[0];
2693             if (status == ERROR_CODE_SUCCESS) {
2694                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC;
2695             } else {
2696                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2697             }
2698             break;
2699         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2700         case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE:
2701             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2702                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2703                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2704                 hci_emit_event(event, sizeof(event), 1);
2705             }
2706             break;
2707 #endif
2708         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
2709             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
2710 
2711 #ifdef ENABLE_CLASSIC
2712             // determine usable ACL packet types based on host buffer size and supported features
2713             hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
2714             log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
2715 #endif
2716             // Classic/LE
2717             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2718             break;
2719         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2720             manufacturer = little_endian_read_16(packet, 10);
2721             // map Cypress to Broadcom
2722             if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2723                 log_info("Treat Cypress as Broadcom");
2724                 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2725                 little_endian_store_16(packet, 10, manufacturer);
2726             }
2727             hci_stack->manufacturer = manufacturer;
2728             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2729             break;
2730         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2731             hci_store_local_supported_commands(packet);
2732             break;
2733 #ifdef ENABLE_CLASSIC
2734         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2735             if (packet[5]) return;
2736             hci_stack->synchronous_flow_control_enabled = 1;
2737             break;
2738         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2739             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2740             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2741             conn   = hci_connection_for_handle(handle);
2742             if (conn != NULL) {
2743                 uint8_t key_size = 0;
2744                 if (status == 0){
2745                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
2746                     log_info("Handle %04x key Size: %u", handle, key_size);
2747                 } else {
2748                     key_size = 1;
2749                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2750                 }
2751                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2752             }
2753             break;
2754         // assert pairing complete event is emitted.
2755         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
2756         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
2757         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
2758         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
2759             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2760             // lookup connection by gap pairing addr
2761             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
2762             if (conn == NULL) break;
2763             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2764             break;
2765 
2766 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2767         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
2768         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
2769             uint8_t event[67];
2770             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
2771             event[1] = 65;
2772             (void)memset(&event[2], 0, 65);
2773             if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){
2774                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
2775                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
2776                     event[2] = 3;
2777                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
2778                 } else {
2779                     event[2] = 1;
2780                 }
2781             }
2782             hci_emit_event(event, sizeof(event), 0);
2783             break;
2784         }
2785 
2786         // note: only needed if user does not provide OOB data
2787         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
2788             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
2789             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
2790             if (conn == NULL) break;
2791             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2792             break;
2793 #endif
2794 #endif
2795 #ifdef ENABLE_BLE
2796 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2797         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
2798         case HCI_OPCODE_HCI_LE_CREATE_CIS:
2799             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2800             if (status != ERROR_CODE_SUCCESS){
2801                 hci_iso_stream_requested_finalize(0xff);
2802             }
2803             break;
2804         case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: {
2805             // lookup BIG by state
2806             btstack_linked_list_iterator_t it;
2807             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
2808             while (btstack_linked_list_iterator_has_next(&it)) {
2809                 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
2810                 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
2811                     status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2812                     if (status == ERROR_CODE_SUCCESS){
2813                         big->state_vars.next_bis++;
2814                         if (big->state_vars.next_bis == big->num_bis){
2815                             big->state = LE_AUDIO_BIG_STATE_ACTIVE;
2816                             hci_emit_big_created(big, ERROR_CODE_SUCCESS);
2817                         } else {
2818                             big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
2819                         }
2820                     } else {
2821                         big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
2822                         big->state_vars.status = status;
2823                     }
2824                     return;
2825                 }
2826             }
2827             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
2828             while (btstack_linked_list_iterator_has_next(&it)) {
2829                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
2830                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
2831                     status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2832                     if (status == ERROR_CODE_SUCCESS){
2833                         big_sync->state_vars.next_bis++;
2834                         if (big_sync->state_vars.next_bis == big_sync->num_bis){
2835                             big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE;
2836                             hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS);
2837                         } else {
2838                             big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
2839                         }
2840                     } else {
2841                         big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
2842                         big_sync->state_vars.status = status;
2843                     }
2844                     return;
2845                 }
2846             }
2847             break;
2848         }
2849         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
2850             // lookup BIG by state
2851             btstack_linked_list_iterator_t it;
2852             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
2853             while (btstack_linked_list_iterator_has_next(&it)) {
2854                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
2855                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED){
2856                     btstack_linked_list_iterator_remove(&it);
2857                     switch (big_sync->state){
2858                         case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
2859                             hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
2860                             break;
2861                         default:
2862                             hci_emit_big_sync_stopped(big_sync);
2863                             break;
2864                     }
2865                     return;
2866                 }
2867             }
2868             break;
2869         }
2870 #endif
2871 #endif
2872         default:
2873             break;
2874     }
2875 }
2876 
2877 static void handle_command_status_event(uint8_t * packet, uint16_t size) {
2878     UNUSED(size);
2879 
2880     // get num cmd packets - limit to 1 to reduce complexity
2881     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2882 
2883     // get opcode and command status
2884     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
2885 
2886 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
2887     uint8_t status = hci_event_command_status_get_status(packet);
2888 #endif
2889 
2890 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
2891     bd_addr_type_t addr_type;
2892 #endif
2893 
2894     switch (opcode){
2895 #ifdef ENABLE_CLASSIC
2896         case HCI_OPCODE_HCI_CREATE_CONNECTION:
2897         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
2898 #endif
2899 #ifdef ENABLE_LE_CENTRAL
2900         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
2901 #endif
2902 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
2903             addr_type = hci_stack->outgoing_addr_type;
2904 
2905             // reset outgoing address info
2906             memset(hci_stack->outgoing_addr, 0, 6);
2907             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2908 
2909             // on error
2910             if (status != ERROR_CODE_SUCCESS){
2911 #ifdef ENABLE_LE_CENTRAL
2912                 if (hci_is_le_connection_type(addr_type)){
2913                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2914                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2915                 }
2916 #endif
2917                 // error => outgoing connection failed
2918                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
2919                 if (conn != NULL){
2920                     hci_handle_connection_failed(conn, status);
2921                 }
2922             }
2923             break;
2924 #endif
2925 #ifdef ENABLE_CLASSIC
2926         case HCI_OPCODE_HCI_INQUIRY:
2927             if (status == ERROR_CODE_SUCCESS) {
2928                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2929             } else {
2930                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2931             }
2932             break;
2933 #endif
2934 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2935         case HCI_OPCODE_HCI_LE_CREATE_CIS:
2936         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
2937             if (status == ERROR_CODE_SUCCESS){
2938                 hci_iso_stream_requested_confirm(0xff);
2939             } else {
2940                 hci_iso_stream_requested_finalize(0xff);
2941             }
2942             break;
2943 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
2944         default:
2945             break;
2946     }
2947 }
2948 
2949 #ifdef ENABLE_BLE
2950 static void event_handle_le_connection_complete(const uint8_t * packet){
2951 	bd_addr_t addr;
2952 	bd_addr_type_t addr_type;
2953 	hci_connection_t * conn;
2954 
2955 	// Connection management
2956 	reverse_bd_addr(&packet[8], addr);
2957 	addr_type = (bd_addr_type_t)packet[7];
2958 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2959 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2960 
2961 #ifdef ENABLE_LE_CENTRAL
2962 	// handle error: error is reported only to the initiator -> outgoing connection
2963 	if (packet[3]){
2964 
2965 		// handle cancelled outgoing connection
2966 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2967 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2968 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2969 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2970 		    // reset state
2971             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2972             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2973 			// get outgoing connection conn struct for direct connect
2974 			conn = gap_get_outgoing_connection();
2975 		}
2976 
2977 		// outgoing le connection establishment is done
2978 		if (conn){
2979 			// remove entry
2980 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2981 			btstack_memory_hci_connection_free( conn );
2982 		}
2983 		return;
2984 	}
2985 #endif
2986 
2987 	// on success, both hosts receive connection complete event
2988 	if (packet[6] == HCI_ROLE_MASTER){
2989 #ifdef ENABLE_LE_CENTRAL
2990 		// if we're master on an le connection, it was an outgoing connection and we're done with it
2991 		// note: no hci_connection_t object exists yet for connect with whitelist
2992 		if (hci_is_le_connection_type(addr_type)){
2993 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2994 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2995 		}
2996 #endif
2997 	} else {
2998 #ifdef ENABLE_LE_PERIPHERAL
2999 		// if we're slave, it was an incoming connection, advertisements have stopped
3000         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
3001 #endif
3002 	}
3003 
3004 	// LE connections are auto-accepted, so just create a connection if there isn't one already
3005 	if (!conn){
3006 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3007 	}
3008 
3009 	// no memory, sorry.
3010 	if (!conn){
3011 		return;
3012 	}
3013 
3014 	conn->state = OPEN;
3015 	conn->role  = packet[6];
3016 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
3017 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
3018 
3019 #ifdef ENABLE_LE_PERIPHERAL
3020 	if (packet[6] == HCI_ROLE_SLAVE){
3021 		hci_update_advertisements_enabled_for_current_roles();
3022 	}
3023 #endif
3024 
3025     // init unenhanced att bearer mtu
3026     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3027     conn->att_connection.mtu_exchanged = false;
3028 
3029     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
3030 
3031 	// restart timer
3032 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3033 	// btstack_run_loop_add_timer(&conn->timeout);
3034 
3035 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3036 
3037 	hci_emit_nr_connections_changed();
3038 }
3039 #endif
3040 
3041 #ifdef ENABLE_CLASSIC
3042 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){
3043     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
3044     // LEVEL_4 is tested by l2cap
3045     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
3046     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
3047     if (level >= LEVEL_3){
3048         // MITM not possible without keyboard or display
3049         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3050         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3051 
3052         // MITM possible if one side has keyboard and the other has keyboard or display
3053         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3054         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3055 
3056         // MITM not possible if one side has only display and other side has no keyboard
3057         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3058         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3059     }
3060     // LEVEL 2 requires SSP, which is a given
3061     return true;
3062 }
3063 
3064 static bool btstack_is_null(uint8_t * data, uint16_t size){
3065     uint16_t i;
3066     for (i=0; i < size ; i++){
3067         if (data[i] != 0) {
3068             return false;
3069         }
3070     }
3071     return true;
3072 }
3073 
3074 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
3075     // get requested security level
3076     gap_security_level_t requested_security_level = conn->requested_security_level;
3077     if (hci_stack->gap_secure_connections_only_mode){
3078         requested_security_level = LEVEL_4;
3079     }
3080 
3081     // assess security: LEVEL 4 requires SC
3082     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
3083     if ((requested_security_level == LEVEL_4) &&
3084         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
3085         !hci_remote_sc_enabled(conn)){
3086         log_info("Level 4 required, but SC not supported -> abort");
3087         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3088         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3089         return;
3090     }
3091 
3092     // assess security based on io capabilities
3093     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3094         // responder: fully validate io caps of both sides as well as OOB data
3095         bool security_possible = false;
3096         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3097 
3098 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3099         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3100         // so we merge the OOB data availability
3101         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3102         if (conn->classic_oob_c_192 != NULL){
3103             have_oob_data |= 1;
3104         }
3105         if (conn->classic_oob_c_256 != NULL){
3106             have_oob_data |= 2;
3107         }
3108         // for up to Level 3, either P-192 as well as P-256 will do
3109         // 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
3110         // if remote does not SC, we should not receive P-256 data either
3111         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3112             security_possible = true;
3113         }
3114         // for Level 4, P-256 is needed
3115         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3116             security_possible = true;
3117         }
3118 #endif
3119 
3120         if (security_possible == false){
3121             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3122             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3123             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3124             return;
3125         }
3126     } else {
3127         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
3128 #ifndef ENABLE_CLASSIC_PAIRING_OOB
3129 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3130         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3131             log_info("Level 3+ required, but no input/output -> abort");
3132             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3133             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3134             return;
3135         }
3136 #endif
3137 #endif
3138     }
3139 
3140 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3141     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3142         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3143     } else {
3144         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3145     }
3146 #endif
3147 }
3148 
3149 #endif
3150 
3151 static void event_handler(uint8_t *packet, uint16_t size){
3152 
3153     uint16_t event_length = packet[1];
3154 
3155     // assert packet is complete
3156     if (size != (event_length + 2u)){
3157         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
3158         return;
3159     }
3160 
3161     hci_con_handle_t handle;
3162     hci_connection_t * conn;
3163     int i;
3164 
3165 #ifdef ENABLE_CLASSIC
3166     hci_link_type_t link_type;
3167     bd_addr_t addr;
3168     bd_addr_type_t addr_type;
3169 #endif
3170 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3171     hci_iso_stream_t * iso_stream;
3172     le_audio_big_t   * big;
3173     le_audio_big_sync_t * big_sync;
3174 #endif
3175 
3176     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
3177 
3178     switch (hci_event_packet_get_type(packet)) {
3179 
3180         case HCI_EVENT_COMMAND_COMPLETE:
3181             handle_command_complete_event(packet, size);
3182             break;
3183 
3184         case HCI_EVENT_COMMAND_STATUS:
3185             handle_command_status_event(packet, size);
3186             break;
3187 
3188         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
3189             if (size < 3) return;
3190             uint16_t num_handles = packet[2];
3191             if (size != (3u + num_handles * 4u)) return;
3192             uint16_t offset = 3;
3193             for (i=0; i<num_handles;i++){
3194                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
3195                 offset += 2u;
3196                 uint16_t num_packets = little_endian_read_16(packet, offset);
3197                 offset += 2u;
3198 
3199                 conn = hci_connection_for_handle(handle);
3200                 if (conn != NULL) {
3201 
3202                     if (conn->num_packets_sent >= num_packets) {
3203                         conn->num_packets_sent -= num_packets;
3204                     } else {
3205                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3206                         conn->num_packets_sent = 0;
3207                     }
3208                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3209                 }
3210 
3211 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
3212                 hci_controller_dump_packets();
3213 #endif
3214 
3215 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3216                 if (conn == NULL){
3217                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle);
3218                     if (iso_stream != NULL){
3219                         if (iso_stream->num_packets_sent >= num_packets) {
3220                             iso_stream->num_packets_sent -= num_packets;
3221                         } else {
3222                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3223                             iso_stream->num_packets_sent = 0;
3224                         }
3225                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3226                                  num_packets, handle, iso_stream->num_packets_sent);
3227                     }
3228                     hci_iso_notify_can_send_now();
3229                 }
3230 #endif
3231 
3232 #ifdef ENABLE_CLASSIC
3233                 // For SCO, we do the can_send_now_check here
3234                 hci_notify_if_sco_can_send_now();
3235 #endif
3236             }
3237             break;
3238         }
3239 
3240 #ifdef ENABLE_CLASSIC
3241         case HCI_EVENT_FLUSH_OCCURRED:
3242             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
3243             handle = hci_event_flush_occurred_get_handle(packet);
3244             conn = hci_connection_for_handle(handle);
3245             if (conn) {
3246                 log_info("Flush occurred, disconnect 0x%04x", handle);
3247                 conn->state = SEND_DISCONNECT;
3248             }
3249             break;
3250 
3251         case HCI_EVENT_INQUIRY_COMPLETE:
3252             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3253                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3254                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
3255                 hci_emit_event(event, sizeof(event), 1);
3256             }
3257             break;
3258         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3259             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3260                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3261             }
3262             break;
3263         case HCI_EVENT_CONNECTION_REQUEST:
3264             reverse_bd_addr(&packet[2], addr);
3265             link_type = (hci_link_type_t) packet[11];
3266 
3267             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
3268             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
3269                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
3270                 bd_addr_copy(hci_stack->decline_addr, addr);
3271                 break;
3272             }
3273 
3274             if (hci_stack->gap_classic_accept_callback != NULL){
3275                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3276                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
3277                     bd_addr_copy(hci_stack->decline_addr, addr);
3278                     break;
3279                 }
3280             }
3281 
3282             // TODO: eval COD 8-10
3283             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
3284             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
3285             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3286             if (!conn) {
3287                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3288             }
3289             if (!conn) {
3290                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
3291                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3292                 bd_addr_copy(hci_stack->decline_addr, addr);
3293                 hci_run();
3294                 // avoid event to higher layer
3295                 return;
3296             }
3297             conn->role  = HCI_ROLE_SLAVE;
3298             conn->state = RECEIVED_CONNECTION_REQUEST;
3299             // store info about eSCO
3300             if (link_type == HCI_LINK_TYPE_ESCO){
3301                 conn->remote_supported_features[0] |= 1;
3302             }
3303             hci_run();
3304             break;
3305 
3306         case HCI_EVENT_CONNECTION_COMPLETE:
3307             // Connection management
3308             reverse_bd_addr(&packet[5], addr);
3309             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3310             addr_type = BD_ADDR_TYPE_ACL;
3311             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3312             if (conn) {
3313                 if (!packet[2]){
3314                     conn->state = OPEN;
3315                     conn->con_handle = little_endian_read_16(packet, 3);
3316 
3317                     // trigger write supervision timeout if we're master
3318                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
3319                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
3320                     }
3321 
3322                     // trigger write automatic flush timeout
3323                     if (hci_stack->automatic_flush_timeout != 0){
3324                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
3325                     }
3326 
3327                     // restart timer
3328                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3329                     btstack_run_loop_add_timer(&conn->timeout);
3330 
3331                     // trigger remote features for dedicated bonding
3332                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3333                         hci_trigger_remote_features_for_connection(conn);
3334                     }
3335 
3336                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3337 
3338                     hci_emit_nr_connections_changed();
3339                 } else {
3340                     // connection failed
3341                     hci_handle_connection_failed(conn, packet[2]);
3342                 }
3343             }
3344             break;
3345 
3346         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3347             reverse_bd_addr(&packet[5], addr);
3348             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3349             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3350             if (packet[2]){
3351                 // connection failed
3352                 if (conn){
3353                     hci_handle_connection_failed(conn, packet[2]);
3354                 }
3355                 break;
3356             }
3357             if (!conn) {
3358                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3359             }
3360             if (!conn) {
3361                 break;
3362             }
3363             conn->state = OPEN;
3364             conn->con_handle = little_endian_read_16(packet, 3);
3365 
3366 #ifdef ENABLE_SCO_OVER_HCI
3367             // update SCO
3368             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3369                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3370             }
3371             // trigger can send now
3372             if (hci_have_usb_transport()){
3373                 hci_stack->sco_can_send_now = true;
3374             }
3375 #endif
3376 #ifdef HAVE_SCO_TRANSPORT
3377             // configure sco transport
3378             if (hci_stack->sco_transport != NULL){
3379                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3380                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3381             }
3382 #endif
3383             break;
3384 
3385         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3386             handle = little_endian_read_16(packet, 3);
3387             conn = hci_connection_for_handle(handle);
3388             if (!conn) break;
3389             if (!packet[2]){
3390                 const uint8_t * features = &packet[5];
3391                 hci_handle_remote_features_page_0(conn, features);
3392 
3393                 // read extended features if possible
3394                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
3395                 && ((conn->remote_supported_features[0] & 2) != 0)) {
3396                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
3397                     break;
3398                 }
3399             }
3400             hci_handle_remote_features_received(conn);
3401             break;
3402 
3403         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3404             handle = little_endian_read_16(packet, 3);
3405             conn = hci_connection_for_handle(handle);
3406             if (!conn) break;
3407             // status = ok, page = 1
3408             if (!packet[2]) {
3409                 uint8_t page_number = packet[5];
3410                 uint8_t maximum_page_number = packet[6];
3411                 const uint8_t * features = &packet[7];
3412                 bool done = false;
3413                 switch (page_number){
3414                     case 1:
3415                         hci_handle_remote_features_page_1(conn, features);
3416                         if (maximum_page_number >= 2){
3417                             // get Secure Connections (Controller) from Page 2 if available
3418                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
3419                         } else {
3420                             // otherwise, assume SC (Controller) == SC (Host)
3421                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
3422                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
3423                             }
3424                             done = true;
3425                         }
3426                         break;
3427                     case 2:
3428                         hci_handle_remote_features_page_2(conn, features);
3429                         done = true;
3430                         break;
3431                     default:
3432                         break;
3433                 }
3434                 if (!done) break;
3435             }
3436             hci_handle_remote_features_received(conn);
3437             break;
3438 
3439         case HCI_EVENT_LINK_KEY_REQUEST:
3440 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
3441             hci_event_link_key_request_get_bd_addr(packet, addr);
3442             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3443             if (!conn) break;
3444 
3445             // lookup link key in db if not cached
3446             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
3447                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
3448             }
3449 
3450             // response sent by hci_run()
3451             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
3452 #endif
3453             break;
3454 
3455         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
3456             hci_event_link_key_request_get_bd_addr(packet, addr);
3457             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3458             if (!conn) break;
3459 
3460             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
3461 
3462             // CVE-2020-26555: ignore NULL link key
3463             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
3464             if (btstack_is_null(&packet[8], 16)) break;
3465 
3466             link_key_type_t link_key_type = (link_key_type_t)packet[24];
3467             // Change Connection Encryption keeps link key type
3468             if (link_key_type != CHANGED_COMBINATION_KEY){
3469                 conn->link_key_type = link_key_type;
3470             }
3471 
3472             // cache link key. link keys stored in little-endian format for legacy reasons
3473             memcpy(&conn->link_key, &packet[8], 16);
3474 
3475             // only store link key:
3476             // - if bondable enabled
3477             if (hci_stack->bondable == false) break;
3478             // - if security level sufficient
3479             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
3480             // - for SSP, also check if remote side requested bonding as well
3481             if (conn->link_key_type != COMBINATION_KEY){
3482                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3483                 if (!remote_bonding){
3484                     break;
3485                 }
3486             }
3487             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
3488             break;
3489         }
3490 
3491         case HCI_EVENT_PIN_CODE_REQUEST:
3492             hci_event_pin_code_request_get_bd_addr(packet, addr);
3493             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3494             if (!conn) break;
3495 
3496             hci_pairing_started(conn, false);
3497             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
3498             if (!hci_stack->bondable ){
3499                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3500                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3501                 hci_run();
3502                 return;
3503             }
3504             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3505             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3506                 log_info("Level 4 required, but SC not supported -> abort");
3507                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3508                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3509                 hci_run();
3510                 return;
3511             }
3512             break;
3513 
3514         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
3515             hci_event_io_capability_response_get_bd_addr(packet, addr);
3516             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3517             if (!conn) break;
3518 
3519             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
3520             hci_pairing_started(conn, true);
3521             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3522             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3523 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3524             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3525 #endif
3526             break;
3527 
3528         case HCI_EVENT_IO_CAPABILITY_REQUEST:
3529             hci_event_io_capability_response_get_bd_addr(packet, addr);
3530             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3531             if (!conn) break;
3532 
3533             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
3534             hci_connection_timestamp(conn);
3535             hci_pairing_started(conn, true);
3536             break;
3537 
3538 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3539         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
3540             hci_event_remote_oob_data_request_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_connection_timestamp(conn);
3545 
3546             hci_pairing_started(conn, true);
3547 
3548             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
3549             break;
3550 #endif
3551 
3552         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
3553             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
3554             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3555             if (!conn) break;
3556             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
3557                 if (hci_stack->ssp_auto_accept){
3558                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
3559                 };
3560             } else {
3561                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3562                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
3563                 // don't forward event to app
3564                 hci_run();
3565                 return;
3566             }
3567             break;
3568 
3569         case HCI_EVENT_USER_PASSKEY_REQUEST:
3570             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
3571             if (hci_stack->ssp_auto_accept){
3572                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
3573             };
3574             break;
3575 
3576         case HCI_EVENT_MODE_CHANGE:
3577             handle = hci_event_mode_change_get_handle(packet);
3578             conn = hci_connection_for_handle(handle);
3579             if (!conn) break;
3580             conn->connection_mode = hci_event_mode_change_get_mode(packet);
3581             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
3582             break;
3583 #endif
3584 
3585         case HCI_EVENT_ENCRYPTION_CHANGE:
3586         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
3587             handle = hci_event_encryption_change_get_connection_handle(packet);
3588             conn = hci_connection_for_handle(handle);
3589             if (!conn) break;
3590             if (hci_event_encryption_change_get_status(packet) == 0u) {
3591                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
3592                 if (encryption_enabled){
3593                     if (hci_is_le_connection(conn)){
3594                         // For LE, we accept connection as encrypted
3595                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
3596                     }
3597 #ifdef ENABLE_CLASSIC
3598                     else {
3599 
3600                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
3601                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
3602                         bool connected_uses_aes_ccm = encryption_enabled == 2;
3603                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
3604                             log_info("SC during pairing, but only E0 now -> abort");
3605                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3606                             break;
3607                         }
3608 
3609                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
3610                         if (connected_uses_aes_ccm){
3611                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3612                         }
3613 
3614 #ifdef ENABLE_TESTING_SUPPORT
3615                         // work around for issue with PTS dongle
3616                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3617 #endif
3618                         // validate encryption key size
3619                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
3620                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
3621                             // already got encryption key size
3622                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
3623                         } else {
3624                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
3625                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
3626                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
3627                             } else {
3628                                 // if not, pretend everything is perfect
3629                                 hci_handle_read_encryption_key_size_complete(conn, 16);
3630                             }
3631                         }
3632                     }
3633 #endif
3634                 } else {
3635                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
3636                 }
3637             } else {
3638                 uint8_t status = hci_event_encryption_change_get_status(packet);
3639                 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3640                     conn->bonding_flags &= ~BONDING_DEDICATED;
3641                     conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
3642                     conn->bonding_status = status;
3643                 }
3644             }
3645 
3646             break;
3647 
3648 #ifdef ENABLE_CLASSIC
3649         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
3650             handle = hci_event_authentication_complete_get_connection_handle(packet);
3651             conn = hci_connection_for_handle(handle);
3652             if (!conn) break;
3653 
3654             // clear authentication active flag
3655             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
3656             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
3657 
3658             // authenticated only if auth status == 0
3659             if (hci_event_authentication_complete_get_status(packet) == 0){
3660                 // authenticated
3661                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3662 
3663                 // If not already encrypted, start encryption
3664                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
3665                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3666                     break;
3667                 }
3668             }
3669 
3670             // emit updated security level
3671             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
3672             break;
3673 
3674         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3675             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3676             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3677             if (!conn) break;
3678 
3679             // treat successfully paired connection as authenticated
3680             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
3681                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3682             }
3683 
3684             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
3685             break;
3686 #endif
3687 
3688         // HCI_EVENT_DISCONNECTION_COMPLETE
3689         // has been split, to first notify stack before shutting connection down
3690         // see end of function, too.
3691         case HCI_EVENT_DISCONNECTION_COMPLETE:
3692             if (packet[2]) break;   // status != 0
3693             handle = little_endian_read_16(packet, 3);
3694             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
3695             if (hci_stack->acl_fragmentation_total_size > 0u) {
3696                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3697                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
3698                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
3699                     hci_stack->acl_fragmentation_total_size = 0;
3700                     hci_stack->acl_fragmentation_pos = 0;
3701                     if (release_buffer){
3702                         hci_release_packet_buffer();
3703                     }
3704                 }
3705             }
3706 
3707 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3708             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
3709             if (hci_stack->iso_fragmentation_total_size > 0u) {
3710                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3711                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
3712                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
3713                     hci_stack->iso_fragmentation_total_size = 0;
3714                     hci_stack->iso_fragmentation_pos = 0;
3715                     if (release_buffer){
3716                         hci_release_packet_buffer();
3717                     }
3718                 }
3719             }
3720 
3721             // finalize iso stream if handle matches
3722             iso_stream = hci_iso_stream_for_con_handle(handle);
3723             if (iso_stream != NULL){
3724                 hci_iso_stream_finalize(iso_stream);
3725                 break;
3726             }
3727 #endif
3728 
3729             conn = hci_connection_for_handle(handle);
3730             if (!conn) break;
3731 #ifdef ENABLE_CLASSIC
3732             // pairing failed if it was ongoing
3733             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
3734 #endif
3735 
3736             // emit dedicatd bonding event
3737             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3738                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3739             }
3740 
3741             // mark connection for shutdown, stop timers, reset state
3742             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3743             hci_connection_stop_timer(conn);
3744             hci_connection_init(conn);
3745 
3746 #ifdef ENABLE_BLE
3747 #ifdef ENABLE_LE_PERIPHERAL
3748             // re-enable advertisements for le connections if active
3749             if (hci_is_le_connection(conn)){
3750                 hci_update_advertisements_enabled_for_current_roles();
3751             }
3752 #endif
3753 #endif
3754             break;
3755 
3756         case HCI_EVENT_HARDWARE_ERROR:
3757             log_error("Hardware Error: 0x%02x", packet[2]);
3758             if (hci_stack->hardware_error_callback){
3759                 (*hci_stack->hardware_error_callback)(packet[2]);
3760             } else {
3761                 // if no special requests, just reboot stack
3762                 hci_power_control_off();
3763                 hci_power_control_on();
3764             }
3765             break;
3766 
3767 #ifdef ENABLE_CLASSIC
3768         case HCI_EVENT_ROLE_CHANGE:
3769             if (packet[2]) break;   // status != 0
3770             reverse_bd_addr(&packet[3], addr);
3771             addr_type = BD_ADDR_TYPE_ACL;
3772             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3773             if (!conn) break;
3774             conn->role = packet[9];
3775             break;
3776 #endif
3777 
3778         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3779             // release packet buffer only for asynchronous transport and if there are not further fragments
3780             if (hci_transport_synchronous()) {
3781                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
3782                 return; // instead of break: to avoid re-entering hci_run()
3783             }
3784             hci_stack->acl_fragmentation_tx_active = 0;
3785 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3786             hci_stack->iso_fragmentation_tx_active = 0;
3787             if (hci_stack->iso_fragmentation_total_size) break;
3788 #endif
3789             if (hci_stack->acl_fragmentation_total_size) break;
3790             hci_release_packet_buffer();
3791 
3792 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3793             hci_iso_notify_can_send_now();
3794 #endif
3795             // L2CAP receives this event via the hci_emit_event below
3796 
3797 #ifdef ENABLE_CLASSIC
3798             // For SCO, we do the can_send_now_check here
3799             hci_notify_if_sco_can_send_now();
3800 #endif
3801             break;
3802 
3803 #ifdef ENABLE_CLASSIC
3804         case HCI_EVENT_SCO_CAN_SEND_NOW:
3805             // For SCO, we do the can_send_now_check here
3806             hci_stack->sco_can_send_now = true;
3807             hci_notify_if_sco_can_send_now();
3808             return;
3809 
3810         // explode inquriy results for easier consumption
3811         case HCI_EVENT_INQUIRY_RESULT:
3812         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3813         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3814             gap_inquiry_explode(packet, size);
3815             break;
3816 #endif
3817 
3818 #ifdef ENABLE_BLE
3819         case HCI_EVENT_LE_META:
3820             switch (packet[2]){
3821 #ifdef ENABLE_LE_CENTRAL
3822                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
3823                     if (!hci_stack->le_scanning_enabled) break;
3824                     le_handle_advertisement_report(packet, size);
3825                     break;
3826 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3827                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
3828                     if (!hci_stack->le_scanning_enabled) break;
3829                     le_handle_extended_advertisement_report(packet, size);
3830                     break;
3831 #endif
3832 #endif
3833                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3834 					event_handle_le_connection_complete(packet);
3835                     break;
3836 
3837                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3838                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3839                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3840                     conn = hci_connection_for_handle(handle);
3841                     if (!conn) break;
3842                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3843                     break;
3844 
3845                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
3846                     // connection
3847                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
3848                     conn = hci_connection_for_handle(handle);
3849                     if (conn) {
3850                         // read arguments
3851                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
3852                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
3853                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
3854                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
3855 
3856                         // validate against current connection parameter range
3857                         le_connection_parameter_range_t existing_range;
3858                         gap_get_connection_parameter_range(&existing_range);
3859                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3860                         if (update_parameter){
3861                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
3862                             conn->le_conn_interval_min = le_conn_interval_min;
3863                             conn->le_conn_interval_max = le_conn_interval_max;
3864                             conn->le_conn_latency = le_conn_latency;
3865                             conn->le_supervision_timeout = le_supervision_timeout;
3866                         } else {
3867                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
3868                         }
3869                     }
3870                     break;
3871 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3872                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
3873                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
3874                     conn = hci_connection_for_handle(handle);
3875                     if (conn) {
3876                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
3877                     }
3878                     break;
3879 #endif
3880 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3881                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
3882                     handle = hci_subevent_le_cis_established_get_connection_handle(packet);
3883                     iso_stream = hci_iso_stream_for_con_handle(handle);
3884                     if (iso_stream){
3885                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
3886                         if (status == ERROR_CODE_SUCCESS){
3887                             iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
3888                         } else {
3889                             hci_iso_stream_finalize(iso_stream);
3890                         }
3891                     }
3892                     break;
3893                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
3894                     big = hci_big_for_handle(packet[4]);
3895                     if (big != NULL){
3896                         uint8_t status = packet[3];
3897                         if (status == ERROR_CODE_SUCCESS){
3898                             // store bis_con_handles and trigger iso path setup
3899                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[20]);
3900                             uint8_t i;
3901                             for (i=0;i<num_bis;i++){
3902                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
3903                                 big->bis_con_handles[i] = bis_handle;
3904                                 // assign bis handle
3905                                 btstack_linked_list_iterator_t it;
3906                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3907                                 while (btstack_linked_list_iterator_has_next(&it)){
3908                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3909                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
3910                                         (iso_stream->big_handle == big->big_handle)){
3911                                         iso_stream->con_handle = bis_handle;
3912                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
3913                                     }
3914                                 }
3915                             }
3916                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
3917                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
3918                                 big->state_vars.next_bis = 0;
3919                             }
3920                         } else {
3921                             // create BIG failed or has been stopped by us
3922                             hci_iso_stream_requested_finalize(big->big_handle);
3923                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
3924                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
3925                                 hci_emit_big_created(big, status);
3926                             } else {
3927                                 hci_emit_big_terminated(big);
3928                             }
3929                         }
3930                     }
3931                     break;
3932                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
3933                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
3934                     if (big != NULL){
3935                         // finalize associated ISO streams
3936                         btstack_linked_list_iterator_t it;
3937                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3938                         while (btstack_linked_list_iterator_has_next(&it)){
3939                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3940                             if (iso_stream->big_handle == big->big_handle){
3941                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->big_handle, iso_stream->con_handle);
3942                                 btstack_linked_list_iterator_remove(&it);
3943                                 btstack_memory_hci_iso_stream_free(iso_stream);
3944                             }
3945                         }
3946                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
3947                         switch (big->state){
3948                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
3949                                 hci_emit_big_created(big, big->state_vars.status);
3950                                 break;
3951                             default:
3952                                 hci_emit_big_terminated(big);
3953                                 break;
3954                         }
3955                     }
3956                     break;
3957                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
3958                     big_sync = hci_big_sync_for_handle(packet[4]);
3959                     if (big_sync != NULL){
3960                         uint8_t status = packet[3];
3961                         if (status == ERROR_CODE_SUCCESS){
3962                             // store bis_con_handles and trigger iso path setup
3963                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[16]);
3964                             uint8_t i;
3965                             for (i=0;i<num_bis;i++){
3966                                 big_sync->bis_con_handles[i] = little_endian_read_16(packet, 17 + (2 * i));
3967                             }
3968                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
3969                                 // trigger iso path setup
3970                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
3971                                 big_sync->state_vars.next_bis = 0;
3972                             }
3973                         } else {
3974                             // create BIG Sync failed or has been stopped by us
3975                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
3976                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
3977                                 hci_emit_big_sync_created(big_sync, status);
3978                             } else {
3979                                 hci_emit_big_sync_stopped(big_sync);
3980                             }
3981                         }
3982                     }
3983                     break;
3984                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
3985                     big_sync = hci_big_sync_for_handle(packet[4]);
3986                     if (big_sync != NULL){
3987                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
3988                         hci_emit_big_sync_stopped(big_sync);
3989                     }
3990                     break;
3991 #endif
3992                 default:
3993                     break;
3994             }
3995             break;
3996 #endif
3997         case HCI_EVENT_VENDOR_SPECIFIC:
3998             // Vendor specific commands often create vendor specific event instead of num completed packets
3999             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
4000             switch (hci_stack->manufacturer){
4001                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
4002                     hci_stack->num_cmd_packets = 1;
4003                     break;
4004                 default:
4005                     break;
4006             }
4007             break;
4008         default:
4009             break;
4010     }
4011 
4012     handle_event_for_current_stack_state(packet, size);
4013 
4014     // notify upper stack
4015 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
4016 
4017     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4018     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4019 		handle = little_endian_read_16(packet, 3);
4020 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4021 		// discard connection if app did not trigger a reconnect in the event handler
4022 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
4023 			hci_shutdown_connection(aConn);
4024 		}
4025 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
4026         hci_controller_dump_packets();
4027 #endif
4028     }
4029 
4030 	// execute main loop
4031 	hci_run();
4032 }
4033 
4034 #ifdef ENABLE_CLASSIC
4035 
4036 #ifdef ENABLE_SCO_OVER_HCI
4037 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
4038 static void sco_schedule_tx(hci_connection_t * conn);
4039 
4040 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
4041     log_debug("SCO TX Timeout");
4042     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
4043     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4044     if (!conn) return;
4045 
4046     // trigger send
4047     conn->sco_tx_ready = 1;
4048     // extra packet if CVSD but SCO buffer is too short
4049     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
4050         conn->sco_tx_ready++;
4051     }
4052     hci_notify_if_sco_can_send_now();
4053 }
4054 
4055 
4056 #define SCO_TX_AFTER_RX_MS (6)
4057 
4058 static void sco_schedule_tx(hci_connection_t * conn){
4059 
4060     uint32_t now = btstack_run_loop_get_time_ms();
4061     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
4062     int time_delta_ms = sco_tx_ms - now;
4063 
4064     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
4065 
4066     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
4067     btstack_run_loop_remove_timer(timer);
4068     btstack_run_loop_set_timer(timer, time_delta_ms);
4069     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
4070     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
4071     btstack_run_loop_add_timer(timer);
4072 }
4073 #endif
4074 
4075 static void sco_handler(uint8_t * packet, uint16_t size){
4076     // lookup connection struct
4077     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
4078     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
4079     if (!conn) return;
4080 
4081 #ifdef ENABLE_SCO_OVER_HCI
4082     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4083     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4084         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4085             packet[2] = 0x3c;
4086             memmove(&packet[3], &packet[23], 63);
4087             size = 63;
4088         }
4089     }
4090 
4091     if (hci_have_usb_transport()){
4092         // Nothing to do
4093     } else {
4094         // 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);
4095         if (hci_stack->synchronous_flow_control_enabled == 0){
4096             uint32_t now = btstack_run_loop_get_time_ms();
4097 
4098             if (!conn->sco_rx_valid){
4099                 // ignore first 10 packets
4100                 conn->sco_rx_count++;
4101                 // log_debug("sco rx count %u", conn->sco_rx_count);
4102                 if (conn->sco_rx_count == 10) {
4103                     // use first timestamp as is and pretent it just started
4104                     conn->sco_rx_ms = now;
4105                     conn->sco_rx_valid = 1;
4106                     conn->sco_rx_count = 0;
4107                     sco_schedule_tx(conn);
4108                 }
4109             } else {
4110                 // track expected arrival timme
4111                 conn->sco_rx_count++;
4112                 conn->sco_rx_ms += 7;
4113                 int delta = (int32_t) (now - conn->sco_rx_ms);
4114                 if (delta > 0){
4115                     conn->sco_rx_ms++;
4116                 }
4117                 // log_debug("sco rx %u", conn->sco_rx_ms);
4118                 sco_schedule_tx(conn);
4119             }
4120         }
4121     }
4122 #endif
4123 
4124     // deliver to app
4125     if (hci_stack->sco_packet_handler) {
4126         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
4127     }
4128 
4129 #ifdef HAVE_SCO_TRANSPORT
4130     // We can send one packet for each received packet
4131     conn->sco_tx_ready++;
4132     hci_notify_if_sco_can_send_now();
4133 #endif
4134 
4135 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4136     conn->num_packets_completed++;
4137     hci_stack->host_completed_packets = 1;
4138     hci_run();
4139 #endif
4140 }
4141 #endif
4142 
4143 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
4144     hci_dump_packet(packet_type, 1, packet, size);
4145     switch (packet_type) {
4146         case HCI_EVENT_PACKET:
4147             event_handler(packet, size);
4148             break;
4149         case HCI_ACL_DATA_PACKET:
4150             acl_handler(packet, size);
4151             break;
4152 #ifdef ENABLE_CLASSIC
4153         case HCI_SCO_DATA_PACKET:
4154             sco_handler(packet, size);
4155             break;
4156 #endif
4157 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4158         case HCI_ISO_DATA_PACKET:
4159             hci_iso_packet_handler(packet, size);
4160             break;
4161 #endif
4162         default:
4163             break;
4164     }
4165 }
4166 
4167 /**
4168  * @brief Add event packet handler.
4169  */
4170 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4171     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4172 }
4173 
4174 /**
4175  * @brief Remove event packet handler.
4176  */
4177 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
4178     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4179 }
4180 
4181 /** Register HCI packet handlers */
4182 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4183     hci_stack->acl_packet_handler = handler;
4184 }
4185 
4186 #ifdef ENABLE_CLASSIC
4187 /**
4188  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
4189  */
4190 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
4191     hci_stack->sco_packet_handler = handler;
4192 }
4193 #endif
4194 
4195 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4196 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
4197     hci_stack->iso_packet_handler = handler;
4198 }
4199 #endif
4200 
4201 static void hci_state_reset(void){
4202     // no connections yet
4203     hci_stack->connections = NULL;
4204 
4205     // keep discoverable/connectable as this has been requested by the client(s)
4206     // hci_stack->discoverable = 0;
4207     // hci_stack->connectable = 0;
4208     // hci_stack->bondable = 1;
4209     // hci_stack->own_addr_type = 0;
4210 
4211     // buffer is free
4212     hci_stack->hci_packet_buffer_reserved = false;
4213 
4214     // no pending cmds
4215     hci_stack->decline_reason = 0;
4216 
4217     hci_stack->secure_connections_active = false;
4218 
4219 #ifdef ENABLE_CLASSIC
4220     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
4221     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
4222 
4223     hci_stack->gap_tasks_classic =
4224             GAP_TASK_SET_DEFAULT_LINK_POLICY |
4225             GAP_TASK_SET_CLASS_OF_DEVICE |
4226             GAP_TASK_SET_LOCAL_NAME |
4227             GAP_TASK_SET_EIR_DATA |
4228             GAP_TASK_WRITE_SCAN_ENABLE |
4229             GAP_TASK_WRITE_PAGE_TIMEOUT;
4230 #endif
4231 
4232 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4233     hci_stack->classic_read_local_oob_data = false;
4234     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4235 #endif
4236 
4237     // LE
4238 #ifdef ENABLE_BLE
4239     memset(hci_stack->le_random_address, 0, 6);
4240     hci_stack->le_random_address_set = 0;
4241 #endif
4242 #ifdef ENABLE_LE_CENTRAL
4243     hci_stack->le_scanning_active  = false;
4244     hci_stack->le_scanning_param_update = true;
4245     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4246     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4247     hci_stack->le_whitelist_capacity = 0;
4248 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4249     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
4250 #endif
4251 #endif
4252 #ifdef ENABLE_LE_PERIPHERAL
4253     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4254     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4255         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4256     }
4257     if (hci_stack->le_advertisements_data != NULL){
4258         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4259     }
4260 #endif
4261 }
4262 
4263 #ifdef ENABLE_CLASSIC
4264 /**
4265  * @brief Configure Bluetooth hardware control. Has to be called before power on.
4266  */
4267 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
4268     // store and open remote device db
4269     hci_stack->link_key_db = link_key_db;
4270     if (hci_stack->link_key_db) {
4271         hci_stack->link_key_db->open();
4272     }
4273 }
4274 #endif
4275 
4276 void hci_init(const hci_transport_t *transport, const void *config){
4277 
4278 #ifdef HAVE_MALLOC
4279     if (!hci_stack) {
4280         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
4281     }
4282 #else
4283     hci_stack = &hci_stack_static;
4284 #endif
4285     memset(hci_stack, 0, sizeof(hci_stack_t));
4286 
4287     // reference to use transport layer implementation
4288     hci_stack->hci_transport = transport;
4289 
4290     // reference to used config
4291     hci_stack->config = config;
4292 
4293     // setup pointer for outgoing packet buffer
4294     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
4295 
4296     // max acl payload size defined in config.h
4297     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4298 
4299     // register packet handlers with transport
4300     transport->register_packet_handler(&packet_handler);
4301 
4302     hci_stack->state = HCI_STATE_OFF;
4303 
4304     // class of device
4305     hci_stack->class_of_device = 0x007a020c; // Smartphone
4306 
4307     // bondable by default
4308     hci_stack->bondable = 1;
4309 
4310 #ifdef ENABLE_CLASSIC
4311     // classic name
4312     hci_stack->local_name = default_classic_name;
4313 
4314     // Master slave policy
4315     hci_stack->master_slave_policy = 1;
4316 
4317     // Allow Role Switch
4318     hci_stack->allow_role_switch = 1;
4319 
4320     // Default / minimum security level = 2
4321     hci_stack->gap_security_level = LEVEL_2;
4322 
4323     // Default Security Mode 4
4324     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
4325 
4326     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4327     hci_stack->gap_required_encyrption_key_size = 7;
4328 
4329     // Link Supervision Timeout
4330     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4331 
4332 #endif
4333 
4334     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
4335     hci_stack->ssp_enable = 1;
4336     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
4337     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4338     hci_stack->ssp_auto_accept = 1;
4339 
4340     // Secure Connections: enable (requires support from Controller)
4341     hci_stack->secure_connections_enable = true;
4342 
4343     // voice setting - signed 16 bit pcm data with CVSD over the air
4344     hci_stack->sco_voice_setting = 0x60;
4345 
4346 #ifdef ENABLE_LE_CENTRAL
4347     // connection parameter to use for outgoing connections
4348     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
4349     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
4350     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
4351     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
4352     hci_stack->le_connection_latency      = 4;         // 4
4353     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
4354     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
4355     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
4356 
4357     // default LE Scanning
4358     hci_stack->le_scan_type     =   0x1; // active
4359     hci_stack->le_scan_interval = 0x1e0; // 300 ms
4360     hci_stack->le_scan_window   =  0x30; //  30 ms
4361 #endif
4362 
4363 #ifdef ENABLE_LE_PERIPHERAL
4364     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4365 #endif
4366 
4367     // connection parameter range used to answer connection parameter update requests in l2cap
4368     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4369     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4370     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4371     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4372     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4373     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4374 
4375     hci_state_reset();
4376 }
4377 
4378 void hci_deinit(void){
4379     btstack_run_loop_remove_timer(&hci_stack->timeout);
4380 #ifdef HAVE_MALLOC
4381     if (hci_stack) {
4382         free(hci_stack);
4383     }
4384 #endif
4385     hci_stack = NULL;
4386 
4387 #ifdef ENABLE_CLASSIC
4388     disable_l2cap_timeouts = 0;
4389 #endif
4390 }
4391 
4392 /**
4393  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
4394  */
4395 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
4396     hci_stack->chipset = chipset_driver;
4397 
4398     // reset chipset driver - init is also called on power_up
4399     if (hci_stack->chipset && hci_stack->chipset->init){
4400         hci_stack->chipset->init(hci_stack->config);
4401     }
4402 }
4403 
4404 /**
4405  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
4406  */
4407 void hci_set_control(const btstack_control_t *hardware_control){
4408     // references to used control implementation
4409     hci_stack->control = hardware_control;
4410     // init with transport config
4411     hardware_control->init(hci_stack->config);
4412 }
4413 
4414 static void hci_discard_connections(void){
4415     btstack_linked_list_iterator_t it;
4416     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4417     while (btstack_linked_list_iterator_has_next(&it)){
4418         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
4419         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4420         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
4421         hci_shutdown_connection(connection);
4422     }
4423 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4424     while (hci_stack->iso_streams != NULL){
4425         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
4426     }
4427 #endif
4428 }
4429 
4430 void hci_close(void){
4431 
4432 #ifdef ENABLE_CLASSIC
4433     // close remote device db
4434     if (hci_stack->link_key_db) {
4435         hci_stack->link_key_db->close();
4436     }
4437 #endif
4438 
4439     hci_discard_connections();
4440 
4441     hci_power_control(HCI_POWER_OFF);
4442 
4443 #ifdef HAVE_MALLOC
4444     free(hci_stack);
4445 #endif
4446     hci_stack = NULL;
4447 }
4448 
4449 #ifdef HAVE_SCO_TRANSPORT
4450 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
4451     hci_stack->sco_transport = sco_transport;
4452     sco_transport->register_packet_handler(&packet_handler);
4453 }
4454 #endif
4455 
4456 #ifdef ENABLE_CLASSIC
4457 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
4458     // validate ranage and set
4459     if (encryption_key_size < 7)  return;
4460     if (encryption_key_size > 16) return;
4461     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
4462 }
4463 
4464 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
4465     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
4466         hci_stack->gap_security_mode = security_mode;
4467         return ERROR_CODE_SUCCESS;
4468     } else {
4469         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
4470     }
4471 }
4472 
4473 gap_security_mode_t gap_get_security_mode(void){
4474     return hci_stack->gap_security_mode;
4475 }
4476 
4477 void gap_set_security_level(gap_security_level_t security_level){
4478     hci_stack->gap_security_level = security_level;
4479 }
4480 
4481 gap_security_level_t gap_get_security_level(void){
4482     if (hci_stack->gap_secure_connections_only_mode){
4483         return LEVEL_4;
4484     }
4485     return hci_stack->gap_security_level;
4486 }
4487 
4488 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
4489     hci_stack->gap_minimal_service_security_level = security_level;
4490 }
4491 
4492 void gap_set_secure_connections_only_mode(bool enable){
4493     hci_stack->gap_secure_connections_only_mode = enable;
4494 }
4495 
4496 bool gap_get_secure_connections_only_mode(void){
4497     return hci_stack->gap_secure_connections_only_mode;
4498 }
4499 #endif
4500 
4501 #ifdef ENABLE_CLASSIC
4502 void gap_set_class_of_device(uint32_t class_of_device){
4503     hci_stack->class_of_device = class_of_device;
4504     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
4505     hci_run();
4506 }
4507 
4508 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4509     hci_stack->default_link_policy_settings = default_link_policy_settings;
4510     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
4511     hci_run();
4512 }
4513 
4514 void gap_set_allow_role_switch(bool allow_role_switch){
4515     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4516 }
4517 
4518 uint8_t hci_get_allow_role_switch(void){
4519     return  hci_stack->allow_role_switch;
4520 }
4521 
4522 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
4523     hci_stack->link_supervision_timeout = link_supervision_timeout;
4524 }
4525 
4526 void gap_enable_link_watchdog(uint16_t timeout_ms){
4527     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
4528 }
4529 
4530 uint16_t hci_automatic_flush_timeout(void){
4531     return hci_stack->automatic_flush_timeout;
4532 }
4533 
4534 void hci_disable_l2cap_timeout_check(void){
4535     disable_l2cap_timeouts = 1;
4536 }
4537 #endif
4538 
4539 #ifndef HAVE_HOST_CONTROLLER_API
4540 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4541 void hci_set_bd_addr(bd_addr_t addr){
4542     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4543     hci_stack->custom_bd_addr_set = 1;
4544 }
4545 #endif
4546 
4547 // State-Module-Driver overview
4548 // state                    module  low-level
4549 // HCI_STATE_OFF             off      close
4550 // HCI_STATE_INITIALIZING,   on       open
4551 // HCI_STATE_WORKING,        on       open
4552 // HCI_STATE_HALTING,        on       open
4553 // HCI_STATE_SLEEPING,    off/sleep   close
4554 // HCI_STATE_FALLING_ASLEEP  on       open
4555 
4556 static int hci_power_control_on(void){
4557 
4558     // power on
4559     int err = 0;
4560     if (hci_stack->control && hci_stack->control->on){
4561         err = (*hci_stack->control->on)();
4562     }
4563     if (err){
4564         log_error( "POWER_ON failed");
4565         hci_emit_hci_open_failed();
4566         return err;
4567     }
4568 
4569     // int chipset driver
4570     if (hci_stack->chipset && hci_stack->chipset->init){
4571         hci_stack->chipset->init(hci_stack->config);
4572     }
4573 
4574     // init transport
4575     if (hci_stack->hci_transport->init){
4576         hci_stack->hci_transport->init(hci_stack->config);
4577     }
4578 
4579     // open transport
4580     err = hci_stack->hci_transport->open();
4581     if (err){
4582         log_error( "HCI_INIT failed, turning Bluetooth off again");
4583         if (hci_stack->control && hci_stack->control->off){
4584             (*hci_stack->control->off)();
4585         }
4586         hci_emit_hci_open_failed();
4587         return err;
4588     }
4589     return 0;
4590 }
4591 
4592 static void hci_power_control_off(void){
4593 
4594     log_info("hci_power_control_off");
4595 
4596     // close low-level device
4597     hci_stack->hci_transport->close();
4598 
4599     log_info("hci_power_control_off - hci_transport closed");
4600 
4601     // power off
4602     if (hci_stack->control && hci_stack->control->off){
4603         (*hci_stack->control->off)();
4604     }
4605 
4606     log_info("hci_power_control_off - control closed");
4607 
4608     hci_stack->state = HCI_STATE_OFF;
4609 }
4610 
4611 static void hci_power_control_sleep(void){
4612 
4613     log_info("hci_power_control_sleep");
4614 
4615 #if 0
4616     // don't close serial port during sleep
4617 
4618     // close low-level device
4619     hci_stack->hci_transport->close(hci_stack->config);
4620 #endif
4621 
4622     // sleep mode
4623     if (hci_stack->control && hci_stack->control->sleep){
4624         (*hci_stack->control->sleep)();
4625     }
4626 
4627     hci_stack->state = HCI_STATE_SLEEPING;
4628 }
4629 
4630 static int hci_power_control_wake(void){
4631 
4632     log_info("hci_power_control_wake");
4633 
4634     // wake on
4635     if (hci_stack->control && hci_stack->control->wake){
4636         (*hci_stack->control->wake)();
4637     }
4638 
4639 #if 0
4640     // open low-level device
4641     int err = hci_stack->hci_transport->open(hci_stack->config);
4642     if (err){
4643         log_error( "HCI_INIT failed, turning Bluetooth off again");
4644         if (hci_stack->control && hci_stack->control->off){
4645             (*hci_stack->control->off)();
4646         }
4647         hci_emit_hci_open_failed();
4648         return err;
4649     }
4650 #endif
4651 
4652     return 0;
4653 }
4654 
4655 static void hci_power_enter_initializing_state(void){
4656     // set up state machine
4657     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
4658     hci_stack->hci_packet_buffer_reserved = false;
4659     hci_stack->state = HCI_STATE_INITIALIZING;
4660     hci_stack->substate = HCI_INIT_SEND_RESET;
4661 }
4662 
4663 static void hci_power_enter_halting_state(void){
4664 #ifdef ENABLE_BLE
4665     hci_whitelist_free();
4666 #endif
4667     // see hci_run
4668     hci_stack->state = HCI_STATE_HALTING;
4669     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
4670     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
4671     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
4672     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4673     btstack_run_loop_add_timer(&hci_stack->timeout);
4674 }
4675 
4676 // returns error
4677 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
4678     int err;
4679     switch (power_mode){
4680         case HCI_POWER_ON:
4681             err = hci_power_control_on();
4682             if (err != 0) {
4683                 log_error("hci_power_control_on() error %d", err);
4684                 return err;
4685             }
4686             hci_power_enter_initializing_state();
4687             break;
4688         case HCI_POWER_OFF:
4689             // do nothing
4690             break;
4691         case HCI_POWER_SLEEP:
4692             // do nothing (with SLEEP == OFF)
4693             break;
4694         default:
4695             btstack_assert(false);
4696             break;
4697     }
4698     return ERROR_CODE_SUCCESS;
4699 }
4700 
4701 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
4702     switch (power_mode){
4703         case HCI_POWER_ON:
4704             // do nothing
4705             break;
4706         case HCI_POWER_OFF:
4707             // no connections yet, just turn it off
4708             hci_power_control_off();
4709             break;
4710         case HCI_POWER_SLEEP:
4711             // no connections yet, just turn it off
4712             hci_power_control_sleep();
4713             break;
4714         default:
4715             btstack_assert(false);
4716             break;
4717     }
4718     return ERROR_CODE_SUCCESS;
4719 }
4720 
4721 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
4722     switch (power_mode){
4723         case HCI_POWER_ON:
4724             // do nothing
4725             break;
4726         case HCI_POWER_OFF:
4727             hci_power_enter_halting_state();
4728             break;
4729         case HCI_POWER_SLEEP:
4730             // see hci_run
4731             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4732             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4733             break;
4734         default:
4735             btstack_assert(false);
4736             break;
4737     }
4738     return ERROR_CODE_SUCCESS;
4739 }
4740 
4741 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
4742     switch (power_mode){
4743         case HCI_POWER_ON:
4744             hci_power_enter_initializing_state();
4745             break;
4746         case HCI_POWER_OFF:
4747             // do nothing
4748             break;
4749         case HCI_POWER_SLEEP:
4750             // see hci_run
4751             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4752             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4753             break;
4754         default:
4755             btstack_assert(false);
4756             break;
4757     }
4758     return ERROR_CODE_SUCCESS;
4759 }
4760 
4761 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
4762     switch (power_mode){
4763         case HCI_POWER_ON:
4764             hci_power_enter_initializing_state();
4765             break;
4766         case HCI_POWER_OFF:
4767             hci_power_enter_halting_state();
4768             break;
4769         case HCI_POWER_SLEEP:
4770             // do nothing
4771             break;
4772         default:
4773             btstack_assert(false);
4774             break;
4775     }
4776     return ERROR_CODE_SUCCESS;
4777 }
4778 
4779 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
4780     int err;
4781     switch (power_mode){
4782         case HCI_POWER_ON:
4783             err = hci_power_control_wake();
4784             if (err) return err;
4785             hci_power_enter_initializing_state();
4786             break;
4787         case HCI_POWER_OFF:
4788             hci_power_enter_halting_state();
4789             break;
4790         case HCI_POWER_SLEEP:
4791             // do nothing
4792             break;
4793         default:
4794             btstack_assert(false);
4795             break;
4796     }
4797     return ERROR_CODE_SUCCESS;
4798 }
4799 
4800 int hci_power_control(HCI_POWER_MODE power_mode){
4801     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
4802     int err = 0;
4803     switch (hci_stack->state){
4804         case HCI_STATE_OFF:
4805             err = hci_power_control_state_off(power_mode);
4806             break;
4807         case HCI_STATE_INITIALIZING:
4808             err = hci_power_control_state_initializing(power_mode);
4809             break;
4810         case HCI_STATE_WORKING:
4811             err = hci_power_control_state_working(power_mode);
4812             break;
4813         case HCI_STATE_HALTING:
4814             err = hci_power_control_state_halting(power_mode);
4815             break;
4816         case HCI_STATE_FALLING_ASLEEP:
4817             err = hci_power_control_state_falling_asleep(power_mode);
4818             break;
4819         case HCI_STATE_SLEEPING:
4820             err = hci_power_control_state_sleeping(power_mode);
4821             break;
4822         default:
4823             btstack_assert(false);
4824             break;
4825     }
4826     if (err != 0){
4827         return err;
4828     }
4829 
4830     // create internal event
4831 	hci_emit_state();
4832 
4833 	// trigger next/first action
4834 	hci_run();
4835 
4836     return 0;
4837 }
4838 
4839 
4840 static void hci_halting_run(void) {
4841 
4842     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4843 
4844     hci_connection_t *connection;
4845 #ifdef ENABLE_BLE
4846 #ifdef ENABLE_LE_PERIPHERAL
4847     bool stop_advertismenets;
4848 #endif
4849 #endif
4850 
4851     switch (hci_stack->substate) {
4852         case HCI_HALTING_CLASSIC_STOP:
4853 #ifdef ENABLE_CLASSIC
4854             if (!hci_can_send_command_packet_now()) return;
4855 
4856             if (hci_stack->connectable || hci_stack->discoverable){
4857                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4858                 hci_send_cmd(&hci_write_scan_enable, 0);
4859                 return;
4860             }
4861 #endif
4862             /* fall through */
4863 
4864         case HCI_HALTING_LE_ADV_STOP:
4865             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4866 
4867 #ifdef ENABLE_BLE
4868 #ifdef ENABLE_LE_PERIPHERAL
4869             if (!hci_can_send_command_packet_now()) return;
4870 
4871             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
4872 
4873 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4874             if (hci_extended_advertising_supported()){
4875 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4876                 btstack_linked_list_iterator_t it;
4877                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4878                 // stop all periodic advertisements and check if an extended set is active
4879                 while (btstack_linked_list_iterator_has_next(&it)){
4880                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4881                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
4882                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
4883                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
4884                         return;
4885                     }
4886                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
4887                         stop_advertismenets = true;
4888                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4889                     }
4890                 }
4891 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
4892                 if (stop_advertismenets){
4893                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4894                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
4895                     return;
4896                 }
4897             }
4898             else
4899 #else
4900             {
4901                 if (stop_advertismenets) {
4902                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4903                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
4904                     return;
4905                 }
4906             }
4907 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
4908 #endif  /* ENABLE_LE_PERIPHERAL */
4909 #endif  /* ENABLE_BLE */
4910 
4911             /* fall through */
4912 
4913         case HCI_HALTING_LE_SCAN_STOP:
4914             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
4915             if (!hci_can_send_command_packet_now()) return;
4916 
4917 #ifdef ENABLE_BLE
4918 #ifdef ENABLE_LE_CENTRAL
4919             if (hci_stack->le_scanning_active){
4920                 hci_le_scan_stop();
4921                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4922                 return;
4923             }
4924 #endif
4925 #endif
4926 
4927             /* fall through */
4928 
4929         case HCI_HALTING_DISCONNECT_ALL:
4930             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4931             if (!hci_can_send_command_packet_now()) return;
4932 
4933             // close all open connections
4934             connection = (hci_connection_t *) hci_stack->connections;
4935             if (connection) {
4936                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4937 
4938                 // check state
4939                 if (connection->state == SENT_DISCONNECT) return;
4940                 connection->state = SENT_DISCONNECT;
4941 
4942                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4943 
4944                 // finally, send the disconnect command
4945                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4946                 return;
4947             }
4948 
4949 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4950             // stop BIGs and BIG Syncs
4951             if (hci_stack->le_audio_bigs != NULL){
4952                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
4953                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
4954                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
4955                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
4956                 return;
4957             }
4958             if (hci_stack->le_audio_big_syncs != NULL){
4959                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
4960                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
4961                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
4962                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
4963                 return;
4964             }
4965 #endif
4966 
4967             btstack_run_loop_remove_timer(&hci_stack->timeout);
4968 
4969             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4970             log_info("HCI_STATE_HALTING: wait 50 ms");
4971             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
4972             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
4973             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4974             btstack_run_loop_add_timer(&hci_stack->timeout);
4975             break;
4976 
4977         case HCI_HALTING_CLOSE:
4978             // close left over connections (that had not been properly closed before)
4979             hci_discard_connections();
4980 
4981             log_info("HCI_STATE_HALTING, calling off");
4982 
4983             // switch mode
4984             hci_power_control_off();
4985 
4986             log_info("HCI_STATE_HALTING, emitting state");
4987             hci_emit_state();
4988             log_info("HCI_STATE_HALTING, done");
4989             break;
4990 
4991         case HCI_HALTING_W4_CLOSE_TIMER:
4992             // keep waiting
4993 
4994             break;
4995         default:
4996             break;
4997     }
4998 };
4999 
5000 static void hci_falling_asleep_run(void){
5001     hci_connection_t * connection;
5002     switch(hci_stack->substate) {
5003         case HCI_FALLING_ASLEEP_DISCONNECT:
5004             log_info("HCI_STATE_FALLING_ASLEEP");
5005             // close all open connections
5006             connection =  (hci_connection_t *) hci_stack->connections;
5007             if (connection){
5008 
5009                 // send disconnect
5010                 if (!hci_can_send_command_packet_now()) return;
5011 
5012                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5013                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5014 
5015                 // send disconnected event right away - causes higher layer connections to get closed, too.
5016                 hci_shutdown_connection(connection);
5017                 return;
5018             }
5019 
5020             if (hci_classic_supported()){
5021                 // disable page and inquiry scan
5022                 if (!hci_can_send_command_packet_now()) return;
5023 
5024                 log_info("HCI_STATE_HALTING, disabling inq scans");
5025                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5026 
5027                 // continue in next sub state
5028                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5029                 break;
5030             }
5031 
5032             /* fall through */
5033 
5034             case HCI_FALLING_ASLEEP_COMPLETE:
5035                 log_info("HCI_STATE_HALTING, calling sleep");
5036                 // switch mode
5037                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5038                 hci_emit_state();
5039                 break;
5040 
5041                 default:
5042                     break;
5043     }
5044 }
5045 
5046 #ifdef ENABLE_CLASSIC
5047 
5048 static void hci_update_scan_enable(void){
5049     // 2 = page scan, 1 = inq scan
5050     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5051     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5052     hci_run();
5053 }
5054 
5055 void gap_discoverable_control(uint8_t enable){
5056     if (enable) enable = 1; // normalize argument
5057 
5058     if (hci_stack->discoverable == enable){
5059         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5060         return;
5061     }
5062 
5063     hci_stack->discoverable = enable;
5064     hci_update_scan_enable();
5065 }
5066 
5067 void gap_connectable_control(uint8_t enable){
5068     if (enable) enable = 1; // normalize argument
5069 
5070     // don't emit event
5071     if (hci_stack->connectable == enable) return;
5072 
5073     hci_stack->connectable = enable;
5074     hci_update_scan_enable();
5075 }
5076 #endif
5077 
5078 void gap_local_bd_addr(bd_addr_t address_buffer){
5079     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5080 }
5081 
5082 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5083 static void hci_host_num_completed_packets(void){
5084 
5085     // create packet manually as arrays are not supported and num_commands should not get reduced
5086     hci_reserve_packet_buffer();
5087     uint8_t * packet = hci_get_outgoing_packet_buffer();
5088 
5089     uint16_t size = 0;
5090     uint16_t num_handles = 0;
5091     packet[size++] = 0x35;
5092     packet[size++] = 0x0c;
5093     size++;  // skip param len
5094     size++;  // skip num handles
5095 
5096     // add { handle, packets } entries
5097     btstack_linked_item_t * it;
5098     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5099         hci_connection_t * connection = (hci_connection_t *) it;
5100         if (connection->num_packets_completed){
5101             little_endian_store_16(packet, size, connection->con_handle);
5102             size += 2;
5103             little_endian_store_16(packet, size, connection->num_packets_completed);
5104             size += 2;
5105             //
5106             num_handles++;
5107             connection->num_packets_completed = 0;
5108         }
5109     }
5110 
5111     packet[2] = size - 3;
5112     packet[3] = num_handles;
5113 
5114     hci_stack->host_completed_packets = 0;
5115 
5116     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5117     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5118 
5119     // release packet buffer for synchronous transport implementations
5120     if (hci_transport_synchronous()){
5121         hci_release_packet_buffer();
5122         hci_emit_transport_packet_sent();
5123     }
5124 }
5125 #endif
5126 
5127 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5128     UNUSED(ds);
5129     hci_stack->substate = HCI_HALTING_CLOSE;
5130     // allow packet handlers to defer final shutdown
5131     hci_emit_state();
5132     hci_run();
5133 }
5134 
5135 static bool hci_run_acl_fragments(void){
5136     if (hci_stack->acl_fragmentation_total_size > 0u) {
5137         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5138         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5139         if (connection) {
5140             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5141                 hci_send_acl_packet_fragments(connection);
5142                 return true;
5143             }
5144         } else {
5145             // connection gone -> discard further fragments
5146             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5147             hci_stack->acl_fragmentation_total_size = 0;
5148             hci_stack->acl_fragmentation_pos = 0;
5149         }
5150     }
5151     return false;
5152 }
5153 
5154 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5155 static bool hci_run_iso_fragments(void){
5156     if (hci_stack->iso_fragmentation_total_size > 0u) {
5157         // TODO: flow control
5158         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5159             hci_send_iso_packet_fragments();
5160             return true;
5161         }
5162     }
5163     return false;
5164 }
5165 #endif
5166 
5167 #ifdef ENABLE_CLASSIC
5168 
5169 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5170 static bool hci_classic_operation_active(void) {
5171     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5172         return true;
5173     }
5174     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5175         return true;
5176     }
5177     btstack_linked_item_t * it;
5178     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5179         hci_connection_t *connection = (hci_connection_t *) it;
5180         switch (connection->state) {
5181             case SENT_CREATE_CONNECTION:
5182             case SENT_CANCEL_CONNECTION:
5183             case SENT_DISCONNECT:
5184                 return true;
5185             default:
5186                 break;
5187         }
5188     }
5189     return false;
5190 }
5191 #endif
5192 
5193 static bool hci_run_general_gap_classic(void){
5194 
5195     // assert stack is working and classic is active
5196     if (hci_classic_supported() == false)      return false;
5197     if (hci_stack->state != HCI_STATE_WORKING) return false;
5198 
5199     // decline incoming connections
5200     if (hci_stack->decline_reason){
5201         uint8_t reason = hci_stack->decline_reason;
5202         hci_stack->decline_reason = 0;
5203         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5204         return true;
5205     }
5206 
5207     if (hci_stack->gap_tasks_classic != 0){
5208         hci_run_gap_tasks_classic();
5209         return true;
5210     }
5211 
5212     // start/stop inquiry
5213     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5214 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5215         if (hci_classic_operation_active() == false)
5216 #endif
5217         {
5218             uint8_t duration = hci_stack->inquiry_state;
5219             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5220             if (hci_stack->inquiry_max_period_length != 0){
5221                 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);
5222             } else {
5223                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5224             }
5225             return true;
5226         }
5227     }
5228     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5229         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5230         hci_send_cmd(&hci_inquiry_cancel);
5231         return true;
5232     }
5233 
5234     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5235         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5236         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5237         return true;
5238     }
5239 
5240     // remote name request
5241     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5242 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5243         if (hci_classic_operation_active() == false)
5244 #endif
5245         {
5246             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5247             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5248                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5249             return true;
5250         }
5251     }
5252 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5253     // Local OOB data
5254     if (hci_stack->classic_read_local_oob_data){
5255         hci_stack->classic_read_local_oob_data = false;
5256         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5257             hci_send_cmd(&hci_read_local_extended_oob_data);
5258         } else {
5259             hci_send_cmd(&hci_read_local_oob_data);
5260         }
5261     }
5262 #endif
5263     // pairing
5264     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5265         uint8_t state = hci_stack->gap_pairing_state;
5266         uint8_t pin_code[16];
5267         switch (state){
5268             case GAP_PAIRING_STATE_SEND_PIN:
5269                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5270                 memset(pin_code, 0, 16);
5271                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5272                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5273                 break;
5274             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5275                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5276                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5277                 break;
5278             case GAP_PAIRING_STATE_SEND_PASSKEY:
5279                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5280                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5281                 break;
5282             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5283                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5284                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5285                 break;
5286             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5287                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5288                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5289                 break;
5290             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5291                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5292                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5293                 break;
5294             default:
5295                 break;
5296         }
5297         return true;
5298     }
5299     return false;
5300 }
5301 #endif
5302 
5303 #ifdef ENABLE_BLE
5304 
5305 #ifdef ENABLE_LE_CENTRAL
5306 static void hci_le_scan_stop(void){
5307 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5308     if (hci_extended_advertising_supported()) {
5309             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5310         } else
5311 #endif
5312     {
5313         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5314     }
5315 }
5316 #endif
5317 
5318 #ifdef ENABLE_LE_PERIPHERAL
5319 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5320 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
5321     uint8_t  operation = 0;
5322     if (pos == 0){
5323         // first fragment or complete data
5324         operation |= 1;
5325     }
5326     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
5327         // last fragment or complete data
5328         operation |= 2;
5329     }
5330     return operation;
5331 }
5332 #endif
5333 #endif
5334 
5335 static bool hci_run_general_gap_le(void){
5336 
5337     btstack_linked_list_iterator_t lit;
5338 
5339     // Phase 1: collect what to stop
5340 
5341 #ifdef ENABLE_LE_CENTRAL
5342     bool scanning_stop = false;
5343     bool connecting_stop = false;
5344 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5345 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5346     bool periodic_sync_stop = false;
5347 #endif
5348 #endif
5349 #endif
5350 
5351 #ifdef ENABLE_LE_PERIPHERAL
5352     bool advertising_stop = false;
5353 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5354     le_advertising_set_t * advertising_stop_set = NULL;
5355 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5356     bool periodic_advertising_stop = false;
5357 #endif
5358 #endif
5359 #endif
5360 
5361     // check if own address changes
5362     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5363 
5364     // check if whitelist needs modification
5365     bool whitelist_modification_pending = false;
5366     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5367     while (btstack_linked_list_iterator_has_next(&lit)){
5368         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5369         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
5370             whitelist_modification_pending = true;
5371             break;
5372         }
5373     }
5374 
5375     // check if resolving list needs modification
5376     bool resolving_list_modification_pending = false;
5377 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5378     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
5379 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
5380         resolving_list_modification_pending = true;
5381     }
5382 #endif
5383 
5384 #ifdef ENABLE_LE_CENTRAL
5385 
5386 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5387     // check if periodic advertiser list needs modification
5388     bool periodic_list_modification_pending = false;
5389     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5390     while (btstack_linked_list_iterator_has_next(&lit)){
5391         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5392         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
5393             periodic_list_modification_pending = true;
5394             break;
5395         }
5396     }
5397 #endif
5398 
5399     // scanning control
5400     if (hci_stack->le_scanning_active) {
5401         // stop if:
5402         // - parameter change required
5403         // - it's disabled
5404         // - whitelist change required but used for scanning
5405         // - resolving list modified
5406         // - own address changes
5407         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
5408         if ((hci_stack->le_scanning_param_update) ||
5409             !hci_stack->le_scanning_enabled ||
5410             (scanning_uses_whitelist && whitelist_modification_pending) ||
5411             resolving_list_modification_pending ||
5412             random_address_change){
5413 
5414             scanning_stop = true;
5415         }
5416     }
5417 
5418     // connecting control
5419     bool connecting_with_whitelist;
5420     switch (hci_stack->le_connecting_state){
5421         case LE_CONNECTING_DIRECT:
5422         case LE_CONNECTING_WHITELIST:
5423             // stop connecting if:
5424             // - connecting uses white and whitelist modification pending
5425             // - if it got disabled
5426             // - resolving list modified
5427             // - own address changes
5428             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
5429             if ((connecting_with_whitelist && whitelist_modification_pending) ||
5430                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
5431                 resolving_list_modification_pending ||
5432                 random_address_change) {
5433 
5434                 connecting_stop = true;
5435             }
5436             break;
5437         default:
5438             break;
5439     }
5440 
5441 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5442 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5443     // periodic sync control
5444     bool sync_with_advertiser_list;
5445     switch(hci_stack->le_periodic_sync_state){
5446         case LE_CONNECTING_DIRECT:
5447         case LE_CONNECTING_WHITELIST:
5448             // stop sync if:
5449             // - sync with advertiser list and advertiser list modification pending
5450             // - if it got disabled
5451             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
5452             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
5453                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
5454                 periodic_sync_stop = true;
5455             }
5456             break;
5457         default:
5458             break;
5459     }
5460 #endif
5461 #endif
5462 
5463 #endif /* ENABLE_LE_CENTRAL */
5464 
5465 #ifdef ENABLE_LE_PERIPHERAL
5466     // le advertisement control
5467     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
5468         // stop if:
5469         // - parameter change required
5470         // - random address used in advertising and changes
5471         // - it's disabled
5472         // - whitelist change required but used for advertisement filter policy
5473         // - resolving list modified
5474         // - own address changes
5475         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
5476         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
5477         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
5478         if (advertising_change ||
5479             (advertising_uses_random_address && random_address_change) ||
5480             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
5481             (advertising_uses_whitelist && whitelist_modification_pending) ||
5482             resolving_list_modification_pending ||
5483             random_address_change) {
5484 
5485             advertising_stop = true;
5486         }
5487     }
5488 
5489 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5490     if (hci_extended_advertising_supported() && (advertising_stop == false)){
5491         btstack_linked_list_iterator_t it;
5492         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5493         while (btstack_linked_list_iterator_has_next(&it)){
5494             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5495             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5496                 // stop if:
5497                 // - parameter change required
5498                 // - random address used in connectable advertising and changes
5499                 // - it's disabled
5500                 // - whitelist change required but used for advertisement filter policy
5501                 // - resolving list modified
5502                 // - own address changes
5503                 // - advertisement set will be removed
5504                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
5505                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
5506                 bool advertising_uses_random_address =
5507                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
5508                         advertising_connectable;
5509                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
5510                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
5511                 bool advertising_set_random_address_change =
5512                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5513                 bool advertising_set_will_be_removed =
5514                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
5515                 if (advertising_parameter_change ||
5516                     (advertising_uses_random_address && advertising_set_random_address_change) ||
5517                     (advertising_enabled == false) ||
5518                     (advertising_uses_whitelist && whitelist_modification_pending) ||
5519                     resolving_list_modification_pending ||
5520                     advertising_set_will_be_removed) {
5521 
5522                     advertising_stop = true;
5523                     advertising_stop_set = advertising_set;
5524                     break;
5525                 }
5526             }
5527 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5528             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5529                 // stop if:
5530                 // - it's disabled
5531                 // - parameter change required
5532                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
5533                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
5534                 if ((periodic_enabled == false) || periodic_parameter_change){
5535                     periodic_advertising_stop = true;
5536                     advertising_stop_set = advertising_set;
5537                 }
5538             }
5539 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5540         }
5541     }
5542 #endif
5543 
5544 #endif
5545 
5546 
5547     // Phase 2: stop everything that should be off during modifications
5548 
5549 
5550     // 2.1 Outgoing connection
5551 #ifdef ENABLE_LE_CENTRAL
5552     if (connecting_stop){
5553         hci_send_cmd(&hci_le_create_connection_cancel);
5554         return true;
5555     }
5556 #endif
5557 
5558     // 2.2 Scanning
5559 #ifdef ENABLE_LE_CENTRAL
5560     if (scanning_stop){
5561         hci_stack->le_scanning_active = false;
5562         hci_le_scan_stop();
5563         return true;
5564     }
5565 
5566     // 2.3 Periodic Sync
5567 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5568     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
5569         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
5570         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
5571         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
5572         return true;
5573     }
5574 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5575     if (periodic_sync_stop){
5576         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
5577         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
5578         return true;
5579     }
5580 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5581 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5582 #endif /* ENABLE_LE_CENTRAL */
5583 
5584     // 2.4 Advertising: legacy, extended, periodic
5585 #ifdef ENABLE_LE_PERIPHERAL
5586     if (advertising_stop){
5587 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5588         if (hci_extended_advertising_supported()) {
5589             uint8_t advertising_stop_handle;
5590             if (advertising_stop_set != NULL){
5591                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5592                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5593             } else {
5594                 advertising_stop_handle = 0;
5595                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5596             }
5597             const uint8_t advertising_handles[] = { advertising_stop_handle };
5598             const uint16_t durations[] = { 0 };
5599             const uint16_t max_events[] = { 0 };
5600             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5601         } else
5602 #endif
5603         {
5604             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5605             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5606         }
5607         return true;
5608     }
5609 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5610 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5611     if (periodic_advertising_stop){
5612         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5613         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
5614         return true;
5615     }
5616 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5617 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5618 #endif /* ENABLE_LE_PERIPHERAL */
5619 
5620 
5621     // Phase 3: modify
5622 
5623     if (random_address_change){
5624         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5625 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5626         if (hci_extended_advertising_supported()) {
5627             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5628         }
5629 #endif
5630         {
5631             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5632         }
5633         return true;
5634     }
5635 
5636 #ifdef ENABLE_LE_CENTRAL
5637     if (hci_stack->le_scanning_param_update){
5638         hci_stack->le_scanning_param_update = false;
5639 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5640         if (hci_extended_advertising_supported()){
5641             // prepare arrays for all PHYs
5642             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
5643             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
5644             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
5645             uint8_t  scanning_phys     = 1;  // LE 1M PHY
5646             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
5647                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
5648         } else
5649 #endif
5650         {
5651             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5652                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
5653         }
5654         return true;
5655     }
5656 #endif
5657 
5658 #ifdef ENABLE_LE_PERIPHERAL
5659     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
5660         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5661         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5662 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5663         if (hci_extended_advertising_supported()){
5664             // map advertisment type to advertising event properties
5665             uint16_t adv_event_properties = 0;
5666             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5667             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5668                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5669             }
5670             hci_stack->le_advertising_set_in_current_command = 0;
5671             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5672                          0,
5673                          adv_event_properties,
5674                          hci_stack->le_advertisements_interval_min,
5675                          hci_stack->le_advertisements_interval_max,
5676                          hci_stack->le_advertisements_channel_map,
5677                          hci_stack->le_advertisements_own_addr_type,
5678                          hci_stack->le_advertisements_direct_address_type,
5679                          hci_stack->le_advertisements_direct_address,
5680                          hci_stack->le_advertisements_filter_policy,
5681                          0x7f,  // tx power: no preference
5682                          0x01,  // primary adv phy: LE 1M
5683                          0,     // secondary adv max skip
5684                          0,     // secondary adv phy
5685                          0,     // adv sid
5686                          0      // scan request notification
5687                          );
5688         }
5689 #endif
5690         {
5691             hci_send_cmd(&hci_le_set_advertising_parameters,
5692                          hci_stack->le_advertisements_interval_min,
5693                          hci_stack->le_advertisements_interval_max,
5694                          hci_stack->le_advertisements_type,
5695                          hci_stack->le_advertisements_own_addr_type,
5696                          hci_stack->le_advertisements_direct_address_type,
5697                          hci_stack->le_advertisements_direct_address,
5698                          hci_stack->le_advertisements_channel_map,
5699                          hci_stack->le_advertisements_filter_policy);
5700         }
5701         return true;
5702     }
5703 
5704     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
5705         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5706         uint8_t adv_data_clean[31];
5707         memset(adv_data_clean, 0, sizeof(adv_data_clean));
5708         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
5709                      hci_stack->le_advertisements_data_len);
5710         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
5711 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5712         if (hci_extended_advertising_supported()){
5713             hci_stack->le_advertising_set_in_current_command = 0;
5714             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
5715         } else
5716 #endif
5717         {
5718             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
5719         }
5720         return true;
5721     }
5722 
5723     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
5724         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5725         uint8_t scan_data_clean[31];
5726         memset(scan_data_clean, 0, sizeof(scan_data_clean));
5727         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
5728                      hci_stack->le_scan_response_data_len);
5729         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
5730 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5731         if (hci_extended_advertising_supported()){
5732             hci_stack->le_advertising_set_in_current_command = 0;
5733             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
5734         } else
5735 #endif
5736         {
5737             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
5738         }
5739         return true;
5740     }
5741 
5742 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5743     if (hci_extended_advertising_supported()) {
5744         btstack_linked_list_iterator_t it;
5745         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5746         while (btstack_linked_list_iterator_has_next(&it)){
5747             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5748             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
5749                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
5750                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5751                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
5752                 return true;
5753             }
5754             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
5755                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5756                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
5757                 return true;
5758             }
5759             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
5760                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5761                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5762                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5763                              advertising_set->advertising_handle,
5764                              advertising_set->extended_params.advertising_event_properties,
5765                              advertising_set->extended_params.primary_advertising_interval_min,
5766                              advertising_set->extended_params.primary_advertising_interval_max,
5767                              advertising_set->extended_params.primary_advertising_channel_map,
5768                              advertising_set->extended_params.own_address_type,
5769                              advertising_set->extended_params.peer_address_type,
5770                              advertising_set->extended_params.peer_address,
5771                              advertising_set->extended_params.advertising_filter_policy,
5772                              advertising_set->extended_params.advertising_tx_power,
5773                              advertising_set->extended_params.primary_advertising_phy,
5774                              advertising_set->extended_params.secondary_advertising_max_skip,
5775                              advertising_set->extended_params.secondary_advertising_phy,
5776                              advertising_set->extended_params.advertising_sid,
5777                              advertising_set->extended_params.scan_request_notification_enable
5778                 );
5779                 return true;
5780             }
5781             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
5782                 uint16_t pos = advertising_set->adv_data_pos;
5783                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
5784                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5785                 if ((operation & 0x02) != 0){
5786                     // last fragment or complete data
5787                     operation |= 2;
5788                     advertising_set->adv_data_pos = 0;
5789                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5790                 } else {
5791                     advertising_set->adv_data_pos += data_to_upload;
5792                 }
5793                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5794                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
5795                 return true;
5796             }
5797             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
5798                 uint16_t pos = advertising_set->scan_data_pos;
5799                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
5800                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5801                 if ((operation & 0x02) != 0){
5802                     advertising_set->scan_data_pos = 0;
5803                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5804                 } else {
5805                     advertising_set->scan_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_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
5809                 return true;
5810             }
5811 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5812             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
5813                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
5814                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5815                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
5816                              advertising_set->advertising_handle,
5817                              advertising_set->periodic_params.periodic_advertising_interval_min,
5818                              advertising_set->periodic_params.periodic_advertising_interval_max,
5819                              advertising_set->periodic_params.periodic_advertising_properties);
5820                 return true;
5821             }
5822             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
5823                 uint16_t pos = advertising_set->periodic_data_pos;
5824                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
5825                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5826                 if ((operation & 0x02) != 0){
5827                     // last fragment or complete data
5828                     operation |= 2;
5829                     advertising_set->periodic_data_pos = 0;
5830                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
5831                 } else {
5832                     advertising_set->periodic_data_pos += data_to_upload;
5833                 }
5834                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5835                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
5836                 return true;
5837             }
5838 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5839         }
5840     }
5841 #endif
5842 
5843 #endif
5844 
5845 #ifdef ENABLE_LE_CENTRAL
5846     // if connect with whitelist was active and is not cancelled yet, wait until next time
5847     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
5848 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5849     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
5850     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
5851 #endif
5852 #endif
5853 
5854     // LE Whitelist Management
5855     if (whitelist_modification_pending){
5856         // add/remove entries
5857         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5858         while (btstack_linked_list_iterator_has_next(&lit)){
5859             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5860 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5861 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5862 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
5863 				return true;
5864 			}
5865             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
5866 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
5867                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
5868                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
5869                 return true;
5870             }
5871             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
5872 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5873 				btstack_memory_whitelist_entry_free(entry);
5874             }
5875         }
5876     }
5877 
5878 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5879     // LE Resolving List Management
5880     if (resolving_list_supported) {
5881 		uint16_t i;
5882 		switch (hci_stack->le_resolving_list_state) {
5883 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
5884 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
5885 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
5886 				return true;
5887 			case LE_RESOLVING_LIST_READ_SIZE:
5888 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
5889 				hci_send_cmd(&hci_le_read_resolving_list_size);
5890 				return true;
5891 			case LE_RESOLVING_LIST_SEND_CLEAR:
5892 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
5893 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
5894 							  sizeof(hci_stack->le_resolving_list_add_entries));
5895 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
5896 							  sizeof(hci_stack->le_resolving_list_remove_entries));
5897 				hci_send_cmd(&hci_le_clear_resolving_list);
5898 				return true;
5899 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
5900 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5901 					uint8_t offset = i >> 3;
5902 					uint8_t mask = 1 << (i & 7);
5903 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
5904 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
5905 					bd_addr_t peer_identity_addreses;
5906 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5907 					sm_key_t peer_irk;
5908 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5909 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5910 
5911 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
5912 					// trigger whitelist entry 'update' (work around for controller bug)
5913 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5914 					while (btstack_linked_list_iterator_has_next(&lit)) {
5915 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
5916 						if (entry->address_type != peer_identity_addr_type) continue;
5917 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
5918 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
5919 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
5920 					}
5921 #endif
5922 
5923 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
5924 								 peer_identity_addreses);
5925 					return true;
5926 				}
5927 
5928 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
5929 
5930 				/* fall through */
5931 
5932 			case LE_RESOLVING_LIST_ADD_ENTRIES:
5933 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5934 					uint8_t offset = i >> 3;
5935 					uint8_t mask = 1 << (i & 7);
5936 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
5937 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
5938 					bd_addr_t peer_identity_addreses;
5939 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5940 					sm_key_t peer_irk;
5941 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5942 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5943 					const uint8_t *local_irk = gap_get_persistent_irk();
5944 					// command uses format specifier 'P' that stores 16-byte value without flip
5945 					uint8_t local_irk_flipped[16];
5946 					uint8_t peer_irk_flipped[16];
5947 					reverse_128(local_irk, local_irk_flipped);
5948 					reverse_128(peer_irk, peer_irk_flipped);
5949 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
5950 								 peer_irk_flipped, local_irk_flipped);
5951 					return true;
5952 				}
5953 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5954 				break;
5955 
5956 			default:
5957 				break;
5958 		}
5959 	}
5960     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5961 #endif
5962 
5963 #ifdef ENABLE_LE_CENTRAL
5964 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5965     // LE Whitelist Management
5966     if (periodic_list_modification_pending){
5967         // add/remove entries
5968         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5969         while (btstack_linked_list_iterator_has_next(&lit)){
5970             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5971             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
5972                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5973                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
5974                 return true;
5975             }
5976             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
5977                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5978                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
5979                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
5980                 return true;
5981             }
5982             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
5983                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
5984                 btstack_memory_periodic_advertiser_list_entry_free(entry);
5985             }
5986         }
5987     }
5988 #endif
5989 #endif
5990 
5991     // post-pone all actions until stack is fully working
5992     if (hci_stack->state != HCI_STATE_WORKING) return false;
5993 
5994     // advertisements, active scanning, and creating connections requires random address to be set if using private address
5995     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
5996 
5997     // Phase 4: restore state
5998 
5999 #ifdef ENABLE_LE_CENTRAL
6000     // re-start scanning
6001     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6002         hci_stack->le_scanning_active = true;
6003 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6004         if (hci_extended_advertising_supported()){
6005             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0);
6006         } else
6007 #endif
6008         {
6009             hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
6010         }
6011         return true;
6012     }
6013 #endif
6014 
6015 #ifdef ENABLE_LE_CENTRAL
6016     // re-start connecting
6017     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6018         bd_addr_t null_addr;
6019         memset(null_addr, 0, 6);
6020         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6021         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6022         hci_send_cmd(&hci_le_create_connection,
6023                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
6024                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
6025                      1,         // use whitelist
6026                      0,         // peer address type
6027                      null_addr, // peer bd addr
6028                      hci_stack->le_connection_own_addr_type,   // our addr type:
6029                      hci_stack->le_connection_interval_min,    // conn interval min
6030                      hci_stack->le_connection_interval_max,    // conn interval max
6031                      hci_stack->le_connection_latency,         // conn latency
6032                      hci_stack->le_supervision_timeout,        // conn latency
6033                      hci_stack->le_minimum_ce_length,          // min ce length
6034                      hci_stack->le_maximum_ce_length           // max ce length
6035         );
6036         return true;
6037     }
6038 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6039     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6040         switch(hci_stack->le_periodic_sync_request){
6041             case LE_CONNECTING_DIRECT:
6042             case LE_CONNECTING_WHITELIST:
6043                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6044                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6045                              hci_stack->le_periodic_sync_options,
6046                              hci_stack->le_periodic_sync_advertising_sid,
6047                              hci_stack->le_periodic_sync_advertiser_address_type,
6048                              hci_stack->le_periodic_sync_advertiser_address,
6049                              hci_stack->le_periodic_sync_skip,
6050                              hci_stack->le_periodic_sync_timeout,
6051                              hci_stack->le_periodic_sync_cte_type);
6052                 return true;
6053             default:
6054                 break;
6055         }
6056     }
6057 #endif
6058 #endif
6059 
6060 #ifdef ENABLE_LE_PERIPHERAL
6061     // re-start advertising
6062     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6063         // check if advertisements should be enabled given
6064         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6065         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6066 
6067 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6068         if (hci_extended_advertising_supported()){
6069             const uint8_t advertising_handles[] = { 0 };
6070             const uint16_t durations[] = { 0 };
6071             const uint16_t max_events[] = { 0 };
6072             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6073         } else
6074 #endif
6075         {
6076             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6077         }
6078         return true;
6079     }
6080 
6081 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6082     if (hci_extended_advertising_supported()) {
6083         btstack_linked_list_iterator_t it;
6084         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6085         while (btstack_linked_list_iterator_has_next(&it)) {
6086             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6087             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6088                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6089                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6090                 const uint16_t durations[] = { advertising_set->enable_timeout };
6091                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6092                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6093                 return true;
6094             }
6095 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6096             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6097                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6098                 uint8_t enable = 1;
6099                 if (advertising_set->periodic_include_adi){
6100                     enable |= 2;
6101                 }
6102                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6103                 return true;
6104             }
6105 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6106         }
6107     }
6108 #endif
6109 #endif
6110 
6111     return false;
6112 }
6113 
6114 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6115 static bool hci_run_iso_tasks(void){
6116     btstack_linked_list_iterator_t it;
6117 
6118     // BIG
6119     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6120     while (btstack_linked_list_iterator_has_next(&it)){
6121         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6122         switch (big->state){
6123             case LE_AUDIO_BIG_STATE_CREATE:
6124                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6125                 hci_send_cmd(&hci_le_create_big,
6126                              big->params->big_handle,
6127                              big->params->advertising_handle,
6128                              big->params->num_bis,
6129                              big->params->sdu_interval_us,
6130                              big->params->max_sdu,
6131                              big->params->max_transport_latency_ms,
6132                              big->params->rtn,
6133                              big->params->phy,
6134                              big->params->packing,
6135                              big->params->framing,
6136                              big->params->encryption,
6137                              big->params->broadcast_code);
6138                 return true;
6139             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6140                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6141                 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);
6142                 return true;
6143             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6144                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6145                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6146                 break;
6147             case LE_AUDIO_BIG_STATE_TERMINATE:
6148                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6149                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6150                 return true;
6151             default:
6152                 break;
6153         }
6154     }
6155 
6156     // BIG Sync
6157     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6158     while (btstack_linked_list_iterator_has_next(&it)){
6159         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6160         switch (big_sync->state){
6161             case LE_AUDIO_BIG_STATE_CREATE:
6162                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6163                 hci_send_cmd(&hci_le_big_create_sync,
6164                              big_sync->params->big_handle,
6165                              big_sync->params->sync_handle,
6166                              big_sync->params->encryption,
6167                              big_sync->params->broadcast_code,
6168                              big_sync->params->mse,
6169                              big_sync->params->big_sync_timeout_10ms,
6170                              big_sync->params->num_bis,
6171                              big_sync->params->bis_indices);
6172                 return true;
6173             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6174                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6175                 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);
6176                 return true;
6177             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6178                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6179                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6180                 break;
6181             case LE_AUDIO_BIG_STATE_TERMINATE:
6182                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6183                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6184                 return true;
6185             default:
6186                 break;
6187         }
6188     }
6189 
6190     return false;
6191 }
6192 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6193 #endif
6194 
6195 static bool hci_run_general_pending_commands(void){
6196     btstack_linked_item_t * it;
6197     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6198         hci_connection_t * connection = (hci_connection_t *) it;
6199 
6200         switch(connection->state){
6201             case SEND_CREATE_CONNECTION:
6202                 switch(connection->address_type){
6203 #ifdef ENABLE_CLASSIC
6204                     case BD_ADDR_TYPE_ACL:
6205                         log_info("sending hci_create_connection");
6206                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
6207                         break;
6208 #endif
6209                     default:
6210 #ifdef ENABLE_BLE
6211 #ifdef ENABLE_LE_CENTRAL
6212                         log_info("sending hci_le_create_connection");
6213                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6214                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6215 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6216                         if (hci_extended_advertising_supported()) {
6217                             uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval };
6218                             uint16_t le_connection_scan_window[1]   = { hci_stack->le_connection_scan_window };
6219                             uint16_t le_connection_interval_min[1]  = { hci_stack->le_connection_interval_min };
6220                             uint16_t le_connection_interval_max[1]  = { hci_stack->le_connection_interval_max };
6221                             uint16_t le_connection_latency[1]       = { hci_stack->le_connection_latency };
6222                             uint16_t le_supervision_timeout[1]      = { hci_stack->le_supervision_timeout };
6223                             uint16_t le_minimum_ce_length[1]        = { hci_stack->le_minimum_ce_length };
6224                             uint16_t le_maximum_ce_length[1]        = { hci_stack->le_maximum_ce_length };
6225                             hci_send_cmd(&hci_le_extended_create_connection,
6226                                          0,         // don't use whitelist
6227                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6228                                          connection->address_type,      // peer address type
6229                                          connection->address,           // peer bd addr
6230                                          1,                             // initiating PHY - 1M
6231                                          le_connection_scan_interval,   // conn scan interval
6232                                          le_connection_scan_window,     // conn scan windows
6233                                          le_connection_interval_min,    // conn interval min
6234                                          le_connection_interval_max,    // conn interval max
6235                                          le_connection_latency,         // conn latency
6236                                          le_supervision_timeout,        // conn latency
6237                                          le_minimum_ce_length,          // min ce length
6238                                          le_maximum_ce_length           // max ce length
6239                             );                        }
6240                         else
6241 #endif
6242                         {
6243                             hci_send_cmd(&hci_le_create_connection,
6244                                          hci_stack->le_connection_scan_interval,    // conn scan interval
6245                                          hci_stack->le_connection_scan_window,      // conn scan windows
6246                                          0,         // don't use whitelist
6247                                          connection->address_type, // peer address type
6248                                          connection->address,      // peer bd addr
6249                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6250                                          hci_stack->le_connection_interval_min,    // conn interval min
6251                                          hci_stack->le_connection_interval_max,    // conn interval max
6252                                          hci_stack->le_connection_latency,         // conn latency
6253                                          hci_stack->le_supervision_timeout,        // conn latency
6254                                          hci_stack->le_minimum_ce_length,          // min ce length
6255                                          hci_stack->le_maximum_ce_length          // max ce length
6256                             );
6257                         }
6258                         connection->state = SENT_CREATE_CONNECTION;
6259 #endif
6260 #endif
6261                         break;
6262                 }
6263                 return true;
6264 
6265 #ifdef ENABLE_CLASSIC
6266             case RECEIVED_CONNECTION_REQUEST:
6267                 connection->role  = HCI_ROLE_SLAVE;
6268                 if (connection->address_type == BD_ADDR_TYPE_ACL){
6269                     log_info("sending hci_accept_connection_request");
6270                     connection->state = ACCEPTED_CONNECTION_REQUEST;
6271                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
6272                     return true;
6273                 }
6274                 break;
6275 #endif
6276 
6277 #ifdef ENABLE_BLE
6278 #ifdef ENABLE_LE_CENTRAL
6279             case SEND_CANCEL_CONNECTION:
6280                 connection->state = SENT_CANCEL_CONNECTION;
6281                 hci_send_cmd(&hci_le_create_connection_cancel);
6282                 return true;
6283 #endif
6284 #endif
6285             case SEND_DISCONNECT:
6286                 connection->state = SENT_DISCONNECT;
6287                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6288                 return true;
6289 
6290             default:
6291                 break;
6292         }
6293 
6294         // no further commands if connection is about to get shut down
6295         if (connection->state == SENT_DISCONNECT) continue;
6296 
6297 #ifdef ENABLE_CLASSIC
6298 
6299         // Handling link key request requires remote supported features
6300         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
6301             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
6302             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
6303 
6304             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
6305             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
6306             if (have_link_key && security_level_sufficient){
6307                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
6308             } else {
6309                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
6310             }
6311             return true;
6312         }
6313 
6314         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
6315             log_info("denying to pin request");
6316             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
6317             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
6318             return true;
6319         }
6320 
6321         // security assessment requires remote features
6322         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
6323             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
6324             hci_ssp_assess_security_on_io_cap_request(connection);
6325             // 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
6326         }
6327 
6328         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
6329             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6330             // set authentication requirements:
6331             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
6332             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
6333             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
6334             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
6335                 authreq |= 1;
6336             }
6337             bool bonding = hci_stack->bondable;
6338             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
6339                 // if we have received IO Cap Response, we're in responder role
6340                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6341                 if (bonding && !remote_bonding){
6342                     log_info("Remote not bonding, dropping local flag");
6343                     bonding = false;
6344                 }
6345             }
6346             if (bonding){
6347                 if (connection->bonding_flags & BONDING_DEDICATED){
6348                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6349                 } else {
6350                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
6351                 }
6352             }
6353             uint8_t have_oob_data = 0;
6354 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6355             if (connection->classic_oob_c_192 != NULL){
6356                     have_oob_data |= 1;
6357             }
6358             if (connection->classic_oob_c_256 != NULL){
6359                 have_oob_data |= 2;
6360             }
6361 #endif
6362             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
6363             return true;
6364         }
6365 
6366         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
6367             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6368             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
6369             return true;
6370         }
6371 
6372 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6373         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
6374             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
6375             const uint8_t zero[16] = { 0 };
6376             const uint8_t * r_192 = zero;
6377             const uint8_t * c_192 = zero;
6378             const uint8_t * r_256 = zero;
6379             const uint8_t * c_256 = zero;
6380             // verify P-256 OOB
6381             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
6382                 c_256 = connection->classic_oob_c_256;
6383                 if (connection->classic_oob_r_256 != NULL) {
6384                     r_256 = connection->classic_oob_r_256;
6385                 }
6386             }
6387             // verify P-192 OOB
6388             if ((connection->classic_oob_c_192 != NULL)) {
6389                 c_192 = connection->classic_oob_c_192;
6390                 if (connection->classic_oob_r_192 != NULL) {
6391                     r_192 = connection->classic_oob_r_192;
6392                 }
6393             }
6394 
6395             // assess security
6396             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
6397             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
6398             if (need_level_4 && !can_reach_level_4){
6399                 log_info("Level 4 required, but not possible -> abort");
6400                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
6401                 // send oob negative reply
6402                 c_256 = NULL;
6403                 c_192 = NULL;
6404             }
6405 
6406             // Reply
6407             if (c_256 != zero) {
6408                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
6409             } else if (c_192 != zero){
6410                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
6411             } else {
6412                 hci_stack->classic_oob_con_handle = connection->con_handle;
6413                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
6414             }
6415             return true;
6416         }
6417 #endif
6418 
6419         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
6420             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
6421             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
6422             return true;
6423         }
6424 
6425         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
6426             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
6427             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
6428             return true;
6429         }
6430 
6431         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
6432             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
6433             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
6434             return true;
6435         }
6436 
6437         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
6438             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
6439             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
6440             connection->state = SENT_DISCONNECT;
6441             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6442             return true;
6443         }
6444 
6445         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
6446             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
6447             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
6448             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
6449             return true;
6450         }
6451 
6452         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
6453             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
6454             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
6455             return true;
6456         }
6457 
6458         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
6459             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
6460             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
6461             return true;
6462         }
6463 
6464         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
6465             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6466             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
6467             return true;
6468         }
6469 
6470         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
6471             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
6472             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
6473             return true;
6474         }
6475 
6476         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
6477             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
6478             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
6479             return true;
6480         }
6481 #endif
6482 
6483         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
6484             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
6485 #ifdef ENABLE_CLASSIC
6486             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
6487 #endif
6488             if (connection->state != SENT_DISCONNECT){
6489                 connection->state = SENT_DISCONNECT;
6490                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
6491                 return true;
6492             }
6493         }
6494 
6495 #ifdef ENABLE_CLASSIC
6496         uint16_t sniff_min_interval;
6497         switch (connection->sniff_min_interval){
6498             case 0:
6499                 break;
6500             case 0xffff:
6501                 connection->sniff_min_interval = 0;
6502                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
6503                 return true;
6504             default:
6505                 sniff_min_interval = connection->sniff_min_interval;
6506                 connection->sniff_min_interval = 0;
6507                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
6508                 return true;
6509         }
6510 
6511         if (connection->sniff_subrating_max_latency != 0xffff){
6512             uint16_t max_latency = connection->sniff_subrating_max_latency;
6513             connection->sniff_subrating_max_latency = 0;
6514             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
6515             return true;
6516         }
6517 
6518         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
6519             uint8_t service_type = (uint8_t) connection->qos_service_type;
6520             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
6521             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);
6522             return true;
6523         }
6524 
6525         if (connection->request_role != HCI_ROLE_INVALID){
6526             hci_role_t role = connection->request_role;
6527             connection->request_role = HCI_ROLE_INVALID;
6528             hci_send_cmd(&hci_switch_role_command, connection->address, role);
6529             return true;
6530         }
6531 #endif
6532 
6533         if (connection->gap_connection_tasks != 0){
6534 #ifdef ENABLE_CLASSIC
6535             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
6536                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
6537                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
6538                 return true;
6539             }
6540             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
6541                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
6542                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
6543                 return true;
6544             }
6545 #endif
6546             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
6547                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
6548                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
6549                 return true;
6550             }
6551         }
6552 
6553 #ifdef ENABLE_BLE
6554         switch (connection->le_con_parameter_update_state){
6555             // response to L2CAP CON PARAMETER UPDATE REQUEST
6556             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
6557                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6558                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
6559                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6560                              0x0000, 0xffff);
6561                 return true;
6562             case CON_PARAMETER_UPDATE_REPLY:
6563                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6564                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
6565                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6566                              0x0000, 0xffff);
6567                 return true;
6568             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
6569                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6570                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
6571                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
6572                 return true;
6573             default:
6574                 break;
6575         }
6576         if (connection->le_phy_update_all_phys != 0xffu){
6577             uint8_t all_phys = connection->le_phy_update_all_phys;
6578             connection->le_phy_update_all_phys = 0xff;
6579             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);
6580             return true;
6581         }
6582 #endif
6583     }
6584     return false;
6585 }
6586 
6587 static void hci_run(void){
6588 
6589     // stack state sub statemachines
6590     switch (hci_stack->state) {
6591         case HCI_STATE_INITIALIZING:
6592             hci_initializing_run();
6593             break;
6594         case HCI_STATE_HALTING:
6595             hci_halting_run();
6596             break;
6597         case HCI_STATE_FALLING_ASLEEP:
6598             hci_falling_asleep_run();
6599             break;
6600         default:
6601             break;
6602     }
6603 
6604     // allow to run after initialization to working transition
6605     if (hci_stack->state != HCI_STATE_WORKING){
6606         return;
6607     }
6608 
6609     bool done;
6610 
6611     // send continuation fragments first, as they block the prepared packet buffer
6612     done = hci_run_acl_fragments();
6613     if (done) return;
6614 
6615 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6616     done = hci_run_iso_fragments();
6617     if (done) return;
6618 #endif
6619 
6620 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
6621     // send host num completed packets next as they don't require num_cmd_packets > 0
6622     if (!hci_can_send_comand_packet_transport()) return;
6623     if (hci_stack->host_completed_packets){
6624         hci_host_num_completed_packets();
6625         return;
6626     }
6627 #endif
6628 
6629     if (!hci_can_send_command_packet_now()) return;
6630 
6631     // global/non-connection oriented commands
6632 
6633 
6634 #ifdef ENABLE_CLASSIC
6635     // general gap classic
6636     done = hci_run_general_gap_classic();
6637     if (done) return;
6638 #endif
6639 
6640 #ifdef ENABLE_BLE
6641     // general gap le
6642     done = hci_run_general_gap_le();
6643     if (done) return;
6644 
6645 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6646     // ISO related tasks, e.g. BIG create/terminate/sync
6647     done = hci_run_iso_tasks();
6648     if (done) return;
6649 #endif
6650 #endif
6651 
6652     // send pending HCI commands
6653     hci_run_general_pending_commands();
6654 }
6655 
6656 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
6657     // house-keeping
6658 
6659 #ifdef ENABLE_CLASSIC
6660     bd_addr_t addr;
6661     hci_connection_t * conn;
6662 #endif
6663 #ifdef ENABLE_LE_CENTRAL
6664     uint8_t initiator_filter_policy;
6665 #endif
6666 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6667     uint8_t i;
6668     uint8_t num_cis;
6669     hci_con_handle_t cis_handle;
6670     uint8_t status;
6671 #endif
6672 
6673     uint16_t opcode = little_endian_read_16(packet, 0);
6674     switch (opcode) {
6675         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
6676             hci_stack->loopback_mode = packet[3];
6677             break;
6678 
6679 #ifdef ENABLE_CLASSIC
6680         case HCI_OPCODE_HCI_CREATE_CONNECTION:
6681             reverse_bd_addr(&packet[3], addr);
6682             log_info("Create_connection to %s", bd_addr_to_str(addr));
6683 
6684             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
6685             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
6686                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
6687                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
6688             }
6689 
6690             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6691             if (!conn) {
6692                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6693                 if (!conn) {
6694                     // notify client that alloc failed
6695                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6696                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
6697                 }
6698                 conn->state = SEND_CREATE_CONNECTION;
6699                 conn->role  = HCI_ROLE_MASTER;
6700             }
6701 
6702             log_info("conn state %u", conn->state);
6703             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
6704             switch (conn->state) {
6705                 // if connection active exists
6706                 case OPEN:
6707                     // and OPEN, emit connection complete command
6708                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
6709                     // packet not sent to controller
6710                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6711                 case RECEIVED_DISCONNECTION_COMPLETE:
6712                     // create connection triggered in disconnect complete event, let's do it now
6713                     break;
6714                 case SEND_CREATE_CONNECTION:
6715 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
6716                     if (hci_classic_operation_active()){
6717                         return ERROR_CODE_SUCCESS;
6718                     }
6719 #endif
6720                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
6721                     break;
6722                 default:
6723                     // otherwise, just ignore as it is already in the open process
6724                     // packet not sent to controller
6725                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6726             }
6727             conn->state = SENT_CREATE_CONNECTION;
6728 
6729             // track outgoing connection
6730             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
6731             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
6732             break;
6733 
6734 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
6735         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
6736             // setup_synchronous_connection? Voice setting at offset 22
6737             // TODO: compare to current setting if sco connection already active
6738             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
6739             break;
6740         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
6741             // accept_synchronous_connection? Voice setting at offset 18
6742             // TODO: compare to current setting if sco connection already active
6743             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
6744             // track outgoing connection
6745             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
6746             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
6747             break;
6748 #endif
6749 #endif
6750 
6751 #ifdef ENABLE_BLE
6752 #ifdef ENABLE_LE_CENTRAL
6753         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
6754             // white list used?
6755             initiator_filter_policy = packet[7];
6756             switch (initiator_filter_policy) {
6757                 case 0:
6758                     // whitelist not used
6759                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
6760                     break;
6761                 case 1:
6762                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
6763                     break;
6764                 default:
6765                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
6766                     break;
6767             }
6768             // track outgoing connection
6769             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
6770             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
6771             break;
6772         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
6773             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
6774             break;
6775 #endif
6776 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6777 #ifdef ENABLE_LE_CENTRAL
6778         case HCI_OPCODE_HCI_LE_CREATE_CIS:
6779             status = ERROR_CODE_SUCCESS;
6780             num_cis = packet[3];
6781             // setup hci_iso_streams
6782             for (i=0;i<num_cis;i++){
6783                 cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 4 + (4 * i));
6784                 status = hci_iso_stream_create(cis_handle, 0xff);
6785                 if (status != ERROR_CODE_SUCCESS) {
6786                     break;
6787                 }
6788             }
6789             // free structs on error
6790             if (status != ERROR_CODE_SUCCESS){
6791                 hci_iso_stream_requested_finalize(0xff);
6792                 return status;
6793             }
6794             break;
6795 #endif /* ENABLE_LE_CENTRAL */
6796 #ifdef ENABLE_LE_PERIPHERAL
6797         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
6798             cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 3);
6799             status = hci_iso_stream_create(cis_handle, 0xff);
6800             if (status != ERROR_CODE_SUCCESS){
6801                 return status;
6802             }
6803             break;
6804 #endif /* ENABLE_LE_PERIPHERAL */
6805 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6806 #endif /* ENABLE_BLE */
6807         default:
6808             break;
6809     }
6810 
6811     hci_stack->num_cmd_packets--;
6812 
6813     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
6814     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
6815     if (err != 0){
6816         return ERROR_CODE_HARDWARE_FAILURE;
6817     }
6818     return ERROR_CODE_SUCCESS;
6819 }
6820 
6821 // disconnect because of security block
6822 void hci_disconnect_security_block(hci_con_handle_t con_handle){
6823     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6824     if (!connection) return;
6825     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
6826 }
6827 
6828 
6829 // Configure Secure Simple Pairing
6830 
6831 #ifdef ENABLE_CLASSIC
6832 
6833 // enable will enable SSP during init
6834 void gap_ssp_set_enable(int enable){
6835     hci_stack->ssp_enable = enable;
6836 }
6837 
6838 static int hci_local_ssp_activated(void){
6839     return gap_ssp_supported() && hci_stack->ssp_enable;
6840 }
6841 
6842 // if set, BTstack will respond to io capability request using authentication requirement
6843 void gap_ssp_set_io_capability(int io_capability){
6844     hci_stack->ssp_io_capability = io_capability;
6845 }
6846 void gap_ssp_set_authentication_requirement(int authentication_requirement){
6847     hci_stack->ssp_authentication_requirement = authentication_requirement;
6848 }
6849 
6850 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
6851 void gap_ssp_set_auto_accept(int auto_accept){
6852     hci_stack->ssp_auto_accept = auto_accept;
6853 }
6854 
6855 void gap_secure_connections_enable(bool enable){
6856     hci_stack->secure_connections_enable = enable;
6857 }
6858 bool gap_secure_connections_active(void){
6859     return hci_stack->secure_connections_active;
6860 }
6861 
6862 #endif
6863 
6864 // va_list part of hci_send_cmd
6865 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
6866     if (!hci_can_send_command_packet_now()){
6867         log_error("hci_send_cmd called but cannot send packet now");
6868         return ERROR_CODE_COMMAND_DISALLOWED;
6869     }
6870 
6871     // for HCI INITIALIZATION
6872     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
6873     hci_stack->last_cmd_opcode = cmd->opcode;
6874 
6875     hci_reserve_packet_buffer();
6876     uint8_t * packet = hci_stack->hci_packet_buffer;
6877     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
6878     uint8_t status = hci_send_cmd_packet(packet, size);
6879 
6880     // release packet buffer on error or for synchronous transport implementations
6881     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
6882         hci_release_packet_buffer();
6883         hci_emit_transport_packet_sent();
6884     }
6885 
6886     return status;
6887 }
6888 
6889 /**
6890  * pre: numcmds >= 0 - it's allowed to send a command to the controller
6891  */
6892 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
6893     va_list argptr;
6894     va_start(argptr, cmd);
6895     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
6896     va_end(argptr);
6897     return status;
6898 }
6899 
6900 // Create various non-HCI events.
6901 // TODO: generalize, use table similar to hci_create_command
6902 
6903 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
6904     // dump packet
6905     if (dump) {
6906         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
6907     }
6908 
6909     // dispatch to all event handlers
6910     btstack_linked_list_iterator_t it;
6911     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
6912     while (btstack_linked_list_iterator_has_next(&it)){
6913         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
6914         entry->callback(HCI_EVENT_PACKET, 0, event, size);
6915     }
6916 }
6917 
6918 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
6919     if (!hci_stack->acl_packet_handler) return;
6920     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
6921 }
6922 
6923 #ifdef ENABLE_CLASSIC
6924 static void hci_notify_if_sco_can_send_now(void){
6925     // notify SCO sender if waiting
6926     if (!hci_stack->sco_waiting_for_can_send_now) return;
6927     if (hci_can_send_sco_packet_now()){
6928         hci_stack->sco_waiting_for_can_send_now = 0;
6929         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
6930         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
6931         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
6932     }
6933 }
6934 
6935 // parsing end emitting has been merged to reduce code size
6936 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
6937     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
6938 
6939     uint8_t * eir_data;
6940     ad_context_t context;
6941     const uint8_t * name;
6942     uint8_t         name_len;
6943 
6944     if (size < 3) return;
6945 
6946     int event_type = hci_event_packet_get_type(packet);
6947     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
6948     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
6949 
6950     switch (event_type){
6951         case HCI_EVENT_INQUIRY_RESULT:
6952         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6953             if (size != (3 + (num_responses * 14))) return;
6954             break;
6955         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6956             if (size != 257) return;
6957             if (num_responses != 1) return;
6958             break;
6959         default:
6960             return;
6961     }
6962 
6963     // event[1] is set at the end
6964     int i;
6965     for (i=0; i<num_responses;i++){
6966         memset(event, 0, sizeof(event));
6967         event[0] = GAP_EVENT_INQUIRY_RESULT;
6968         uint8_t event_size = 27;    // if name is not set by EIR
6969 
6970         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
6971         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
6972         (void)memcpy(&event[9],
6973                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
6974                      3); // class of device
6975         (void)memcpy(&event[12],
6976                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
6977                      2); // clock offset
6978 
6979         switch (event_type){
6980             case HCI_EVENT_INQUIRY_RESULT:
6981                 // 14,15,16,17 = 0, size 18
6982                 break;
6983             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6984                 event[14] = 1;
6985                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
6986                 // 16,17 = 0, size 18
6987                 break;
6988             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6989                 event[14] = 1;
6990                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
6991                 // EIR packets only contain a single inquiry response
6992                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
6993                 name = NULL;
6994                 // Iterate over EIR data
6995                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
6996                     uint8_t data_type    = ad_iterator_get_data_type(&context);
6997                     uint8_t data_size    = ad_iterator_get_data_len(&context);
6998                     const uint8_t * data = ad_iterator_get_data(&context);
6999                     // Prefer Complete Local Name over Shortened Local Name
7000                     switch (data_type){
7001                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
7002                             if (name) continue;
7003                             /* fall through */
7004                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
7005                             name = data;
7006                             name_len = data_size;
7007                             break;
7008                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
7009                             if (data_size != 8) break;
7010                             event[16] = 1;
7011                             memcpy(&event[17], data, 8);
7012                             break;
7013                         default:
7014                             break;
7015                     }
7016                 }
7017                 if (name){
7018                     event[25] = 1;
7019                     // truncate name if needed
7020                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
7021                     event[26] = len;
7022                     (void)memcpy(&event[27], name, len);
7023                     event_size += len;
7024                 }
7025                 break;
7026             default:
7027                 return;
7028         }
7029         event[1] = event_size - 2;
7030         hci_emit_event(event, event_size, 1);
7031     }
7032 }
7033 #endif
7034 
7035 void hci_emit_state(void){
7036     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
7037     uint8_t event[3];
7038     event[0] = BTSTACK_EVENT_STATE;
7039     event[1] = sizeof(event) - 2u;
7040     event[2] = hci_stack->state;
7041     hci_emit_event(event, sizeof(event), 1);
7042 }
7043 
7044 #ifdef ENABLE_CLASSIC
7045 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
7046     uint8_t event[13];
7047     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
7048     event[1] = sizeof(event) - 2;
7049     event[2] = status;
7050     little_endian_store_16(event, 3, con_handle);
7051     reverse_bd_addr(address, &event[5]);
7052     event[11] = 1; // ACL connection
7053     event[12] = 0; // encryption disabled
7054     hci_emit_event(event, sizeof(event), 1);
7055 }
7056 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
7057     if (disable_l2cap_timeouts) return;
7058     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
7059     uint8_t event[4];
7060     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
7061     event[1] = sizeof(event) - 2;
7062     little_endian_store_16(event, 2, conn->con_handle);
7063     hci_emit_event(event, sizeof(event), 1);
7064 }
7065 #endif
7066 
7067 #ifdef ENABLE_BLE
7068 #ifdef ENABLE_LE_CENTRAL
7069 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){
7070     uint8_t event[21];
7071     event[0] = HCI_EVENT_LE_META;
7072     event[1] = sizeof(event) - 2u;
7073     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
7074     event[3] = status;
7075     little_endian_store_16(event, 4, con_handle);
7076     event[6] = 0; // TODO: role
7077     event[7] = address_type;
7078     reverse_bd_addr(address, &event[8]);
7079     little_endian_store_16(event, 14, 0); // interval
7080     little_endian_store_16(event, 16, 0); // latency
7081     little_endian_store_16(event, 18, 0); // supervision timeout
7082     event[20] = 0; // master clock accuracy
7083     hci_emit_event(event, sizeof(event), 1);
7084 }
7085 #endif
7086 #endif
7087 
7088 static void hci_emit_transport_packet_sent(void){
7089     // notify upper stack that it might be possible to send again
7090     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
7091     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
7092 }
7093 
7094 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
7095     uint8_t event[6];
7096     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
7097     event[1] = sizeof(event) - 2u;
7098     event[2] = 0; // status = OK
7099     little_endian_store_16(event, 3, con_handle);
7100     event[5] = reason;
7101     hci_emit_event(event, sizeof(event), 1);
7102 }
7103 
7104 static void hci_emit_nr_connections_changed(void){
7105     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
7106     uint8_t event[3];
7107     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
7108     event[1] = sizeof(event) - 2u;
7109     event[2] = nr_hci_connections();
7110     hci_emit_event(event, sizeof(event), 1);
7111 }
7112 
7113 static void hci_emit_hci_open_failed(void){
7114     log_info("BTSTACK_EVENT_POWERON_FAILED");
7115     uint8_t event[2];
7116     event[0] = BTSTACK_EVENT_POWERON_FAILED;
7117     event[1] = sizeof(event) - 2u;
7118     hci_emit_event(event, sizeof(event), 1);
7119 }
7120 
7121 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
7122     log_info("hci_emit_dedicated_bonding_result %u ", status);
7123     uint8_t event[9];
7124     int pos = 0;
7125     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
7126     event[pos++] = sizeof(event) - 2u;
7127     event[pos++] = status;
7128     reverse_bd_addr(address, &event[pos]);
7129     hci_emit_event(event, sizeof(event), 1);
7130 }
7131 
7132 
7133 #ifdef ENABLE_CLASSIC
7134 
7135 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
7136     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
7137     uint8_t event[5];
7138     int pos = 0;
7139     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
7140     event[pos++] = sizeof(event) - 2;
7141     little_endian_store_16(event, 2, con_handle);
7142     pos += 2;
7143     event[pos++] = level;
7144     hci_emit_event(event, sizeof(event), 1);
7145 }
7146 
7147 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
7148     if (!connection) return LEVEL_0;
7149     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
7150     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
7151     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
7152     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
7153     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
7154     // LEVEL 4 always requires 128 bit encrytion key size
7155     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
7156         security_level = LEVEL_3;
7157     }
7158     return security_level;
7159 }
7160 
7161 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
7162     uint8_t event[4];
7163     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
7164     event[1] = sizeof(event) - 2;
7165     event[2] = discoverable;
7166     event[3] = connectable;
7167     hci_emit_event(event, sizeof(event), 1);
7168 }
7169 
7170 // query if remote side supports eSCO
7171 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
7172     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7173     if (!connection) return false;
7174     return (connection->remote_supported_features[0] & 1) != 0;
7175 }
7176 
7177 static bool hci_ssp_supported(hci_connection_t * connection){
7178     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
7179     return (connection->bonding_flags & mask) == mask;
7180 }
7181 
7182 // query if remote side supports SSP
7183 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
7184     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7185     if (!connection) return false;
7186     return hci_ssp_supported(connection) ? 1 : 0;
7187 }
7188 
7189 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
7190     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
7191 }
7192 
7193 /**
7194  * Check if remote supported features query has completed
7195  */
7196 bool hci_remote_features_available(hci_con_handle_t handle){
7197     hci_connection_t * connection = hci_connection_for_handle(handle);
7198     if (!connection) return false;
7199     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
7200 }
7201 
7202 /**
7203  * Trigger remote supported features query
7204  */
7205 
7206 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
7207     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
7208         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7209     }
7210 }
7211 
7212 void hci_remote_features_query(hci_con_handle_t con_handle){
7213     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7214     if (!connection) return;
7215     hci_trigger_remote_features_for_connection(connection);
7216     hci_run();
7217 }
7218 
7219 // GAP API
7220 /**
7221  * @bbrief enable/disable bonding. default is enabled
7222  * @praram enabled
7223  */
7224 void gap_set_bondable_mode(int enable){
7225     hci_stack->bondable = enable ? 1 : 0;
7226 }
7227 /**
7228  * @brief Get bondable mode.
7229  * @return 1 if bondable
7230  */
7231 int gap_get_bondable_mode(void){
7232     return hci_stack->bondable;
7233 }
7234 
7235 /**
7236  * @brief map link keys to security levels
7237  */
7238 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
7239     switch (link_key_type){
7240         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7241             return LEVEL_4;
7242         case COMBINATION_KEY:
7243         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7244             return LEVEL_3;
7245         default:
7246             return LEVEL_2;
7247     }
7248 }
7249 
7250 /**
7251  * @brief map link keys to secure connection yes/no
7252  */
7253 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
7254     switch (link_key_type){
7255         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7256         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7257             return true;
7258         default:
7259             return false;
7260     }
7261 }
7262 
7263 /**
7264  * @brief map link keys to authenticated
7265  */
7266 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
7267     switch (link_key_type){
7268         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7269         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7270             return true;
7271         default:
7272             return false;
7273     }
7274 }
7275 
7276 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
7277     log_info("gap_mitm_protection_required_for_security_level %u", level);
7278     return level > LEVEL_2;
7279 }
7280 
7281 /**
7282  * @brief get current security level
7283  */
7284 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
7285     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7286     if (!connection) return LEVEL_0;
7287     return gap_security_level_for_connection(connection);
7288 }
7289 
7290 /**
7291  * @brief request connection to device to
7292  * @result GAP_AUTHENTICATION_RESULT
7293  */
7294 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
7295     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7296     if (!connection){
7297         hci_emit_security_level(con_handle, LEVEL_0);
7298         return;
7299     }
7300 
7301     btstack_assert(hci_is_le_connection(connection) == false);
7302 
7303     // 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)
7304     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
7305     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
7306         requested_level = LEVEL_4;
7307     }
7308 
7309     gap_security_level_t current_level = gap_security_level(con_handle);
7310     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
7311         requested_level, connection->requested_security_level, current_level);
7312 
7313     // authentication active if authentication request was sent or planned level > 0
7314     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
7315     if (authentication_active){
7316         // authentication already active
7317         if (connection->requested_security_level < requested_level){
7318             // increase requested level as new level is higher
7319             // TODO: handle re-authentication when done
7320             connection->requested_security_level = requested_level;
7321         }
7322     } else {
7323         // no request active, notify if security sufficient
7324         if (requested_level <= current_level){
7325             hci_emit_security_level(con_handle, current_level);
7326             return;
7327         }
7328 
7329         // store request
7330         connection->requested_security_level = requested_level;
7331 
7332         // start to authenticate connection
7333         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
7334 
7335         // request remote features if not already active, also trigger hci_run
7336         hci_remote_features_query(con_handle);
7337     }
7338 }
7339 
7340 /**
7341  * @brief start dedicated bonding with device. disconnect after bonding
7342  * @param device
7343  * @param request MITM protection
7344  * @result GAP_DEDICATED_BONDING_COMPLETE
7345  */
7346 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
7347 
7348     // create connection state machine
7349     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
7350 
7351     if (!connection){
7352         return BTSTACK_MEMORY_ALLOC_FAILED;
7353     }
7354 
7355     // delete linkn key
7356     gap_drop_link_key_for_bd_addr(device);
7357 
7358     // configure LEVEL_2/3, dedicated bonding
7359     connection->state = SEND_CREATE_CONNECTION;
7360     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
7361     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
7362     connection->bonding_flags = BONDING_DEDICATED;
7363 
7364     // wait for GAP Security Result and send GAP Dedicated Bonding complete
7365 
7366     // handle: connnection failure (connection complete != ok)
7367     // handle: authentication failure
7368     // handle: disconnect on done
7369 
7370     hci_run();
7371 
7372     return 0;
7373 }
7374 
7375 void gap_set_local_name(const char * local_name){
7376     hci_stack->local_name = local_name;
7377     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
7378     // also update EIR if not set by user
7379     if (hci_stack->eir_data == NULL){
7380         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7381     }
7382     hci_run();
7383 }
7384 #endif
7385 
7386 
7387 #ifdef ENABLE_BLE
7388 
7389 #ifdef ENABLE_LE_CENTRAL
7390 void gap_start_scan(void){
7391     hci_stack->le_scanning_enabled = true;
7392     hci_run();
7393 }
7394 
7395 void gap_stop_scan(void){
7396     hci_stack->le_scanning_enabled = false;
7397     hci_run();
7398 }
7399 
7400 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
7401     hci_stack->le_scan_type          = scan_type;
7402     hci_stack->le_scan_filter_policy = scanning_filter_policy;
7403     hci_stack->le_scan_interval      = scan_interval;
7404     hci_stack->le_scan_window        = scan_window;
7405     hci_stack->le_scanning_param_update = true;
7406     hci_run();
7407 }
7408 
7409 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
7410     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
7411 }
7412 
7413 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
7414     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
7415     if (!conn){
7416         // disallow if le connection is already outgoing
7417         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7418             log_error("le connection already active");
7419             return ERROR_CODE_COMMAND_DISALLOWED;
7420         }
7421 
7422         log_info("gap_connect: no connection exists yet, creating context");
7423         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
7424         if (!conn){
7425             // notify client that alloc failed
7426             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7427             log_info("gap_connect: failed to alloc hci_connection_t");
7428             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
7429         }
7430 
7431         // set le connecting state
7432         if (hci_is_le_connection_type(addr_type)){
7433             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
7434         }
7435 
7436         conn->state = SEND_CREATE_CONNECTION;
7437         log_info("gap_connect: send create connection next");
7438         hci_run();
7439         return ERROR_CODE_SUCCESS;
7440     }
7441 
7442     if (!hci_is_le_connection(conn) ||
7443         (conn->state == SEND_CREATE_CONNECTION) ||
7444         (conn->state == SENT_CREATE_CONNECTION)) {
7445         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
7446         log_error("gap_connect: classic connection or connect is already being created");
7447         return GATT_CLIENT_IN_WRONG_STATE;
7448     }
7449 
7450     // check if connection was just disconnected
7451     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7452         log_info("gap_connect: send create connection (again)");
7453         conn->state = SEND_CREATE_CONNECTION;
7454         hci_run();
7455         return ERROR_CODE_SUCCESS;
7456     }
7457 
7458     log_info("gap_connect: context exists with state %u", conn->state);
7459     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
7460     hci_run();
7461     return ERROR_CODE_SUCCESS;
7462 }
7463 
7464 // @assumption: only a single outgoing LE Connection exists
7465 static hci_connection_t * gap_get_outgoing_connection(void){
7466     btstack_linked_item_t *it;
7467     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7468         hci_connection_t * conn = (hci_connection_t *) it;
7469         if (!hci_is_le_connection(conn)) continue;
7470         switch (conn->state){
7471             case SEND_CREATE_CONNECTION:
7472             case SENT_CREATE_CONNECTION:
7473             case SENT_CANCEL_CONNECTION:
7474                 return conn;
7475             default:
7476                 break;
7477         };
7478     }
7479     return NULL;
7480 }
7481 
7482 uint8_t gap_connect_cancel(void){
7483     hci_connection_t * conn;
7484     switch (hci_stack->le_connecting_request){
7485         case LE_CONNECTING_IDLE:
7486             break;
7487         case LE_CONNECTING_WHITELIST:
7488             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7489             hci_run();
7490             break;
7491         case LE_CONNECTING_DIRECT:
7492             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7493             conn = gap_get_outgoing_connection();
7494             if (conn == NULL){
7495                 hci_run();
7496             } else {
7497                 switch (conn->state){
7498                     case SEND_CREATE_CONNECTION:
7499                         // skip sending create connection and emit event instead
7500                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
7501                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
7502                         btstack_memory_hci_connection_free( conn );
7503                         break;
7504                     case SENT_CREATE_CONNECTION:
7505                         // request to send cancel connection
7506                         conn->state = SEND_CANCEL_CONNECTION;
7507                         hci_run();
7508                         break;
7509                     default:
7510                         break;
7511                 }
7512             }
7513             break;
7514         default:
7515             btstack_unreachable();
7516             break;
7517     }
7518     return ERROR_CODE_SUCCESS;
7519 }
7520 
7521 /**
7522  * @brief Set connection parameters for outgoing connections
7523  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
7524  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
7525  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
7526  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
7527  * @param conn_latency, default: 4
7528  * @param supervision_timeout (unit: 10ms), default: 720 ms
7529  * @param min_ce_length (unit: 0.625ms), default: 10 ms
7530  * @param max_ce_length (unit: 0.625ms), default: 30 ms
7531  */
7532 
7533 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
7534     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
7535     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
7536     hci_stack->le_connection_scan_interval = conn_scan_interval;
7537     hci_stack->le_connection_scan_window = conn_scan_window;
7538     hci_stack->le_connection_interval_min = conn_interval_min;
7539     hci_stack->le_connection_interval_max = conn_interval_max;
7540     hci_stack->le_connection_latency = conn_latency;
7541     hci_stack->le_supervision_timeout = supervision_timeout;
7542     hci_stack->le_minimum_ce_length = min_ce_length;
7543     hci_stack->le_maximum_ce_length = max_ce_length;
7544 }
7545 #endif
7546 
7547 /**
7548  * @brief Updates the connection parameters for a given LE connection
7549  * @param handle
7550  * @param conn_interval_min (unit: 1.25ms)
7551  * @param conn_interval_max (unit: 1.25ms)
7552  * @param conn_latency
7553  * @param supervision_timeout (unit: 10ms)
7554  * @return 0 if ok
7555  */
7556 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7557     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7558     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7559     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7560     connection->le_conn_interval_min = conn_interval_min;
7561     connection->le_conn_interval_max = conn_interval_max;
7562     connection->le_conn_latency = conn_latency;
7563     connection->le_supervision_timeout = supervision_timeout;
7564     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
7565     hci_run();
7566     return 0;
7567 }
7568 
7569 /**
7570  * @brief Request an update of the connection parameter for a given LE connection
7571  * @param handle
7572  * @param conn_interval_min (unit: 1.25ms)
7573  * @param conn_interval_max (unit: 1.25ms)
7574  * @param conn_latency
7575  * @param supervision_timeout (unit: 10ms)
7576  * @return 0 if ok
7577  */
7578 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7579     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7580     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7581     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7582     connection->le_conn_interval_min = conn_interval_min;
7583     connection->le_conn_interval_max = conn_interval_max;
7584     connection->le_conn_latency = conn_latency;
7585     connection->le_supervision_timeout = supervision_timeout;
7586     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
7587     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
7588     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
7589     return 0;
7590 }
7591 
7592 #ifdef ENABLE_LE_PERIPHERAL
7593 
7594 /**
7595  * @brief Set Advertisement Data
7596  * @param advertising_data_length
7597  * @param advertising_data (max 31 octets)
7598  * @note data is not copied, pointer has to stay valid
7599  */
7600 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
7601     hci_stack->le_advertisements_data_len = advertising_data_length;
7602     hci_stack->le_advertisements_data = advertising_data;
7603     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7604     hci_run();
7605 }
7606 
7607 /**
7608  * @brief Set Scan Response Data
7609  * @param advertising_data_length
7610  * @param advertising_data (max 31 octets)
7611  * @note data is not copied, pointer has to stay valid
7612  */
7613 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
7614     hci_stack->le_scan_response_data_len = scan_response_data_length;
7615     hci_stack->le_scan_response_data = scan_response_data;
7616     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7617     hci_run();
7618 }
7619 
7620 /**
7621  * @brief Set Advertisement Parameters
7622  * @param adv_int_min
7623  * @param adv_int_max
7624  * @param adv_type
7625  * @param direct_address_type
7626  * @param direct_address
7627  * @param channel_map
7628  * @param filter_policy
7629  *
7630  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
7631  */
7632  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
7633     uint8_t direct_address_typ, bd_addr_t direct_address,
7634     uint8_t channel_map, uint8_t filter_policy) {
7635 
7636     hci_stack->le_advertisements_interval_min = adv_int_min;
7637     hci_stack->le_advertisements_interval_max = adv_int_max;
7638     hci_stack->le_advertisements_type = adv_type;
7639     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
7640     hci_stack->le_advertisements_channel_map = channel_map;
7641     hci_stack->le_advertisements_filter_policy = filter_policy;
7642     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
7643                  6);
7644 
7645     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7646     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
7647     hci_run();
7648  }
7649 
7650 /**
7651  * @brief Enable/Disable Advertisements
7652  * @param enabled
7653  */
7654 void gap_advertisements_enable(int enabled){
7655     if (enabled == 0){
7656         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7657     } else {
7658         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
7659     }
7660     hci_update_advertisements_enabled_for_current_roles();
7661     hci_run();
7662 }
7663 
7664 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7665 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
7666     btstack_linked_list_iterator_t it;
7667     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
7668     while (btstack_linked_list_iterator_has_next(&it)){
7669         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
7670         if ( item->advertising_handle == advertising_handle ) {
7671             return item;
7672         }
7673     }
7674     return NULL;
7675 }
7676 
7677 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
7678     // find free advertisement handle
7679     uint8_t advertisement_handle;
7680     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
7681         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
7682     }
7683     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7684     // clear
7685     memset(storage, 0, sizeof(le_advertising_set_t));
7686     // copy params
7687     storage->advertising_handle = advertisement_handle;
7688     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7689     // add to list
7690     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
7691     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7692     *out_advertising_handle = advertisement_handle;
7693     // set tasks and start
7694     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7695     hci_run();
7696     return ERROR_CODE_SUCCESS;
7697 }
7698 
7699 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
7700     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7701     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7702     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7703     // set tasks and start
7704     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7705     hci_run();
7706     return ERROR_CODE_SUCCESS;
7707 }
7708 
7709 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
7710     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7711     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7712     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
7713     return ERROR_CODE_SUCCESS;
7714 }
7715 
7716 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
7717     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7718     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7719     memcpy(advertising_set->random_address, random_address, 6);
7720     // set tasks and start
7721     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7722     hci_run();
7723     return ERROR_CODE_SUCCESS;
7724 }
7725 
7726 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
7727     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7728     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7729     advertising_set->adv_data = advertising_data;
7730     advertising_set->adv_data_len = advertising_data_length;
7731     // set tasks and start
7732     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7733     hci_run();
7734     return ERROR_CODE_SUCCESS;
7735 }
7736 
7737 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){
7738     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7739     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7740     advertising_set->scan_data = scan_response_data;
7741     advertising_set->scan_data_len = scan_response_data_length;
7742     // set tasks and start
7743     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7744     hci_run();
7745     return ERROR_CODE_SUCCESS;
7746 }
7747 
7748 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
7749     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7750     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7751     advertising_set->enable_timeout = timeout;
7752     advertising_set->enable_max_scan_events = num_extended_advertising_events;
7753     // set tasks and start
7754     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
7755     hci_run();
7756     return ERROR_CODE_SUCCESS;
7757 }
7758 
7759 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
7760     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7761     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7762     // set tasks and start
7763     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7764     hci_run();
7765     return ERROR_CODE_SUCCESS;
7766 }
7767 
7768 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
7769     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7770     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7771     // set tasks and start
7772     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
7773     hci_run();
7774     return ERROR_CODE_SUCCESS;
7775 }
7776 
7777 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7778 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
7779     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7780     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7781     // periodic advertising requires neither connectable, scannable, legacy or anonymous
7782     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7783     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
7784     // set tasks and start
7785     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
7786     hci_run();
7787     return ERROR_CODE_SUCCESS;
7788 }
7789 
7790 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
7791     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7792     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7793     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
7794     return ERROR_CODE_SUCCESS;
7795 }
7796 
7797 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
7798     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7799     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7800     advertising_set->periodic_data = periodic_data;
7801     advertising_set->periodic_data_len = periodic_data_length;
7802     // set tasks and start
7803     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
7804     hci_run();
7805     return ERROR_CODE_SUCCESS;
7806 }
7807 
7808 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
7809     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7810     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7811     // set tasks and start
7812     advertising_set->periodic_include_adi = include_adi;
7813     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7814     hci_run();
7815     return ERROR_CODE_SUCCESS;
7816 }
7817 
7818 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
7819     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7820     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7821     // set tasks and start
7822     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7823     hci_run();
7824     return ERROR_CODE_SUCCESS;
7825 }
7826 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
7827 
7828 #endif
7829 
7830 #endif
7831 
7832 void hci_le_set_own_address_type(uint8_t own_address_type){
7833     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
7834     if (own_address_type == hci_stack->le_own_addr_type) return;
7835     hci_stack->le_own_addr_type = own_address_type;
7836 
7837 #ifdef ENABLE_LE_PERIPHERAL
7838     // update advertisement parameters, too
7839     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7840     hci_run();
7841 #endif
7842 #ifdef ENABLE_LE_CENTRAL
7843     // note: we don't update scan parameters or modify ongoing connection attempts
7844 #endif
7845 }
7846 
7847 void hci_le_random_address_set(const bd_addr_t random_address){
7848     memcpy(hci_stack->le_random_address, random_address, 6);
7849     hci_stack->le_random_address_set = true;
7850     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7851     hci_run();
7852 }
7853 
7854 #endif
7855 
7856 uint8_t gap_disconnect(hci_con_handle_t handle){
7857     hci_connection_t * conn = hci_connection_for_handle(handle);
7858     if (!conn){
7859         hci_emit_disconnection_complete(handle, 0);
7860         return 0;
7861     }
7862     // ignore if already disconnected
7863     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7864         return 0;
7865     }
7866     conn->state = SEND_DISCONNECT;
7867     hci_run();
7868     return 0;
7869 }
7870 
7871 int gap_read_rssi(hci_con_handle_t con_handle){
7872     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7873     if (hci_connection == NULL) return 0;
7874     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
7875     hci_run();
7876     return 1;
7877 }
7878 
7879 /**
7880  * @brief Get connection type
7881  * @param con_handle
7882  * @result connection_type
7883  */
7884 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
7885     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7886     if (!conn) return GAP_CONNECTION_INVALID;
7887     switch (conn->address_type){
7888         case BD_ADDR_TYPE_LE_PUBLIC:
7889         case BD_ADDR_TYPE_LE_RANDOM:
7890             return GAP_CONNECTION_LE;
7891         case BD_ADDR_TYPE_SCO:
7892             return GAP_CONNECTION_SCO;
7893         case BD_ADDR_TYPE_ACL:
7894             return GAP_CONNECTION_ACL;
7895         default:
7896             return GAP_CONNECTION_INVALID;
7897     }
7898 }
7899 
7900 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
7901     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7902     if (!conn) return HCI_ROLE_INVALID;
7903     return (hci_role_t) conn->role;
7904 }
7905 
7906 
7907 #ifdef ENABLE_CLASSIC
7908 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
7909     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7910     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7911     conn->request_role = role;
7912     hci_run();
7913     return ERROR_CODE_SUCCESS;
7914 }
7915 #endif
7916 
7917 #ifdef ENABLE_BLE
7918 
7919 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){
7920     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7921     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7922 
7923     conn->le_phy_update_all_phys    = all_phys;
7924     conn->le_phy_update_tx_phys     = tx_phys;
7925     conn->le_phy_update_rx_phys     = rx_phys;
7926     conn->le_phy_update_phy_options = phy_options;
7927 
7928     hci_run();
7929 
7930     return 0;
7931 }
7932 
7933 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
7934     // check if already in list
7935     btstack_linked_list_iterator_t it;
7936     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7937     while (btstack_linked_list_iterator_has_next(&it)) {
7938         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
7939         if (entry->address_type != address_type) {
7940             continue;
7941         }
7942         if (memcmp(entry->address, address, 6) != 0) {
7943             continue;
7944         }
7945 		// disallow if already scheduled to add
7946 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
7947 			return ERROR_CODE_COMMAND_DISALLOWED;
7948 		}
7949 		// still on controller, but scheduled to remove -> re-add
7950 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
7951 		return ERROR_CODE_SUCCESS;
7952     }
7953     // alloc and add to list
7954     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
7955     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
7956     entry->address_type = address_type;
7957     (void)memcpy(entry->address, address, 6);
7958     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
7959     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
7960     return ERROR_CODE_SUCCESS;
7961 }
7962 
7963 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7964     btstack_linked_list_iterator_t it;
7965     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7966     while (btstack_linked_list_iterator_has_next(&it)){
7967         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7968         if (entry->address_type != address_type) {
7969             continue;
7970         }
7971         if (memcmp(entry->address, address, 6) != 0) {
7972             continue;
7973         }
7974         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7975             // remove from controller if already present
7976             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7977         }  else {
7978             // directly remove entry from whitelist
7979             btstack_linked_list_iterator_remove(&it);
7980             btstack_memory_whitelist_entry_free(entry);
7981         }
7982         return ERROR_CODE_SUCCESS;
7983     }
7984     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7985 }
7986 
7987 static void hci_whitelist_clear(void){
7988     btstack_linked_list_iterator_t it;
7989     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7990     while (btstack_linked_list_iterator_has_next(&it)){
7991         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7992         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7993             // remove from controller if already present
7994             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7995             continue;
7996         }
7997         // directly remove entry from whitelist
7998         btstack_linked_list_iterator_remove(&it);
7999         btstack_memory_whitelist_entry_free(entry);
8000     }
8001 }
8002 
8003 // free all entries unconditionally
8004 static void hci_whitelist_free(void){
8005     btstack_linked_list_iterator_t lit;
8006     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
8007     while (btstack_linked_list_iterator_has_next(&lit)){
8008         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
8009         btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
8010         btstack_memory_whitelist_entry_free(entry);
8011     }
8012 }
8013 
8014 /**
8015  * @brief Clear Whitelist
8016  * @return 0 if ok
8017  */
8018 uint8_t gap_whitelist_clear(void){
8019     hci_whitelist_clear();
8020     hci_run();
8021     return ERROR_CODE_SUCCESS;
8022 }
8023 
8024 /**
8025  * @brief Add Device to Whitelist
8026  * @param address_typ
8027  * @param address
8028  * @return 0 if ok
8029  */
8030 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8031     uint8_t status = hci_whitelist_add(address_type, address);
8032     if (status){
8033         return status;
8034     }
8035     hci_run();
8036     return ERROR_CODE_SUCCESS;
8037 }
8038 
8039 /**
8040  * @brief Remove Device from Whitelist
8041  * @param address_typ
8042  * @param address
8043  * @return 0 if ok
8044  */
8045 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8046     uint8_t status = hci_whitelist_remove(address_type, address);
8047     if (status){
8048         return status;
8049     }
8050     hci_run();
8051     return ERROR_CODE_SUCCESS;
8052 }
8053 
8054 #ifdef ENABLE_LE_CENTRAL
8055 /**
8056  * @brief Connect with Whitelist
8057  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
8058  * @return - if ok
8059  */
8060 uint8_t gap_connect_with_whitelist(void){
8061     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8062         return ERROR_CODE_COMMAND_DISALLOWED;
8063     }
8064     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8065     hci_run();
8066     return ERROR_CODE_SUCCESS;
8067 }
8068 
8069 /**
8070  * @brief Auto Connection Establishment - Start Connecting to device
8071  * @param address_typ
8072  * @param address
8073  * @return 0 if ok
8074  */
8075 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
8076     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8077         return ERROR_CODE_COMMAND_DISALLOWED;
8078     }
8079 
8080     uint8_t status = hci_whitelist_add(address_type, address);
8081     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
8082         return status;
8083     }
8084 
8085     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8086 
8087     hci_run();
8088     return ERROR_CODE_SUCCESS;
8089 }
8090 
8091 /**
8092  * @brief Auto Connection Establishment - Stop Connecting to device
8093  * @param address_typ
8094  * @param address
8095  * @return 0 if ok
8096  */
8097 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
8098     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8099         return ERROR_CODE_COMMAND_DISALLOWED;
8100     }
8101 
8102     hci_whitelist_remove(address_type, address);
8103     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
8104         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8105     }
8106     hci_run();
8107     return 0;
8108 }
8109 
8110 /**
8111  * @brief Auto Connection Establishment - Stop everything
8112  * @note  Convenience function to stop all active auto connection attempts
8113  */
8114 uint8_t gap_auto_connection_stop_all(void){
8115     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
8116         return ERROR_CODE_COMMAND_DISALLOWED;
8117     }
8118     hci_whitelist_clear();
8119     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8120     hci_run();
8121     return ERROR_CODE_SUCCESS;
8122 }
8123 
8124 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
8125     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8126     if (!conn) return 0;
8127     return conn->le_connection_interval;
8128 }
8129 #endif
8130 #endif
8131 
8132 #ifdef ENABLE_CLASSIC
8133 /**
8134  * @brief Set Extended Inquiry Response data
8135  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
8136  * @note has to be done before stack starts up
8137  */
8138 void gap_set_extended_inquiry_response(const uint8_t * data){
8139     hci_stack->eir_data = data;
8140     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
8141     hci_run();
8142 }
8143 
8144 /**
8145  * @brief Start GAP Classic Inquiry
8146  * @param duration in 1.28s units
8147  * @return 0 if ok
8148  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
8149  */
8150 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
8151     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
8152     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8153     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
8154         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8155     }
8156     hci_stack->inquiry_state = duration_in_1280ms_units;
8157     hci_stack->inquiry_max_period_length = 0;
8158     hci_stack->inquiry_min_period_length = 0;
8159     hci_run();
8160     return 0;
8161 }
8162 
8163 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
8164     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
8165     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
8166     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8167     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8168     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8169     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
8170 
8171     hci_stack->inquiry_state = duration;
8172     hci_stack->inquiry_max_period_length = max_period_length;
8173     hci_stack->inquiry_min_period_length = min_period_length;
8174     hci_run();
8175     return 0;
8176 }
8177 
8178 /**
8179  * @brief Stop GAP Classic Inquiry
8180  * @return 0 if ok
8181  */
8182 int gap_inquiry_stop(void){
8183     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
8184         // emit inquiry complete event, before it even started
8185         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
8186         hci_emit_event(event, sizeof(event), 1);
8187         return 0;
8188     }
8189     switch (hci_stack->inquiry_state){
8190         case GAP_INQUIRY_STATE_ACTIVE:
8191             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
8192             hci_run();
8193             return ERROR_CODE_SUCCESS;
8194         case GAP_INQUIRY_STATE_PERIODIC:
8195             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
8196             hci_run();
8197             return ERROR_CODE_SUCCESS;
8198         default:
8199             return ERROR_CODE_COMMAND_DISALLOWED;
8200     }
8201 }
8202 
8203 void gap_inquiry_set_lap(uint32_t lap){
8204     hci_stack->inquiry_lap = lap;
8205 }
8206 
8207 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
8208     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
8209     hci_stack->inquiry_scan_window   = inquiry_scan_window;
8210     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
8211     hci_run();
8212 }
8213 
8214 
8215 /**
8216  * @brief Remote Name Request
8217  * @param addr
8218  * @param page_scan_repetition_mode
8219  * @param clock_offset only used when bit 15 is set
8220  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
8221  */
8222 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
8223     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8224     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
8225     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
8226     hci_stack->remote_name_clock_offset = clock_offset;
8227     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
8228     hci_run();
8229     return 0;
8230 }
8231 
8232 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
8233     hci_stack->gap_pairing_state = state;
8234     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
8235     hci_run();
8236     return 0;
8237 }
8238 
8239 /**
8240  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
8241  * @param addr
8242  * @param pin_data
8243  * @param pin_len
8244  * @return 0 if ok
8245  */
8246 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
8247     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8248     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
8249     hci_stack->gap_pairing_pin_len = pin_len;
8250     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
8251 }
8252 
8253 /**
8254  * @brief Legacy Pairing Pin Code Response
8255  * @param addr
8256  * @param pin
8257  * @return 0 if ok
8258  */
8259 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
8260     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
8261 }
8262 
8263 /**
8264  * @brief Abort Legacy Pairing
8265  * @param addr
8266  * @param pin
8267  * @return 0 if ok
8268  */
8269 int gap_pin_code_negative(bd_addr_t addr){
8270     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8271     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
8272 }
8273 
8274 /**
8275  * @brief SSP Passkey Response
8276  * @param addr
8277  * @param passkey
8278  * @return 0 if ok
8279  */
8280 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
8281     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8282     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
8283     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
8284 }
8285 
8286 /**
8287  * @brief Abort SSP Passkey Entry/Pairing
8288  * @param addr
8289  * @param pin
8290  * @return 0 if ok
8291  */
8292 int gap_ssp_passkey_negative(const bd_addr_t addr){
8293     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8294     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
8295 }
8296 
8297 /**
8298  * @brief Accept SSP Numeric Comparison
8299  * @param addr
8300  * @param passkey
8301  * @return 0 if ok
8302  */
8303 int gap_ssp_confirmation_response(const bd_addr_t addr){
8304     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8305     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
8306 }
8307 
8308 /**
8309  * @brief Abort SSP Numeric Comparison/Pairing
8310  * @param addr
8311  * @param pin
8312  * @return 0 if ok
8313  */
8314 int gap_ssp_confirmation_negative(const bd_addr_t addr){
8315     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8316     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
8317 }
8318 
8319 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
8320 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
8321     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8322     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8323     connectionSetAuthenticationFlags(conn, flag);
8324     hci_run();
8325     return ERROR_CODE_SUCCESS;
8326 }
8327 #endif
8328 
8329 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
8330 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
8331     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
8332 }
8333 
8334 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
8335     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
8336 }
8337 #endif
8338 
8339 #ifdef ENABLE_CLASSIC_PAIRING_OOB
8340 /**
8341  * @brief Report Remote OOB Data
8342  * @param bd_addr
8343  * @param c_192 Simple Pairing Hash C derived from P-192 public key
8344  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
8345  * @param c_256 Simple Pairing Hash C derived from P-256 public key
8346  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
8347  */
8348 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){
8349     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8350     if (connection == NULL) {
8351         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8352     }
8353     connection->classic_oob_c_192 = c_192;
8354     connection->classic_oob_r_192 = r_192;
8355 
8356     // ignore P-256 if not supported by us
8357     if (hci_stack->secure_connections_active){
8358         connection->classic_oob_c_256 = c_256;
8359         connection->classic_oob_r_256 = r_256;
8360     }
8361 
8362     return ERROR_CODE_SUCCESS;
8363 }
8364 /**
8365  * @brief Generate new OOB data
8366  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
8367  */
8368 void gap_ssp_generate_oob_data(void){
8369     hci_stack->classic_read_local_oob_data = true;
8370     hci_run();
8371 }
8372 
8373 #endif
8374 
8375 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
8376 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
8377     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8378     if (connection == NULL) {
8379         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8380     }
8381 
8382     memcpy(connection->link_key, link_key, sizeof(link_key_t));
8383     connection->link_key_type = type;
8384 
8385     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
8386 }
8387 
8388 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
8389 /**
8390  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
8391  * @param inquiry_mode see bluetooth_defines.h
8392  */
8393 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
8394     hci_stack->inquiry_mode = inquiry_mode;
8395 }
8396 
8397 /**
8398  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
8399  */
8400 void hci_set_sco_voice_setting(uint16_t voice_setting){
8401     hci_stack->sco_voice_setting = voice_setting;
8402 }
8403 
8404 /**
8405  * @brief Get SCO Voice Setting
8406  * @return current voice setting
8407  */
8408 uint16_t hci_get_sco_voice_setting(void){
8409     return hci_stack->sco_voice_setting;
8410 }
8411 
8412 static int hci_have_usb_transport(void){
8413     if (!hci_stack->hci_transport) return 0;
8414     const char * transport_name = hci_stack->hci_transport->name;
8415     if (!transport_name) return 0;
8416     return (transport_name[0] == 'H') && (transport_name[1] == '2');
8417 }
8418 
8419 /** @brief Get SCO packet length for current SCO Voice setting
8420  *  @note  Using SCO packets of the exact length is required for USB transfer
8421  *  @return Length of SCO packets in bytes (not audio frames)
8422  */
8423 uint16_t hci_get_sco_packet_length(void){
8424     uint16_t sco_packet_length = 0;
8425 
8426 #ifdef ENABLE_SCO_OVER_HCI
8427     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8428     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8429 
8430     if (hci_have_usb_transport()){
8431         // see Core Spec for H2 USB Transfer.
8432         // 3 byte SCO header + 24 bytes per connection
8433         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
8434         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
8435     } else {
8436         // 3 byte SCO header + SCO packet size over the air (60 bytes)
8437         sco_packet_length = 3 + 60 * multiplier;
8438         // assert that it still fits inside an SCO buffer
8439         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
8440             sco_packet_length = 3 + 60;
8441         }
8442     }
8443 #endif
8444 
8445 #ifdef HAVE_SCO_TRANSPORT
8446     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
8447     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8448     sco_packet_length = 3 + 60 * multiplier;
8449 #endif
8450     return sco_packet_length;
8451 }
8452 
8453 /**
8454 * @brief Sets the master/slave policy
8455 * @param policy (0: attempt to become master, 1: let connecting device decide)
8456 */
8457 void hci_set_master_slave_policy(uint8_t policy){
8458     hci_stack->master_slave_policy = policy;
8459 }
8460 
8461 #endif
8462 
8463 HCI_STATE hci_get_state(void){
8464     return hci_stack->state;
8465 }
8466 
8467 #ifdef ENABLE_CLASSIC
8468 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
8469     hci_stack->gap_classic_accept_callback = accept_callback;
8470 }
8471 #endif
8472 
8473 /**
8474  * @brief Set callback for Bluetooth Hardware Error
8475  */
8476 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
8477     hci_stack->hardware_error_callback = fn;
8478 }
8479 
8480 void hci_disconnect_all(void){
8481     btstack_linked_list_iterator_t it;
8482     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
8483     while (btstack_linked_list_iterator_has_next(&it)){
8484         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
8485         if (con->state == SENT_DISCONNECT) continue;
8486         con->state = SEND_DISCONNECT;
8487     }
8488     hci_run();
8489 }
8490 
8491 uint16_t hci_get_manufacturer(void){
8492     return hci_stack->manufacturer;
8493 }
8494 
8495 #ifdef ENABLE_BLE
8496 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
8497     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
8498     if (!hci_con) return NULL;
8499     return &hci_con->sm_connection;
8500 }
8501 
8502 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
8503 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
8504 #endif
8505 
8506 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
8507     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8508     if (hci_connection == NULL) return 0;
8509     if (hci_is_le_connection(hci_connection)){
8510 #ifdef ENABLE_BLE
8511         sm_connection_t * sm_conn = &hci_connection->sm_connection;
8512         if (sm_conn->sm_connection_encrypted) {
8513             return sm_conn->sm_actual_encryption_key_size;
8514         }
8515 #endif
8516     } else {
8517 #ifdef ENABLE_CLASSIC
8518         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
8519             return hci_connection->encryption_key_size;
8520         }
8521 #endif
8522     }
8523     return 0;
8524 }
8525 
8526 bool gap_authenticated(hci_con_handle_t con_handle){
8527     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8528     if (hci_connection == NULL) return false;
8529 
8530     switch (hci_connection->address_type){
8531 #ifdef ENABLE_BLE
8532         case BD_ADDR_TYPE_LE_PUBLIC:
8533         case BD_ADDR_TYPE_LE_RANDOM:
8534             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
8535             return hci_connection->sm_connection.sm_connection_authenticated != 0;
8536 #endif
8537 #ifdef ENABLE_CLASSIC
8538         case BD_ADDR_TYPE_SCO:
8539         case BD_ADDR_TYPE_ACL:
8540             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
8541 #endif
8542         default:
8543             return false;
8544     }
8545 }
8546 
8547 bool gap_secure_connection(hci_con_handle_t con_handle){
8548     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8549     if (hci_connection == NULL) return 0;
8550 
8551     switch (hci_connection->address_type){
8552 #ifdef ENABLE_BLE
8553         case BD_ADDR_TYPE_LE_PUBLIC:
8554         case BD_ADDR_TYPE_LE_RANDOM:
8555             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
8556             return hci_connection->sm_connection.sm_connection_sc != 0;
8557 #endif
8558 #ifdef ENABLE_CLASSIC
8559         case BD_ADDR_TYPE_SCO:
8560         case BD_ADDR_TYPE_ACL:
8561             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
8562 #endif
8563         default:
8564             return false;
8565     }
8566 }
8567 
8568 bool gap_bonded(hci_con_handle_t con_handle){
8569 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8570 	if (hci_connection == NULL) return 0;
8571 
8572 #ifdef ENABLE_CLASSIC
8573 	link_key_t link_key;
8574 	link_key_type_t link_key_type;
8575 #endif
8576 	switch (hci_connection->address_type){
8577 #ifdef ENABLE_BLE
8578 		case BD_ADDR_TYPE_LE_PUBLIC:
8579 		case BD_ADDR_TYPE_LE_RANDOM:
8580 			return hci_connection->sm_connection.sm_le_db_index >= 0;
8581 #endif
8582 #ifdef ENABLE_CLASSIC
8583 		case BD_ADDR_TYPE_SCO:
8584 		case BD_ADDR_TYPE_ACL:
8585 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
8586 #endif
8587 		default:
8588 			return false;
8589 	}
8590 }
8591 
8592 #ifdef ENABLE_BLE
8593 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
8594     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
8595     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
8596     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
8597     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
8598     return sm_conn->sm_connection_authorization_state;
8599 }
8600 #endif
8601 
8602 #ifdef ENABLE_CLASSIC
8603 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){
8604     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8605     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8606     conn->sniff_min_interval = sniff_min_interval;
8607     conn->sniff_max_interval = sniff_max_interval;
8608     conn->sniff_attempt = sniff_attempt;
8609     conn->sniff_timeout = sniff_timeout;
8610     hci_run();
8611     return 0;
8612 }
8613 
8614 /**
8615  * @brief Exit Sniff mode
8616  * @param con_handle
8617  @ @return 0 if ok
8618  */
8619 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
8620     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8621     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8622     conn->sniff_min_interval = 0xffff;
8623     hci_run();
8624     return 0;
8625 }
8626 
8627 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){
8628     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8629     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8630     conn->sniff_subrating_max_latency = max_latency;
8631     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
8632     conn->sniff_subrating_min_local_timeout = min_local_timeout;
8633     hci_run();
8634     return ERROR_CODE_SUCCESS;
8635 }
8636 
8637 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){
8638     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8639     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8640     conn->qos_service_type = service_type;
8641     conn->qos_token_rate = token_rate;
8642     conn->qos_peak_bandwidth = peak_bandwidth;
8643     conn->qos_latency = latency;
8644     conn->qos_delay_variation = delay_variation;
8645     hci_run();
8646     return ERROR_CODE_SUCCESS;
8647 }
8648 
8649 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
8650     hci_stack->new_page_scan_interval = page_scan_interval;
8651     hci_stack->new_page_scan_window = page_scan_window;
8652     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
8653     hci_run();
8654 }
8655 
8656 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
8657     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
8658     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
8659     hci_run();
8660 }
8661 
8662 void gap_set_page_timeout(uint16_t page_timeout){
8663     hci_stack->page_timeout = page_timeout;
8664     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
8665     hci_run();
8666 }
8667 
8668 #endif
8669 
8670 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
8671 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
8672     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
8673     if (le_device_db_index >= le_device_db_max_count()) return;
8674     uint8_t offset = le_device_db_index >> 3;
8675     uint8_t mask = 1 << (le_device_db_index & 7);
8676     hci_stack->le_resolving_list_add_entries[offset] |= mask;
8677     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
8678     	// note: go back to remove entries, otherwise, a remove + add will skip the add
8679         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
8680     }
8681 }
8682 
8683 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
8684 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
8685 	if (le_device_db_index >= le_device_db_max_count()) return;
8686 	uint8_t offset = le_device_db_index >> 3;
8687 	uint8_t mask = 1 << (le_device_db_index & 7);
8688 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
8689 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
8690 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
8691 	}
8692 }
8693 
8694 uint8_t gap_load_resolving_list_from_le_device_db(void){
8695     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
8696 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
8697 	}
8698 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
8699 		// restart le resolving list update
8700 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
8701 	}
8702 	return ERROR_CODE_SUCCESS;
8703 }
8704 #endif
8705 
8706 #ifdef ENABLE_BLE
8707 #ifdef ENABLE_LE_CENTRAL
8708 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8709 
8710 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8711     // check if already in list
8712     btstack_linked_list_iterator_t it;
8713     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8714     while (btstack_linked_list_iterator_has_next(&it)) {
8715         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
8716         if (entry->sid != advertising_sid) {
8717             continue;
8718         }
8719         if (entry->address_type != address_type) {
8720             continue;
8721         }
8722         if (memcmp(entry->address, address, 6) != 0) {
8723             continue;
8724         }
8725         // disallow if already scheduled to add
8726         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
8727             return ERROR_CODE_COMMAND_DISALLOWED;
8728         }
8729         // still on controller, but scheduled to remove -> re-add
8730         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8731         return ERROR_CODE_SUCCESS;
8732     }
8733     // alloc and add to list
8734     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
8735     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8736     entry->sid = advertising_sid;
8737     entry->address_type = address_type;
8738     (void)memcpy(entry->address, address, 6);
8739     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8740     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
8741     return ERROR_CODE_SUCCESS;
8742 }
8743 
8744 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8745     btstack_linked_list_iterator_t it;
8746     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8747     while (btstack_linked_list_iterator_has_next(&it)){
8748         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8749         if (entry->sid != advertising_sid) {
8750             continue;
8751         }
8752         if (entry->address_type != address_type) {
8753             continue;
8754         }
8755         if (memcmp(entry->address, address, 6) != 0) {
8756             continue;
8757         }
8758         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8759             // remove from controller if already present
8760             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8761         }  else {
8762             // directly remove entry from whitelist
8763             btstack_linked_list_iterator_remove(&it);
8764             btstack_memory_periodic_advertiser_list_entry_free(entry);
8765         }
8766         return ERROR_CODE_SUCCESS;
8767     }
8768     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8769 }
8770 
8771 static void hci_periodic_advertiser_list_clear(void){
8772     btstack_linked_list_iterator_t it;
8773     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8774     while (btstack_linked_list_iterator_has_next(&it)){
8775         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8776         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8777             // remove from controller if already present
8778             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8779             continue;
8780         }
8781         // directly remove entry from whitelist
8782         btstack_linked_list_iterator_remove(&it);
8783         btstack_memory_periodic_advertiser_list_entry_free(entry);
8784     }
8785 }
8786 
8787 // free all entries unconditionally
8788 static void hci_periodic_advertiser_list_free(void){
8789     btstack_linked_list_iterator_t lit;
8790     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
8791     while (btstack_linked_list_iterator_has_next(&lit)){
8792         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
8793         btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
8794         btstack_memory_periodic_advertiser_list_entry_free(entry);
8795     }
8796 }
8797 
8798 uint8_t gap_periodic_advertiser_list_clear(void){
8799     hci_periodic_advertiser_list_clear();
8800     hci_run();
8801     return ERROR_CODE_SUCCESS;
8802 }
8803 
8804 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8805     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
8806     if (status){
8807         return status;
8808     }
8809     hci_run();
8810     return ERROR_CODE_SUCCESS;
8811 }
8812 
8813 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8814     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
8815     if (status){
8816         return status;
8817     }
8818     hci_run();
8819     return ERROR_CODE_SUCCESS;
8820 }
8821 
8822 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
8823                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
8824     // abort if already active
8825     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
8826         return ERROR_CODE_COMMAND_DISALLOWED;
8827     }
8828     // store request
8829     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
8830     hci_stack->le_periodic_sync_options = options;
8831     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
8832     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
8833     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
8834     hci_stack->le_periodic_sync_skip = skip;
8835     hci_stack->le_periodic_sync_timeout = sync_timeout;
8836     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
8837 
8838     hci_run();
8839     return ERROR_CODE_SUCCESS;
8840 }
8841 
8842 uint8_t gap_periodic_advertising_create_sync_cancel(void){
8843     // abort if not requested
8844     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
8845         return ERROR_CODE_COMMAND_DISALLOWED;
8846     }
8847     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
8848     hci_run();
8849     return ERROR_CODE_SUCCESS;
8850 }
8851 
8852 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
8853     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
8854         return ERROR_CODE_COMMAND_DISALLOWED;
8855     }
8856     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
8857     hci_run();
8858     return ERROR_CODE_SUCCESS;
8859 }
8860 
8861 #endif
8862 #endif
8863 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
8864 static uint8_t hci_iso_stream_create(hci_con_handle_t con_handle, uint8_t big_handle) {
8865     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
8866     if (iso_stream == NULL){
8867         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8868     } else {
8869         iso_stream->state = HCI_ISO_STREAM_STATE_REQUESTED;
8870         iso_stream->con_handle = con_handle;
8871         iso_stream->big_handle = big_handle;
8872         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
8873         return ERROR_CODE_SUCCESS;
8874     }
8875 }
8876 
8877 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
8878     btstack_linked_list_iterator_t it;
8879     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
8880     while (btstack_linked_list_iterator_has_next(&it)){
8881         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
8882         if (iso_stream->con_handle == con_handle ) {
8883             return iso_stream;
8884         }
8885     }
8886     return NULL;
8887 }
8888 
8889 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
8890     log_info("hci_iso_stream_finalize con_handle 0x%04x, big_handle 0x%02x", iso_stream->con_handle, iso_stream->big_handle);
8891     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
8892     btstack_memory_hci_iso_stream_free(iso_stream);
8893 }
8894 
8895 static void hci_iso_stream_requested_finalize(uint8_t big_handle) {
8896     btstack_linked_list_iterator_t it;
8897     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
8898     while (btstack_linked_list_iterator_has_next(&it)){
8899         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
8900         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
8901             (iso_stream->big_handle == big_handle)){
8902             btstack_linked_list_iterator_remove(&it);
8903             btstack_memory_hci_iso_stream_free(iso_stream);
8904         }
8905     }
8906 }
8907 static void hci_iso_stream_requested_confirm(uint8_t big_handle){
8908     btstack_linked_list_iterator_t it;
8909     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
8910     while (btstack_linked_list_iterator_has_next(&it)){
8911         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
8912         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
8913             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
8914         }
8915     }
8916 }
8917 
8918 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
8919     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
8920     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
8921     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
8922     return (sdu_len_offset + 2 + sdu_len) == size;
8923 }
8924 
8925 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){
8926     if (hci_stack->iso_packet_handler == NULL) {
8927         return;
8928     }
8929     if (size < 4) {
8930         return;
8931     }
8932 
8933     // parse header
8934     uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0);
8935     uint16_t iso_data_len = little_endian_read_16(packet, 2);
8936     hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff);
8937     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
8938     uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3;
8939 
8940     // assert packet is complete
8941     if ((iso_data_len + 4u) != size){
8942         return;
8943     }
8944 
8945     if ((pb_flag & 0x01) == 0){
8946         if (pb_flag == 0x02){
8947             // The ISO_Data_Load field contains a header and a complete SDU.
8948             if (hci_iso_sdu_complete(packet, size)) {
8949                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
8950             }
8951         } else {
8952             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
8953             if (iso_stream == NULL){
8954                 return;
8955             }
8956             if (size > HCI_ISO_PAYLOAD_SIZE){
8957                 return;
8958             }
8959             memcpy(iso_stream->reassembly_buffer, packet, size);
8960             // fix pb_flag
8961             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
8962             iso_stream->reassembly_pos = size;
8963         }
8964     } else {
8965         // iso_data_load contains continuation or last fragment of an SDU
8966         uint8_t  ts_flag = (conn_handle_and_flags >> 14) & 1;
8967         if (ts_flag != 0){
8968            return;
8969         }
8970         // append fragment
8971         if (iso_stream == NULL){
8972             return;
8973         }
8974         if (iso_stream->reassembly_pos == 0){
8975             return;
8976         }
8977         if ((iso_stream->reassembly_pos + iso_data_len) > size){
8978             // reset reassembly buffer
8979             iso_stream->reassembly_pos = 0;
8980             return;
8981         }
8982         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len);
8983         iso_stream->reassembly_pos += iso_data_len;
8984 
8985         // deliver if last fragment and SDU complete
8986         if (pb_flag == 0x03){
8987             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
8988                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
8989             }
8990             iso_stream->reassembly_pos = 0;
8991         }
8992     }
8993 }
8994 
8995 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
8996     uint8_t event [6 + (MAX_NR_BIS * 2)];
8997     uint16_t pos = 0;
8998     event[pos++] = HCI_EVENT_META_GAP;
8999     event[pos++] = 4 + (2 * big->num_bis);
9000     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
9001     event[pos++] = status;
9002     event[pos++] = big->big_handle;
9003     event[pos++] = big->num_bis;
9004     uint8_t i;
9005     for (i=0;i<big->num_bis;i++){
9006         little_endian_store_16(event, pos, big->bis_con_handles[i]);
9007         pos += 2;
9008     }
9009     hci_emit_event(event, pos, 0);
9010 }
9011 
9012 static void hci_emit_big_terminated(const le_audio_big_t * big){
9013     uint8_t event [4];
9014     uint16_t pos = 0;
9015     event[pos++] = HCI_EVENT_META_GAP;
9016     event[pos++] = 2;
9017     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
9018     event[pos++] = big->big_handle;
9019     hci_emit_event(event, pos, 0);
9020 }
9021 
9022 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
9023     uint8_t event [6 + (MAX_NR_BIS * 2)];
9024     uint16_t pos = 0;
9025     event[pos++] = HCI_EVENT_META_GAP;
9026     event[pos++] = 4;
9027     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
9028     event[pos++] = status;
9029     event[pos++] = big_sync->big_handle;
9030     event[pos++] = big_sync->num_bis;
9031     uint8_t i;
9032     for (i=0;i<big_sync->num_bis;i++){
9033         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
9034         pos += 2;
9035     }
9036     hci_emit_event(event, pos, 0);
9037 }
9038 
9039 static void hci_emit_big_sync_stopped(const le_audio_big_sync_t * big_sync){
9040     uint8_t event [4];
9041     uint16_t pos = 0;
9042     event[pos++] = HCI_EVENT_META_GAP;
9043     event[pos++] = 2;
9044     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
9045     event[pos++] = big_sync->big_handle;
9046     hci_emit_event(event, pos, 0);
9047 }
9048 
9049 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
9050     uint8_t event[6];
9051     uint16_t pos = 0;
9052     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
9053     event[pos++] = sizeof(event) - 2;
9054     event[pos++] = big->big_handle;
9055     event[pos++] = bis_index;
9056     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
9057     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
9058 }
9059 
9060 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
9061     btstack_linked_list_iterator_t it;
9062     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9063     while (btstack_linked_list_iterator_has_next(&it)){
9064         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9065         if ( big->big_handle == big_handle ) {
9066             return big;
9067         }
9068     }
9069     return NULL;
9070 }
9071 
9072 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
9073     btstack_linked_list_iterator_t it;
9074     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
9075     while (btstack_linked_list_iterator_has_next(&it)){
9076         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
9077         if ( big_sync->big_handle == big_handle ) {
9078             return big_sync;
9079         }
9080     }
9081     return NULL;
9082 }
9083 
9084 static void hci_iso_notify_can_send_now(void){
9085     btstack_linked_list_iterator_t it;
9086     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9087     while (btstack_linked_list_iterator_has_next(&it)){
9088         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9089         if (big->can_send_now_requested){
9090             // check if no outgoing iso packets pending
9091             uint8_t i;
9092             bool can_send = true;
9093             for (i=0;i<big->num_bis;i++){
9094                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9095                 if ((iso_stream == NULL) || (iso_stream->num_packets_sent > 0)){
9096                     can_send = false;
9097                     break;
9098                 }
9099             }
9100             if (can_send){
9101                 // propagate can send now to individual streams
9102                 big->can_send_now_requested = false;
9103                 for (i=0;i<big->num_bis;i++){
9104                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9105                     iso_stream->emit_ready_to_send = true;
9106                 }
9107             }
9108         }
9109     }
9110 
9111     if (hci_stack->hci_packet_buffer_reserved) return;
9112 
9113     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9114     while (btstack_linked_list_iterator_has_next(&it)){
9115         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9116         // report bis ready
9117         uint8_t i;
9118         bool can_send = true;
9119         for (i=0;i<big->num_bis;i++){
9120             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9121             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
9122                 iso_stream->emit_ready_to_send = false;
9123                 hci_emit_bis_can_send_now(big, i);
9124                 break;
9125             }
9126         }
9127     }
9128 }
9129 
9130 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
9131     if (hci_big_for_handle(big_params->big_handle) != NULL){
9132         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9133     }
9134     if (big_params->num_bis == 0){
9135         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9136     }
9137     if (big_params->num_bis > MAX_NR_BIS){
9138         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9139     }
9140 
9141     // reserve ISO Streams
9142     uint8_t i;
9143     uint8_t status = ERROR_CODE_SUCCESS;
9144     for (i=0;i<big_params->num_bis;i++){
9145         status = hci_iso_stream_create(HCI_CON_HANDLE_INVALID, big_params->big_handle);
9146         if (status != ERROR_CODE_SUCCESS) {
9147             break;
9148         }
9149     }
9150 
9151     // free structs on error
9152     if (status != ERROR_CODE_SUCCESS){
9153         hci_iso_stream_requested_finalize(big_params->big_handle);
9154         return status;
9155     }
9156 
9157     le_audio_big_t * big = storage;
9158     big->big_handle = big_params->big_handle;
9159     big->params = big_params;
9160     big->state = LE_AUDIO_BIG_STATE_CREATE;
9161     big->num_bis = big_params->num_bis;
9162     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9163 
9164     hci_run();
9165 
9166     return ERROR_CODE_SUCCESS;
9167 }
9168 
9169 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
9170     if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){
9171         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9172     }
9173     if (big_sync_params->num_bis == 0){
9174         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9175     }
9176     if (big_sync_params->num_bis > MAX_NR_BIS){
9177         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9178     }
9179 
9180     le_audio_big_sync_t * big_sync = storage;
9181     big_sync->big_handle = big_sync_params->big_handle;
9182     big_sync->params = big_sync_params;
9183     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
9184     big_sync->num_bis = big_sync_params->num_bis;
9185     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9186 
9187     hci_run();
9188 
9189     return ERROR_CODE_SUCCESS;
9190 }
9191 
9192 uint8_t gap_big_terminate(uint8_t big_handle){
9193     le_audio_big_t * big = hci_big_for_handle(big_handle);
9194     if (big == NULL){
9195         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9196     }
9197     switch (big->state){
9198         case LE_AUDIO_BIG_STATE_CREATE:
9199             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9200             hci_emit_big_terminated(big);
9201             break;
9202         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9203             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9204             break;
9205         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9206         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9207         case LE_AUDIO_BIG_STATE_ACTIVE:
9208             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
9209             hci_run();
9210             break;
9211         default:
9212             return ERROR_CODE_COMMAND_DISALLOWED;
9213     }
9214     return ERROR_CODE_SUCCESS;
9215 }
9216 
9217 uint8_t gap_big_sync_terminate(uint8_t big_handle){
9218     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
9219     if (big_sync == NULL){
9220         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9221     }
9222     switch (big_sync->state){
9223         case LE_AUDIO_BIG_STATE_CREATE:
9224             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9225             hci_emit_big_sync_stopped(big_sync);
9226             break;
9227         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9228             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9229             break;
9230         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9231         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9232         case LE_AUDIO_BIG_STATE_ACTIVE:
9233             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
9234             hci_run();
9235             break;
9236         default:
9237             return ERROR_CODE_COMMAND_DISALLOWED;
9238     }
9239     return ERROR_CODE_SUCCESS;
9240 }
9241 
9242 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
9243     le_audio_big_t * big = hci_big_for_handle(big_handle);
9244     if (big == NULL){
9245         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9246     }
9247     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
9248         return ERROR_CODE_COMMAND_DISALLOWED;
9249     }
9250     big->can_send_now_requested = true;
9251     hci_iso_notify_can_send_now();
9252     return ERROR_CODE_SUCCESS;
9253 }
9254 #endif
9255 #endif /* ENABLE_BLE */
9256 
9257 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
9258 void hci_setup_test_connections_fuzz(void){
9259     hci_connection_t * conn;
9260 
9261     // default address: 66:55:44:33:00:01
9262     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
9263 
9264     // setup Controller info
9265     hci_stack->num_cmd_packets = 255;
9266     hci_stack->acl_packets_total_num = 255;
9267 
9268     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
9269     addr[5] = 0x01;
9270     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9271     conn->con_handle = addr[5];
9272     conn->role  = HCI_ROLE_SLAVE;
9273     conn->state = RECEIVED_CONNECTION_REQUEST;
9274     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9275 
9276     // setup incoming Classic SCO connection with con handle 0x0002
9277     addr[5] = 0x02;
9278     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9279     conn->con_handle = addr[5];
9280     conn->role  = HCI_ROLE_SLAVE;
9281     conn->state = RECEIVED_CONNECTION_REQUEST;
9282     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9283 
9284     // setup ready Classic ACL connection with con handle 0x0003
9285     addr[5] = 0x03;
9286     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9287     conn->con_handle = addr[5];
9288     conn->role  = HCI_ROLE_SLAVE;
9289     conn->state = OPEN;
9290     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9291 
9292     // setup ready Classic SCO connection with con handle 0x0004
9293     addr[5] = 0x04;
9294     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9295     conn->con_handle = addr[5];
9296     conn->role  = HCI_ROLE_SLAVE;
9297     conn->state = OPEN;
9298     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9299 
9300     // setup ready LE ACL connection with con handle 0x005 and public address
9301     addr[5] = 0x05;
9302     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
9303     conn->con_handle = addr[5];
9304     conn->role  = HCI_ROLE_SLAVE;
9305     conn->state = OPEN;
9306     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9307     conn->sm_connection.sm_connection_encrypted = 1;
9308 }
9309 
9310 void hci_free_connections_fuzz(void){
9311     btstack_linked_list_iterator_t it;
9312     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9313     while (btstack_linked_list_iterator_has_next(&it)){
9314         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9315         btstack_linked_list_iterator_remove(&it);
9316         btstack_memory_hci_connection_free(con);
9317     }
9318 }
9319 void hci_simulate_working_fuzz(void){
9320     hci_stack->le_scanning_param_update = false;
9321     hci_init_done();
9322     hci_stack->num_cmd_packets = 255;
9323 }
9324 #endif
9325