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