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