xref: /btstack/src/hci.c (revision 4bafedd52103e8739fbbd6cc9fcc8421fb02ce73)
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 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3796     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
3797 #endif
3798 #endif
3799 #ifdef ENABLE_LE_PERIPHERAL
3800     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
3801     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
3802         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3803     }
3804     if (hci_stack->le_advertisements_data != NULL){
3805         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3806     }
3807 #endif
3808 }
3809 
3810 #ifdef ENABLE_CLASSIC
3811 /**
3812  * @brief Configure Bluetooth hardware control. Has to be called before power on.
3813  */
3814 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
3815     // store and open remote device db
3816     hci_stack->link_key_db = link_key_db;
3817     if (hci_stack->link_key_db) {
3818         hci_stack->link_key_db->open();
3819     }
3820 }
3821 #endif
3822 
3823 void hci_init(const hci_transport_t *transport, const void *config){
3824 
3825 #ifdef HAVE_MALLOC
3826     if (!hci_stack) {
3827         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
3828     }
3829 #else
3830     hci_stack = &hci_stack_static;
3831 #endif
3832     memset(hci_stack, 0, sizeof(hci_stack_t));
3833 
3834     // reference to use transport layer implementation
3835     hci_stack->hci_transport = transport;
3836 
3837     // reference to used config
3838     hci_stack->config = config;
3839 
3840     // setup pointer for outgoing packet buffer
3841     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
3842 
3843     // max acl payload size defined in config.h
3844     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
3845 
3846     // register packet handlers with transport
3847     transport->register_packet_handler(&packet_handler);
3848 
3849     hci_stack->state = HCI_STATE_OFF;
3850 
3851     // class of device
3852     hci_stack->class_of_device = 0x007a020c; // Smartphone
3853 
3854     // bondable by default
3855     hci_stack->bondable = 1;
3856 
3857 #ifdef ENABLE_CLASSIC
3858     // classic name
3859     hci_stack->local_name = default_classic_name;
3860 
3861     // Master slave policy
3862     hci_stack->master_slave_policy = 1;
3863 
3864     // Allow Role Switch
3865     hci_stack->allow_role_switch = 1;
3866 
3867     // Default / minimum security level = 2
3868     hci_stack->gap_security_level = LEVEL_2;
3869 
3870     // Default Security Mode 4
3871     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
3872 
3873     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3874     hci_stack->gap_required_encyrption_key_size = 7;
3875 
3876     // Link Supervision Timeout
3877     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
3878 
3879 #endif
3880 
3881     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
3882     hci_stack->ssp_enable = 1;
3883     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
3884     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
3885     hci_stack->ssp_auto_accept = 1;
3886 
3887     // Secure Connections: enable (requires support from Controller)
3888     hci_stack->secure_connections_enable = true;
3889 
3890     // voice setting - signed 16 bit pcm data with CVSD over the air
3891     hci_stack->sco_voice_setting = 0x60;
3892 
3893 #ifdef ENABLE_LE_CENTRAL
3894     // connection parameter to use for outgoing connections
3895     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3896     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3897     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3898     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3899     hci_stack->le_connection_latency      = 4;         // 4
3900     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3901     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3902     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
3903 
3904     // default LE Scanning
3905     hci_stack->le_scan_type     =   0x1; // active
3906     hci_stack->le_scan_interval = 0x1e0; // 300 ms
3907     hci_stack->le_scan_window   =  0x30; //  30 ms
3908 #endif
3909 
3910 #ifdef ENABLE_LE_PERIPHERAL
3911     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
3912 #endif
3913 
3914     // connection parameter range used to answer connection parameter update requests in l2cap
3915     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3916     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3917     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3918     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3919     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3920     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3921 
3922     hci_state_reset();
3923 }
3924 
3925 void hci_deinit(void){
3926     btstack_run_loop_remove_timer(&hci_stack->timeout);
3927 #ifdef HAVE_MALLOC
3928     if (hci_stack) {
3929         free(hci_stack);
3930     }
3931 #endif
3932     hci_stack = NULL;
3933 
3934 #ifdef ENABLE_CLASSIC
3935     disable_l2cap_timeouts = 0;
3936 #endif
3937 }
3938 
3939 /**
3940  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
3941  */
3942 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
3943     hci_stack->chipset = chipset_driver;
3944 
3945     // reset chipset driver - init is also called on power_up
3946     if (hci_stack->chipset && hci_stack->chipset->init){
3947         hci_stack->chipset->init(hci_stack->config);
3948     }
3949 }
3950 
3951 /**
3952  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3953  */
3954 void hci_set_control(const btstack_control_t *hardware_control){
3955     // references to used control implementation
3956     hci_stack->control = hardware_control;
3957     // init with transport config
3958     hardware_control->init(hci_stack->config);
3959 }
3960 
3961 static void hci_discard_connections(void){
3962     btstack_linked_list_iterator_t lit;
3963     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
3964     while (btstack_linked_list_iterator_has_next(&lit)){
3965         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
3966         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
3967         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
3968         hci_shutdown_connection(connection);
3969     }
3970 }
3971 
3972 void hci_close(void){
3973 
3974 #ifdef ENABLE_CLASSIC
3975     // close remote device db
3976     if (hci_stack->link_key_db) {
3977         hci_stack->link_key_db->close();
3978     }
3979 #endif
3980 
3981     hci_discard_connections();
3982 
3983     hci_power_control(HCI_POWER_OFF);
3984 
3985 #ifdef HAVE_MALLOC
3986     free(hci_stack);
3987 #endif
3988     hci_stack = NULL;
3989 }
3990 
3991 #ifdef HAVE_SCO_TRANSPORT
3992 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3993     hci_stack->sco_transport = sco_transport;
3994     sco_transport->register_packet_handler(&packet_handler);
3995 }
3996 #endif
3997 
3998 #ifdef ENABLE_CLASSIC
3999 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
4000     // validate ranage and set
4001     if (encryption_key_size < 7)  return;
4002     if (encryption_key_size > 16) return;
4003     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
4004 }
4005 
4006 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
4007     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
4008         hci_stack->gap_security_mode = security_mode;
4009         return ERROR_CODE_SUCCESS;
4010     } else {
4011         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
4012     }
4013 }
4014 
4015 gap_security_mode_t gap_get_security_mode(void){
4016     return hci_stack->gap_security_mode;
4017 }
4018 
4019 void gap_set_security_level(gap_security_level_t security_level){
4020     hci_stack->gap_security_level = security_level;
4021 }
4022 
4023 gap_security_level_t gap_get_security_level(void){
4024     if (hci_stack->gap_secure_connections_only_mode){
4025         return LEVEL_4;
4026     }
4027     return hci_stack->gap_security_level;
4028 }
4029 
4030 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
4031     hci_stack->gap_minimal_service_security_level = security_level;
4032 }
4033 
4034 void gap_set_secure_connections_only_mode(bool enable){
4035     hci_stack->gap_secure_connections_only_mode = enable;
4036 }
4037 
4038 bool gap_get_secure_connections_only_mode(void){
4039     return hci_stack->gap_secure_connections_only_mode;
4040 }
4041 #endif
4042 
4043 #ifdef ENABLE_CLASSIC
4044 void gap_set_class_of_device(uint32_t class_of_device){
4045     hci_stack->class_of_device = class_of_device;
4046     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
4047     hci_run();
4048 }
4049 
4050 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4051     hci_stack->default_link_policy_settings = default_link_policy_settings;
4052     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
4053     hci_run();
4054 }
4055 
4056 void gap_set_allow_role_switch(bool allow_role_switch){
4057     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4058 }
4059 
4060 uint8_t hci_get_allow_role_switch(void){
4061     return  hci_stack->allow_role_switch;
4062 }
4063 
4064 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
4065     hci_stack->link_supervision_timeout = link_supervision_timeout;
4066 }
4067 
4068 void gap_enable_link_watchdog(uint16_t timeout_ms){
4069     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
4070 }
4071 
4072 uint16_t hci_automatic_flush_timeout(void){
4073     return hci_stack->automatic_flush_timeout;
4074 }
4075 
4076 void hci_disable_l2cap_timeout_check(void){
4077     disable_l2cap_timeouts = 1;
4078 }
4079 #endif
4080 
4081 #ifndef HAVE_HOST_CONTROLLER_API
4082 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4083 void hci_set_bd_addr(bd_addr_t addr){
4084     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4085     hci_stack->custom_bd_addr_set = 1;
4086 }
4087 #endif
4088 
4089 // State-Module-Driver overview
4090 // state                    module  low-level
4091 // HCI_STATE_OFF             off      close
4092 // HCI_STATE_INITIALIZING,   on       open
4093 // HCI_STATE_WORKING,        on       open
4094 // HCI_STATE_HALTING,        on       open
4095 // HCI_STATE_SLEEPING,    off/sleep   close
4096 // HCI_STATE_FALLING_ASLEEP  on       open
4097 
4098 static int hci_power_control_on(void){
4099 
4100     // power on
4101     int err = 0;
4102     if (hci_stack->control && hci_stack->control->on){
4103         err = (*hci_stack->control->on)();
4104     }
4105     if (err){
4106         log_error( "POWER_ON failed");
4107         hci_emit_hci_open_failed();
4108         return err;
4109     }
4110 
4111     // int chipset driver
4112     if (hci_stack->chipset && hci_stack->chipset->init){
4113         hci_stack->chipset->init(hci_stack->config);
4114     }
4115 
4116     // init transport
4117     if (hci_stack->hci_transport->init){
4118         hci_stack->hci_transport->init(hci_stack->config);
4119     }
4120 
4121     // open transport
4122     err = hci_stack->hci_transport->open();
4123     if (err){
4124         log_error( "HCI_INIT failed, turning Bluetooth off again");
4125         if (hci_stack->control && hci_stack->control->off){
4126             (*hci_stack->control->off)();
4127         }
4128         hci_emit_hci_open_failed();
4129         return err;
4130     }
4131     return 0;
4132 }
4133 
4134 static void hci_power_control_off(void){
4135 
4136     log_info("hci_power_control_off");
4137 
4138     // close low-level device
4139     hci_stack->hci_transport->close();
4140 
4141     log_info("hci_power_control_off - hci_transport closed");
4142 
4143     // power off
4144     if (hci_stack->control && hci_stack->control->off){
4145         (*hci_stack->control->off)();
4146     }
4147 
4148     log_info("hci_power_control_off - control closed");
4149 
4150     hci_stack->state = HCI_STATE_OFF;
4151 }
4152 
4153 static void hci_power_control_sleep(void){
4154 
4155     log_info("hci_power_control_sleep");
4156 
4157 #if 0
4158     // don't close serial port during sleep
4159 
4160     // close low-level device
4161     hci_stack->hci_transport->close(hci_stack->config);
4162 #endif
4163 
4164     // sleep mode
4165     if (hci_stack->control && hci_stack->control->sleep){
4166         (*hci_stack->control->sleep)();
4167     }
4168 
4169     hci_stack->state = HCI_STATE_SLEEPING;
4170 }
4171 
4172 static int hci_power_control_wake(void){
4173 
4174     log_info("hci_power_control_wake");
4175 
4176     // wake on
4177     if (hci_stack->control && hci_stack->control->wake){
4178         (*hci_stack->control->wake)();
4179     }
4180 
4181 #if 0
4182     // open low-level device
4183     int err = hci_stack->hci_transport->open(hci_stack->config);
4184     if (err){
4185         log_error( "HCI_INIT failed, turning Bluetooth off again");
4186         if (hci_stack->control && hci_stack->control->off){
4187             (*hci_stack->control->off)();
4188         }
4189         hci_emit_hci_open_failed();
4190         return err;
4191     }
4192 #endif
4193 
4194     return 0;
4195 }
4196 
4197 static void hci_power_enter_initializing_state(void){
4198     // set up state machine
4199     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
4200     hci_stack->hci_packet_buffer_reserved = false;
4201     hci_stack->state = HCI_STATE_INITIALIZING;
4202     hci_stack->substate = HCI_INIT_SEND_RESET;
4203 }
4204 
4205 static void hci_power_enter_halting_state(void){
4206 #ifdef ENABLE_BLE
4207     hci_whitelist_free();
4208 #endif
4209     // see hci_run
4210     hci_stack->state = HCI_STATE_HALTING;
4211     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
4212     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
4213     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
4214     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4215     btstack_run_loop_add_timer(&hci_stack->timeout);
4216 }
4217 
4218 // returns error
4219 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
4220     int err;
4221     switch (power_mode){
4222         case HCI_POWER_ON:
4223             err = hci_power_control_on();
4224             if (err != 0) {
4225                 log_error("hci_power_control_on() error %d", err);
4226                 return err;
4227             }
4228             hci_power_enter_initializing_state();
4229             break;
4230         case HCI_POWER_OFF:
4231             // do nothing
4232             break;
4233         case HCI_POWER_SLEEP:
4234             // do nothing (with SLEEP == OFF)
4235             break;
4236         default:
4237             btstack_assert(false);
4238             break;
4239     }
4240     return ERROR_CODE_SUCCESS;
4241 }
4242 
4243 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
4244     switch (power_mode){
4245         case HCI_POWER_ON:
4246             // do nothing
4247             break;
4248         case HCI_POWER_OFF:
4249             // no connections yet, just turn it off
4250             hci_power_control_off();
4251             break;
4252         case HCI_POWER_SLEEP:
4253             // no connections yet, just turn it off
4254             hci_power_control_sleep();
4255             break;
4256         default:
4257             btstack_assert(false);
4258             break;
4259     }
4260     return ERROR_CODE_SUCCESS;
4261 }
4262 
4263 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
4264     switch (power_mode){
4265         case HCI_POWER_ON:
4266             // do nothing
4267             break;
4268         case HCI_POWER_OFF:
4269             hci_power_enter_halting_state();
4270             break;
4271         case HCI_POWER_SLEEP:
4272             // see hci_run
4273             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4274             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4275             break;
4276         default:
4277             btstack_assert(false);
4278             break;
4279     }
4280     return ERROR_CODE_SUCCESS;
4281 }
4282 
4283 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
4284     switch (power_mode){
4285         case HCI_POWER_ON:
4286             hci_power_enter_initializing_state();
4287             break;
4288         case HCI_POWER_OFF:
4289             // do nothing
4290             break;
4291         case HCI_POWER_SLEEP:
4292             // see hci_run
4293             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4294             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4295             break;
4296         default:
4297             btstack_assert(false);
4298             break;
4299     }
4300     return ERROR_CODE_SUCCESS;
4301 }
4302 
4303 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
4304     switch (power_mode){
4305         case HCI_POWER_ON:
4306             hci_power_enter_initializing_state();
4307             break;
4308         case HCI_POWER_OFF:
4309             hci_power_enter_halting_state();
4310             break;
4311         case HCI_POWER_SLEEP:
4312             // do nothing
4313             break;
4314         default:
4315             btstack_assert(false);
4316             break;
4317     }
4318     return ERROR_CODE_SUCCESS;
4319 }
4320 
4321 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
4322     int err;
4323     switch (power_mode){
4324         case HCI_POWER_ON:
4325             err = hci_power_control_wake();
4326             if (err) return err;
4327             hci_power_enter_initializing_state();
4328             break;
4329         case HCI_POWER_OFF:
4330             hci_power_enter_halting_state();
4331             break;
4332         case HCI_POWER_SLEEP:
4333             // do nothing
4334             break;
4335         default:
4336             btstack_assert(false);
4337             break;
4338     }
4339     return ERROR_CODE_SUCCESS;
4340 }
4341 
4342 int hci_power_control(HCI_POWER_MODE power_mode){
4343     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
4344     int err = 0;
4345     switch (hci_stack->state){
4346         case HCI_STATE_OFF:
4347             err = hci_power_control_state_off(power_mode);
4348             break;
4349         case HCI_STATE_INITIALIZING:
4350             err = hci_power_control_state_initializing(power_mode);
4351             break;
4352         case HCI_STATE_WORKING:
4353             err = hci_power_control_state_working(power_mode);
4354             break;
4355         case HCI_STATE_HALTING:
4356             err = hci_power_control_state_halting(power_mode);
4357             break;
4358         case HCI_STATE_FALLING_ASLEEP:
4359             err = hci_power_control_state_falling_asleep(power_mode);
4360             break;
4361         case HCI_STATE_SLEEPING:
4362             err = hci_power_control_state_sleeping(power_mode);
4363             break;
4364         default:
4365             btstack_assert(false);
4366             break;
4367     }
4368     if (err != 0){
4369         return err;
4370     }
4371 
4372     // create internal event
4373 	hci_emit_state();
4374 
4375 	// trigger next/first action
4376 	hci_run();
4377 
4378     return 0;
4379 }
4380 
4381 
4382 static void hci_halting_run(void) {
4383 
4384     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4385 
4386     hci_connection_t *connection;
4387 #ifdef ENABLE_BLE
4388 #ifdef ENABLE_LE_PERIPHERAL
4389     bool stop_advertismenets;
4390 #endif
4391 #endif
4392 
4393     switch (hci_stack->substate) {
4394         case HCI_HALTING_CLASSIC_STOP:
4395 #ifdef ENABLE_CLASSIC
4396             if (!hci_can_send_command_packet_now()) return;
4397 
4398             if (hci_stack->connectable || hci_stack->discoverable){
4399                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4400                 hci_send_cmd(&hci_write_scan_enable, 0);
4401                 return;
4402             }
4403 #endif
4404             /* fall through */
4405 
4406         case HCI_HALTING_LE_ADV_STOP:
4407             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4408 
4409 #ifdef ENABLE_BLE
4410 #ifdef ENABLE_LE_PERIPHERAL
4411             if (!hci_can_send_command_packet_now()) return;
4412 
4413             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
4414 
4415 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4416             if (hci_extended_advertising_supported()){
4417 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4418                 btstack_linked_list_iterator_t it;
4419                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4420                 // stop all periodic advertisements and check if an extended set is active
4421                 while (btstack_linked_list_iterator_has_next(&it)){
4422                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4423                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
4424                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
4425                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
4426                         return;
4427                     }
4428                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
4429                         stop_advertismenets = true;
4430                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4431                     }
4432                 }
4433 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
4434                 if (stop_advertismenets){
4435                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4436                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
4437                     return;
4438                 }
4439             }
4440             else
4441 #else
4442             {
4443                 if (stop_advertismenets) {
4444                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4445                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
4446                     return;
4447                 }
4448             }
4449 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
4450 #endif  /* ENABLE_LE_PERIPHERAL */
4451 #endif  /* ENABLE_BLE */
4452 
4453             /* fall through */
4454 
4455         case HCI_HALTING_LE_SCAN_STOP:
4456             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
4457             if (!hci_can_send_command_packet_now()) return;
4458 
4459 #ifdef ENABLE_BLE
4460 #ifdef ENABLE_LE_CENTRAL
4461             if (hci_stack->le_scanning_active){
4462                 hci_le_scan_stop();
4463                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4464                 return;
4465             }
4466 #endif
4467 #endif
4468 
4469             /* fall through */
4470 
4471         case HCI_HALTING_DISCONNECT_ALL:
4472             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4473             if (!hci_can_send_command_packet_now()) return;
4474 
4475             // close all open connections
4476             connection = (hci_connection_t *) hci_stack->connections;
4477             if (connection) {
4478                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4479 
4480                 // check state
4481                 if (connection->state == SENT_DISCONNECT) return;
4482                 connection->state = SENT_DISCONNECT;
4483 
4484                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4485 
4486                 // finally, send the disconnect command
4487                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4488                 return;
4489             }
4490 
4491             btstack_run_loop_remove_timer(&hci_stack->timeout);
4492 
4493             hci_stack->substate = HCI_HALTING_READY_FOR_CLOSE;
4494 
4495             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4496             log_info("HCI_STATE_HALTING: wait 50 ms");
4497             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
4498             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
4499             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4500             btstack_run_loop_add_timer(&hci_stack->timeout);
4501             break;
4502 
4503         case HCI_HALTING_CLOSE:
4504             // close left over connections (that had not been properly closed before)
4505             hci_discard_connections();
4506 
4507             log_info("HCI_STATE_HALTING, calling off");
4508 
4509             // switch mode
4510             hci_power_control_off();
4511 
4512             log_info("HCI_STATE_HALTING, emitting state");
4513             hci_emit_state();
4514             log_info("HCI_STATE_HALTING, done");
4515             break;
4516 
4517         case HCI_HALTING_W4_CLOSE_TIMER:
4518             // keep waiting
4519 
4520             break;
4521         default:
4522             break;
4523     }
4524 };
4525 
4526 static void hci_falling_asleep_run(void){
4527     hci_connection_t * connection;
4528     switch(hci_stack->substate) {
4529         case HCI_FALLING_ASLEEP_DISCONNECT:
4530             log_info("HCI_STATE_FALLING_ASLEEP");
4531             // close all open connections
4532             connection =  (hci_connection_t *) hci_stack->connections;
4533             if (connection){
4534 
4535                 // send disconnect
4536                 if (!hci_can_send_command_packet_now()) return;
4537 
4538                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
4539                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4540 
4541                 // send disconnected event right away - causes higher layer connections to get closed, too.
4542                 hci_shutdown_connection(connection);
4543                 return;
4544             }
4545 
4546             if (hci_classic_supported()){
4547                 // disable page and inquiry scan
4548                 if (!hci_can_send_command_packet_now()) return;
4549 
4550                 log_info("HCI_STATE_HALTING, disabling inq scans");
4551                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
4552 
4553                 // continue in next sub state
4554                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
4555                 break;
4556             }
4557 
4558             /* fall through */
4559 
4560             case HCI_FALLING_ASLEEP_COMPLETE:
4561                 log_info("HCI_STATE_HALTING, calling sleep");
4562                 // switch mode
4563                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
4564                 hci_emit_state();
4565                 break;
4566 
4567                 default:
4568                     break;
4569     }
4570 }
4571 
4572 #ifdef ENABLE_CLASSIC
4573 
4574 static void hci_update_scan_enable(void){
4575     // 2 = page scan, 1 = inq scan
4576     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
4577     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
4578     hci_run();
4579 }
4580 
4581 void gap_discoverable_control(uint8_t enable){
4582     if (enable) enable = 1; // normalize argument
4583 
4584     if (hci_stack->discoverable == enable){
4585         hci_emit_discoverable_enabled(hci_stack->discoverable);
4586         return;
4587     }
4588 
4589     hci_stack->discoverable = enable;
4590     hci_update_scan_enable();
4591 }
4592 
4593 void gap_connectable_control(uint8_t enable){
4594     if (enable) enable = 1; // normalize argument
4595 
4596     // don't emit event
4597     if (hci_stack->connectable == enable) return;
4598 
4599     hci_stack->connectable = enable;
4600     hci_update_scan_enable();
4601 }
4602 #endif
4603 
4604 void gap_local_bd_addr(bd_addr_t address_buffer){
4605     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
4606 }
4607 
4608 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4609 static void hci_host_num_completed_packets(void){
4610 
4611     // create packet manually as arrays are not supported and num_commands should not get reduced
4612     hci_reserve_packet_buffer();
4613     uint8_t * packet = hci_get_outgoing_packet_buffer();
4614 
4615     uint16_t size = 0;
4616     uint16_t num_handles = 0;
4617     packet[size++] = 0x35;
4618     packet[size++] = 0x0c;
4619     size++;  // skip param len
4620     size++;  // skip num handles
4621 
4622     // add { handle, packets } entries
4623     btstack_linked_item_t * it;
4624     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4625         hci_connection_t * connection = (hci_connection_t *) it;
4626         if (connection->num_packets_completed){
4627             little_endian_store_16(packet, size, connection->con_handle);
4628             size += 2;
4629             little_endian_store_16(packet, size, connection->num_packets_completed);
4630             size += 2;
4631             //
4632             num_handles++;
4633             connection->num_packets_completed = 0;
4634         }
4635     }
4636 
4637     packet[2] = size - 3;
4638     packet[3] = num_handles;
4639 
4640     hci_stack->host_completed_packets = 0;
4641 
4642     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4643     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
4644 
4645     // release packet buffer for synchronous transport implementations
4646     if (hci_transport_synchronous()){
4647         hci_release_packet_buffer();
4648         hci_emit_transport_packet_sent();
4649     }
4650 }
4651 #endif
4652 
4653 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
4654     UNUSED(ds);
4655     hci_stack->substate = HCI_HALTING_CLOSE;
4656     // allow packet handlers to defer final shutdown
4657     hci_emit_state();
4658     hci_run();
4659 }
4660 
4661 static bool hci_run_acl_fragments(void){
4662     if (hci_stack->acl_fragmentation_total_size > 0u) {
4663         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
4664         hci_connection_t *connection = hci_connection_for_handle(con_handle);
4665         if (connection) {
4666             if (hci_can_send_prepared_acl_packet_now(con_handle)){
4667                 hci_send_acl_packet_fragments(connection);
4668                 return true;
4669             }
4670         } else {
4671             // connection gone -> discard further fragments
4672             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
4673             hci_stack->acl_fragmentation_total_size = 0;
4674             hci_stack->acl_fragmentation_pos = 0;
4675         }
4676     }
4677     return false;
4678 }
4679 
4680 #ifdef ENABLE_CLASSIC
4681 
4682 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
4683 static bool hci_classic_operation_active(void) {
4684     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
4685         return true;
4686     }
4687     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
4688         return true;
4689     }
4690     btstack_linked_item_t * it;
4691     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
4692         hci_connection_t *connection = (hci_connection_t *) it;
4693         switch (connection->state) {
4694             case SENT_CREATE_CONNECTION:
4695             case SENT_CANCEL_CONNECTION:
4696             case SENT_DISCONNECT:
4697                 return true;
4698             default:
4699                 break;
4700         }
4701     }
4702     return false;
4703 }
4704 #endif
4705 
4706 static bool hci_run_general_gap_classic(void){
4707 
4708     // assert stack is working and classic is active
4709     if (hci_classic_supported() == false)      return false;
4710     if (hci_stack->state != HCI_STATE_WORKING) return false;
4711 
4712     // decline incoming connections
4713     if (hci_stack->decline_reason){
4714         uint8_t reason = hci_stack->decline_reason;
4715         hci_stack->decline_reason = 0;
4716         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
4717         return true;
4718     }
4719 
4720     if (hci_stack->gap_tasks_classic != 0){
4721         hci_run_gap_tasks_classic();
4722         return true;
4723     }
4724 
4725     // start/stop inquiry
4726     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
4727 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
4728         if (hci_classic_operation_active() == false)
4729 #endif
4730         {
4731             uint8_t duration = hci_stack->inquiry_state;
4732             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
4733             hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
4734             return true;
4735         }
4736     }
4737     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
4738         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
4739         hci_send_cmd(&hci_inquiry_cancel);
4740         return true;
4741     }
4742     // remote name request
4743     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
4744 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
4745         if (hci_classic_operation_active() == false)
4746 #endif
4747         {
4748             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
4749             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
4750                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
4751             return true;
4752         }
4753     }
4754 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4755     // Local OOB data
4756     if (hci_stack->classic_read_local_oob_data){
4757         hci_stack->classic_read_local_oob_data = false;
4758         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
4759             hci_send_cmd(&hci_read_local_extended_oob_data);
4760         } else {
4761             hci_send_cmd(&hci_read_local_oob_data);
4762         }
4763     }
4764 #endif
4765     // pairing
4766     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
4767         uint8_t state = hci_stack->gap_pairing_state;
4768         uint8_t pin_code[16];
4769         switch (state){
4770             case GAP_PAIRING_STATE_SEND_PIN:
4771                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4772                 memset(pin_code, 0, 16);
4773                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
4774                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
4775                 break;
4776             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
4777                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4778                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
4779                 break;
4780             case GAP_PAIRING_STATE_SEND_PASSKEY:
4781                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4782                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
4783                 break;
4784             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
4785                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4786                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
4787                 break;
4788             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
4789                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4790                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
4791                 break;
4792             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
4793                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4794                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
4795                 break;
4796             default:
4797                 break;
4798         }
4799         return true;
4800     }
4801     return false;
4802 }
4803 #endif
4804 
4805 #ifdef ENABLE_BLE
4806 
4807 #ifdef ENABLE_LE_CENTRAL
4808 static void hci_le_scan_stop(void){
4809 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4810     if (hci_extended_advertising_supported()) {
4811             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
4812         } else
4813 #endif
4814     {
4815         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
4816     }
4817 }
4818 #endif
4819 
4820 #ifdef ENABLE_LE_PERIPHERAL
4821 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4822 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
4823     uint8_t  operation = 0;
4824     if (pos == 0){
4825         // first fragment or complete data
4826         operation |= 1;
4827     }
4828     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
4829         // last fragment or complete data
4830         operation |= 2;
4831     }
4832     return operation;
4833 }
4834 #endif
4835 #endif
4836 
4837 static bool hci_run_general_gap_le(void){
4838 
4839     btstack_linked_list_iterator_t lit;
4840 
4841     // Phase 1: collect what to stop
4842 
4843     bool scanning_stop = false;
4844     bool connecting_stop = false;
4845     bool advertising_stop = false;
4846 
4847 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4848     le_advertising_set_t * advertising_stop_set = NULL;
4849 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4850     bool periodic_stop = false;
4851 #ifdef ENABLE_LE_CENTRAL
4852     bool periodic_sync_stop = false;
4853 #endif
4854 #endif
4855 #endif
4856 
4857 #ifndef ENABLE_LE_CENTRAL
4858     UNUSED(scanning_stop);
4859     UNUSED(connecting_stop);
4860 #endif
4861 #ifndef ENABLE_LE_PERIPHERAL
4862     UNUSED(advertising_stop);
4863 #endif
4864 
4865     // check if own address changes
4866     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
4867 
4868     // check if whitelist needs modification
4869     bool whitelist_modification_pending = false;
4870     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4871     while (btstack_linked_list_iterator_has_next(&lit)){
4872         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4873         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
4874             whitelist_modification_pending = true;
4875             break;
4876         }
4877     }
4878 
4879     // check if resolving list needs modification
4880     bool resolving_list_modification_pending = false;
4881 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4882     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
4883 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
4884         resolving_list_modification_pending = true;
4885     }
4886 #endif
4887 
4888     // check if periodic advertiser list needs modification
4889 #ifdef ENABLE_LE_CENTRAL
4890 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4891     bool periodic_list_modification_pending = false;
4892     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
4893     while (btstack_linked_list_iterator_has_next(&lit)){
4894         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
4895         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
4896             periodic_list_modification_pending = true;
4897             break;
4898         }
4899     }
4900 #endif
4901 #endif
4902 
4903 #ifdef ENABLE_LE_CENTRAL
4904     // scanning control
4905     if (hci_stack->le_scanning_active) {
4906         // stop if:
4907         // - parameter change required
4908         // - it's disabled
4909         // - whitelist change required but used for scanning
4910         // - resolving list modified
4911         // - own address changes
4912         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
4913         if ((hci_stack->le_scanning_param_update) ||
4914             !hci_stack->le_scanning_enabled ||
4915             (scanning_uses_whitelist && whitelist_modification_pending) ||
4916             resolving_list_modification_pending ||
4917             random_address_change){
4918 
4919             scanning_stop = true;
4920         }
4921     }
4922 #endif
4923 
4924 #ifdef ENABLE_LE_CENTRAL
4925     // connecting control
4926     bool connecting_with_whitelist;
4927     switch (hci_stack->le_connecting_state){
4928         case LE_CONNECTING_DIRECT:
4929         case LE_CONNECTING_WHITELIST:
4930             // stop connecting if:
4931             // - connecting uses white and whitelist modification pending
4932             // - if it got disabled
4933             // - resolving list modified
4934             // - own address changes
4935             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
4936             if ((connecting_with_whitelist && whitelist_modification_pending) ||
4937                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
4938                 resolving_list_modification_pending ||
4939                 random_address_change) {
4940 
4941                 connecting_stop = true;
4942             }
4943             break;
4944         default:
4945             break;
4946     }
4947 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4948     // periodic sync control
4949     bool sync_with_advertiser_list;
4950     switch(hci_stack->le_periodic_sync_state){
4951         case LE_CONNECTING_DIRECT:
4952         case LE_CONNECTING_WHITELIST:
4953             // stop sycn if:
4954             // - sync with advertiser list and advertiser list modification pending
4955             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
4956             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
4957                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
4958                 periodic_sync_stop = true;
4959             }
4960             break;
4961         default:
4962             break;
4963     }
4964 #endif
4965 #endif
4966 
4967 #ifdef ENABLE_LE_PERIPHERAL
4968     // le advertisement control
4969     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
4970         // stop if:
4971         // - parameter change required
4972         // - random address used in advertising and changes
4973         // - it's disabled
4974         // - whitelist change required but used for advertisement filter policy
4975         // - resolving list modified
4976         // - own address changes
4977         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
4978         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
4979         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
4980         if (advertising_change ||
4981             (advertising_uses_random_address && random_address_change) ||
4982             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
4983             (advertising_uses_whitelist && whitelist_modification_pending) ||
4984             resolving_list_modification_pending ||
4985             random_address_change) {
4986 
4987             advertising_stop = true;
4988         }
4989     }
4990 
4991 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4992     if (hci_extended_advertising_supported() && (advertising_stop == false)){
4993         btstack_linked_list_iterator_t it;
4994         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4995         while (btstack_linked_list_iterator_has_next(&it)){
4996             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4997             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
4998                 // stop if:
4999                 // - parameter change required
5000                 // - random address used in connectable advertising and changes
5001                 // - it's disabled
5002                 // - whitelist change required but used for advertisement filter policy
5003                 // - resolving list modified
5004                 // - own address changes
5005                 // - advertisement set will be removed
5006                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
5007                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
5008                 bool advertising_uses_random_address =
5009                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
5010                         advertising_connectable;
5011                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
5012                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
5013                 bool advertising_set_random_address_change =
5014                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5015                 bool advertising_set_will_be_removed =
5016                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
5017                 if (advertising_parameter_change ||
5018                     (advertising_uses_random_address && advertising_set_random_address_change) ||
5019                     (advertising_enabled == false) ||
5020                     (advertising_uses_whitelist && whitelist_modification_pending) ||
5021                     resolving_list_modification_pending ||
5022                     advertising_set_will_be_removed) {
5023 
5024                     advertising_stop = true;
5025                     advertising_stop_set = advertising_set;
5026                     break;
5027                 }
5028             }
5029 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5030             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5031                 // stop if:
5032                 // - it's disabled
5033                 // - parameter change required
5034                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
5035                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
5036                 if ((periodic_enabled == false) || periodic_parameter_change){
5037                     periodic_stop = true;
5038                     advertising_stop_set = advertising_set;
5039                 }
5040             }
5041 #endif
5042         }
5043     }
5044 #endif
5045 
5046 #endif
5047 
5048 
5049     // Phase 2: stop everything that should be off during modifications
5050 
5051 #ifdef ENABLE_LE_CENTRAL
5052     if (scanning_stop){
5053         hci_stack->le_scanning_active = false;
5054         hci_le_scan_stop();
5055         return true;
5056     }
5057 #endif
5058 
5059 #ifdef ENABLE_LE_CENTRAL
5060     if (connecting_stop){
5061         hci_send_cmd(&hci_le_create_connection_cancel);
5062         return true;
5063     }
5064 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5065     if (periodic_sync_stop){
5066         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
5067         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
5068         return true;
5069     }
5070 #endif
5071 #endif
5072 
5073 #ifdef ENABLE_LE_PERIPHERAL
5074     if (advertising_stop){
5075 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5076         if (hci_extended_advertising_supported()) {
5077             uint8_t advertising_stop_handle;
5078             if (advertising_stop_set != NULL){
5079                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5080                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5081             } else {
5082                 advertising_stop_handle = 0;
5083                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5084             }
5085             const uint8_t advertising_handles[] = { advertising_stop_handle };
5086             const uint16_t durations[] = { 0 };
5087             const uint16_t max_events[] = { 0 };
5088             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5089         } else
5090 #endif
5091         {
5092             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5093             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5094         }
5095         return true;
5096     }
5097 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5098 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5099     if (periodic_stop){
5100         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5101         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
5102         return true;
5103     }
5104 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5105 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5106 #endif
5107 
5108     // Phase 3: modify
5109 
5110     if (random_address_change){
5111         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5112 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5113         if (hci_extended_advertising_supported()) {
5114             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5115         }
5116 #endif
5117         {
5118             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5119         }
5120         return true;
5121     }
5122 
5123 #ifdef ENABLE_LE_CENTRAL
5124     if (hci_stack->le_scanning_param_update){
5125         hci_stack->le_scanning_param_update = false;
5126 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5127         if (hci_extended_advertising_supported()){
5128             // prepare arrays for all PHYs
5129             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
5130             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
5131             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
5132             uint8_t  scanning_phys     = 1;  // LE 1M PHY
5133             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
5134                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
5135         } else
5136 #endif
5137         {
5138             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5139                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
5140         }
5141         return true;
5142     }
5143 #endif
5144 
5145 #ifdef ENABLE_LE_PERIPHERAL
5146     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
5147         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5148         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5149 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5150         if (hci_extended_advertising_supported()){
5151             // map advertisment type to advertising event properties
5152             uint16_t adv_event_properties = 0;
5153             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5154             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5155                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5156             }
5157             hci_stack->le_advertising_set_in_current_command = 0;
5158             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5159                          0,
5160                          adv_event_properties,
5161                          hci_stack->le_advertisements_interval_min,
5162                          hci_stack->le_advertisements_interval_max,
5163                          hci_stack->le_advertisements_channel_map,
5164                          hci_stack->le_advertisements_own_addr_type,
5165                          hci_stack->le_advertisements_direct_address_type,
5166                          hci_stack->le_advertisements_direct_address,
5167                          hci_stack->le_advertisements_filter_policy,
5168                          0x7f,  // tx power: no preference
5169                          0x01,  // primary adv phy: LE 1M
5170                          0,     // secondary adv max skip
5171                          0,     // secondary adv phy
5172                          0,     // adv sid
5173                          0      // scan request notification
5174                          );
5175         }
5176 #endif
5177         {
5178             hci_send_cmd(&hci_le_set_advertising_parameters,
5179                          hci_stack->le_advertisements_interval_min,
5180                          hci_stack->le_advertisements_interval_max,
5181                          hci_stack->le_advertisements_type,
5182                          hci_stack->le_advertisements_own_addr_type,
5183                          hci_stack->le_advertisements_direct_address_type,
5184                          hci_stack->le_advertisements_direct_address,
5185                          hci_stack->le_advertisements_channel_map,
5186                          hci_stack->le_advertisements_filter_policy);
5187         }
5188         return true;
5189     }
5190 
5191     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
5192         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5193         uint8_t adv_data_clean[31];
5194         memset(adv_data_clean, 0, sizeof(adv_data_clean));
5195         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
5196                      hci_stack->le_advertisements_data_len);
5197         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
5198 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5199         if (hci_extended_advertising_supported()){
5200             hci_stack->le_advertising_set_in_current_command = 0;
5201             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
5202         } else
5203 #endif
5204         {
5205             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
5206         }
5207         return true;
5208     }
5209 
5210     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
5211         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5212         uint8_t scan_data_clean[31];
5213         memset(scan_data_clean, 0, sizeof(scan_data_clean));
5214         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
5215                      hci_stack->le_scan_response_data_len);
5216         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
5217 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5218         if (hci_extended_advertising_supported()){
5219             hci_stack->le_advertising_set_in_current_command = 0;
5220             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
5221         } else
5222 #endif
5223         {
5224             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
5225         }
5226         return true;
5227     }
5228 
5229 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5230     if (hci_extended_advertising_supported()) {
5231         btstack_linked_list_iterator_t it;
5232         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5233         while (btstack_linked_list_iterator_has_next(&it)){
5234             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5235             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
5236                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
5237                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5238                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
5239                 return true;
5240             }
5241             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
5242                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5243                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
5244                 return true;
5245             }
5246             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
5247                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5248                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5249                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5250                              advertising_set->advertising_handle,
5251                              advertising_set->extended_params.advertising_event_properties,
5252                              advertising_set->extended_params.primary_advertising_interval_min,
5253                              advertising_set->extended_params.primary_advertising_interval_max,
5254                              advertising_set->extended_params.primary_advertising_channel_map,
5255                              advertising_set->extended_params.own_address_type,
5256                              advertising_set->extended_params.peer_address_type,
5257                              advertising_set->extended_params.peer_address,
5258                              advertising_set->extended_params.advertising_filter_policy,
5259                              advertising_set->extended_params.advertising_tx_power,
5260                              advertising_set->extended_params.primary_advertising_phy,
5261                              advertising_set->extended_params.secondary_advertising_max_skip,
5262                              advertising_set->extended_params.secondary_advertising_phy,
5263                              advertising_set->extended_params.advertising_sid,
5264                              advertising_set->extended_params.scan_request_notification_enable
5265                 );
5266                 return true;
5267             }
5268             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
5269                 uint16_t pos = advertising_set->adv_data_pos;
5270                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
5271                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5272                 if ((operation & 0x02) != 0){
5273                     // last fragment or complete data
5274                     operation |= 2;
5275                     advertising_set->adv_data_pos = 0;
5276                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5277                 } else {
5278                     advertising_set->adv_data_pos += data_to_upload;
5279                 }
5280                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5281                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
5282                 return true;
5283             }
5284             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
5285                 uint16_t pos = advertising_set->scan_data_pos;
5286                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
5287                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5288                 if ((operation & 0x02) != 0){
5289                     advertising_set->scan_data_pos = 0;
5290                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5291                 } else {
5292                     advertising_set->scan_data_pos += data_to_upload;
5293                 }
5294                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5295                 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
5296                 return true;
5297             }
5298 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5299             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
5300                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
5301                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5302                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
5303                              advertising_set->advertising_handle,
5304                              advertising_set->periodic_params.periodic_advertising_interval_min,
5305                              advertising_set->periodic_params.periodic_advertising_interval_max,
5306                              advertising_set->periodic_params.periodic_advertising_properties);
5307                 return true;
5308             }
5309             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
5310                 uint16_t pos = advertising_set->periodic_data_pos;
5311                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
5312                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5313                 if ((operation & 0x02) != 0){
5314                     // last fragment or complete data
5315                     operation |= 2;
5316                     advertising_set->periodic_data_pos = 0;
5317                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
5318                 } else {
5319                     advertising_set->periodic_data_pos += data_to_upload;
5320                 }
5321                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5322                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
5323                 return true;
5324             }
5325 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5326         }
5327     }
5328 #endif
5329 
5330 
5331 #endif
5332 
5333 
5334 #ifdef ENABLE_LE_CENTRAL
5335     // if connect with whitelist was active and is not cancelled yet, wait until next time
5336     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
5337 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5338     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
5339     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
5340 #endif
5341 #endif
5342 
5343     // LE Whitelist Management
5344     if (whitelist_modification_pending){
5345         // add/remove entries
5346         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5347         while (btstack_linked_list_iterator_has_next(&lit)){
5348             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5349 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5350 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5351 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
5352 				return true;
5353 			}
5354             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
5355 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
5356                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
5357                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
5358                 return true;
5359             }
5360             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
5361 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5362 				btstack_memory_whitelist_entry_free(entry);
5363             }
5364         }
5365     }
5366 
5367 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5368     // LE Resolving List Management
5369     if (resolving_list_supported) {
5370 		uint16_t i;
5371 		switch (hci_stack->le_resolving_list_state) {
5372 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
5373 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
5374 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
5375 				return true;
5376 			case LE_RESOLVING_LIST_READ_SIZE:
5377 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
5378 				hci_send_cmd(&hci_le_read_resolving_list_size);
5379 				return true;
5380 			case LE_RESOLVING_LIST_SEND_CLEAR:
5381 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
5382 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
5383 							  sizeof(hci_stack->le_resolving_list_add_entries));
5384 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
5385 							  sizeof(hci_stack->le_resolving_list_remove_entries));
5386 				hci_send_cmd(&hci_le_clear_resolving_list);
5387 				return true;
5388 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
5389 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5390 					uint8_t offset = i >> 3;
5391 					uint8_t mask = 1 << (i & 7);
5392 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
5393 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
5394 					bd_addr_t peer_identity_addreses;
5395 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5396 					sm_key_t peer_irk;
5397 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5398 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5399 
5400 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
5401 					// trigger whitelist entry 'update' (work around for controller bug)
5402 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5403 					while (btstack_linked_list_iterator_has_next(&lit)) {
5404 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
5405 						if (entry->address_type != peer_identity_addr_type) continue;
5406 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
5407 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
5408 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
5409 					}
5410 #endif
5411 
5412 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
5413 								 peer_identity_addreses);
5414 					return true;
5415 				}
5416 
5417 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
5418 
5419 				/* fall through */
5420 
5421 			case LE_RESOLVING_LIST_ADD_ENTRIES:
5422 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5423 					uint8_t offset = i >> 3;
5424 					uint8_t mask = 1 << (i & 7);
5425 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
5426 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
5427 					bd_addr_t peer_identity_addreses;
5428 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5429 					sm_key_t peer_irk;
5430 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5431 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5432 					const uint8_t *local_irk = gap_get_persistent_irk();
5433 					// command uses format specifier 'P' that stores 16-byte value without flip
5434 					uint8_t local_irk_flipped[16];
5435 					uint8_t peer_irk_flipped[16];
5436 					reverse_128(local_irk, local_irk_flipped);
5437 					reverse_128(peer_irk, peer_irk_flipped);
5438 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
5439 								 peer_irk_flipped, local_irk_flipped);
5440 					return true;
5441 				}
5442 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5443 				break;
5444 
5445 			default:
5446 				break;
5447 		}
5448 	}
5449     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
5450 #endif
5451 
5452 #ifdef ENABLE_LE_CENTRAL
5453 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5454     // LE Whitelist Management
5455     if (periodic_list_modification_pending){
5456         // add/remove entries
5457         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5458         while (btstack_linked_list_iterator_has_next(&lit)){
5459             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5460             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
5461                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5462                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
5463                 return true;
5464             }
5465             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
5466                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5467                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
5468                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address);
5469                 return true;
5470             }
5471             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
5472                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
5473                 btstack_memory_periodic_advertiser_list_entry_free(entry);
5474             }
5475         }
5476     }
5477 #endif
5478 #endif
5479 
5480     // post-pone all actions until stack is fully working
5481     if (hci_stack->state != HCI_STATE_WORKING) return false;
5482 
5483     // advertisements, active scanning, and creating connections requires random address to be set if using private address
5484     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
5485 
5486     // Phase 4: restore state
5487 
5488 #ifdef ENABLE_LE_CENTRAL
5489     // re-start scanning
5490     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
5491         hci_stack->le_scanning_active = true;
5492 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5493         if (hci_extended_advertising_supported()){
5494             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0);
5495         } else
5496 #endif
5497         {
5498             hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
5499         }
5500         return true;
5501     }
5502 #endif
5503 
5504 #ifdef ENABLE_LE_CENTRAL
5505     // re-start connecting
5506     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
5507         bd_addr_t null_addr;
5508         memset(null_addr, 0, 6);
5509         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
5510         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
5511         hci_send_cmd(&hci_le_create_connection,
5512                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
5513                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
5514                      1,         // use whitelist
5515                      0,         // peer address type
5516                      null_addr, // peer bd addr
5517                      hci_stack->le_connection_own_addr_type,   // our addr type:
5518                      hci_stack->le_connection_interval_min,    // conn interval min
5519                      hci_stack->le_connection_interval_max,    // conn interval max
5520                      hci_stack->le_connection_latency,         // conn latency
5521                      hci_stack->le_supervision_timeout,        // conn latency
5522                      hci_stack->le_minimum_ce_length,          // min ce length
5523                      hci_stack->le_maximum_ce_length           // max ce length
5524         );
5525         return true;
5526     }
5527 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5528     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
5529         switch(hci_stack->le_periodic_sync_request){
5530             case LE_CONNECTING_DIRECT:
5531             case LE_CONNECTING_WHITELIST:
5532                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
5533                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
5534                              hci_stack->le_periodic_sync_options,
5535                              hci_stack->le_periodic_sync_advertising_sid,
5536                              hci_stack->le_periodic_sync_advertiser_address_type,
5537                              hci_stack->le_periodic_sync_advertiser_address,
5538                              hci_stack->le_periodic_sync_skip,
5539                              hci_stack->le_periodic_sync_timeout,
5540                              hci_stack->le_periodic_sync_cte_type);
5541                 return true;
5542             default:
5543                 break;
5544         }
5545     }
5546 #endif
5547 #endif
5548 
5549 #ifdef ENABLE_LE_PERIPHERAL
5550     // re-start advertising
5551     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
5552         // check if advertisements should be enabled given
5553         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
5554         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
5555 
5556 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5557         if (hci_extended_advertising_supported()){
5558             const uint8_t advertising_handles[] = { 0 };
5559             const uint16_t durations[] = { 0 };
5560             const uint16_t max_events[] = { 0 };
5561             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
5562         } else
5563 #endif
5564         {
5565             hci_send_cmd(&hci_le_set_advertise_enable, 1);
5566         }
5567         return true;
5568     }
5569 
5570 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5571     if (hci_extended_advertising_supported()) {
5572         btstack_linked_list_iterator_t it;
5573         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5574         while (btstack_linked_list_iterator_has_next(&it)) {
5575             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
5576             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
5577                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
5578                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
5579                 const uint16_t durations[] = { advertising_set->enable_timeout };
5580                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
5581                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
5582                 return true;
5583             }
5584 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5585             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
5586                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5587                 uint8_t enable = 1;
5588                 if (advertising_set->periodic_include_adi){
5589                     enable |= 2;
5590                 }
5591                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
5592                 return true;
5593             }
5594 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5595         }
5596     }
5597 #endif
5598 #endif
5599 
5600     return false;
5601 }
5602 #endif
5603 
5604 static bool hci_run_general_pending_commands(void){
5605     btstack_linked_item_t * it;
5606     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5607         hci_connection_t * connection = (hci_connection_t *) it;
5608 
5609         switch(connection->state){
5610             case SEND_CREATE_CONNECTION:
5611                 switch(connection->address_type){
5612 #ifdef ENABLE_CLASSIC
5613                     case BD_ADDR_TYPE_ACL:
5614                         log_info("sending hci_create_connection");
5615                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
5616                         break;
5617 #endif
5618                     default:
5619 #ifdef ENABLE_BLE
5620 #ifdef ENABLE_LE_CENTRAL
5621                         log_info("sending hci_le_create_connection");
5622                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
5623                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
5624                         hci_send_cmd(&hci_le_create_connection,
5625                                      hci_stack->le_connection_scan_interval,    // conn scan interval
5626                                      hci_stack->le_connection_scan_window,      // conn scan windows
5627                                      0,         // don't use whitelist
5628                                      connection->address_type, // peer address type
5629                                      connection->address,      // peer bd addr
5630                                      hci_stack->le_connection_own_addr_type,   // our addr type:
5631                                      hci_stack->le_connection_interval_min,    // conn interval min
5632                                      hci_stack->le_connection_interval_max,    // conn interval max
5633                                      hci_stack->le_connection_latency,         // conn latency
5634                                      hci_stack->le_supervision_timeout,        // conn latency
5635                                      hci_stack->le_minimum_ce_length,          // min ce length
5636                                      hci_stack->le_maximum_ce_length          // max ce length
5637                         );
5638                         connection->state = SENT_CREATE_CONNECTION;
5639 #endif
5640 #endif
5641                         break;
5642                 }
5643                 return true;
5644 
5645 #ifdef ENABLE_CLASSIC
5646             case RECEIVED_CONNECTION_REQUEST:
5647                 connection->role  = HCI_ROLE_SLAVE;
5648                 if (connection->address_type == BD_ADDR_TYPE_ACL){
5649                     log_info("sending hci_accept_connection_request");
5650                     connection->state = ACCEPTED_CONNECTION_REQUEST;
5651                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
5652                     return true;
5653                 }
5654                 break;
5655 #endif
5656 
5657 #ifdef ENABLE_BLE
5658 #ifdef ENABLE_LE_CENTRAL
5659             case SEND_CANCEL_CONNECTION:
5660                 connection->state = SENT_CANCEL_CONNECTION;
5661                 hci_send_cmd(&hci_le_create_connection_cancel);
5662                 return true;
5663 #endif
5664 #endif
5665             case SEND_DISCONNECT:
5666                 connection->state = SENT_DISCONNECT;
5667                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5668                 return true;
5669 
5670             default:
5671                 break;
5672         }
5673 
5674         // no further commands if connection is about to get shut down
5675         if (connection->state == SENT_DISCONNECT) continue;
5676 
5677 #ifdef ENABLE_CLASSIC
5678 
5679         // Handling link key request requires remote supported features
5680         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
5681             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
5682             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
5683 
5684             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
5685             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
5686             if (have_link_key && security_level_sufficient){
5687                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
5688             } else {
5689                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
5690             }
5691             return true;
5692         }
5693 
5694         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
5695             log_info("denying to pin request");
5696             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
5697             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
5698             return true;
5699         }
5700 
5701         // security assessment requires remote features
5702         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
5703             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
5704             hci_ssp_assess_security_on_io_cap_request(connection);
5705             // 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
5706         }
5707 
5708         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
5709             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
5710             // set authentication requirements:
5711             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
5712             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
5713             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
5714             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
5715                 authreq |= 1;
5716             }
5717             bool bonding = hci_stack->bondable;
5718             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
5719                 // if we have received IO Cap Response, we're in responder role
5720                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
5721                 if (bonding && !remote_bonding){
5722                     log_info("Remote not bonding, dropping local flag");
5723                     bonding = false;
5724                 }
5725             }
5726             if (bonding){
5727                 if (connection->bonding_flags & BONDING_DEDICATED){
5728                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
5729                 } else {
5730                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
5731                 }
5732             }
5733             uint8_t have_oob_data = 0;
5734 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5735             if (connection->classic_oob_c_192 != NULL){
5736                     have_oob_data |= 1;
5737             }
5738             if (connection->classic_oob_c_256 != NULL){
5739                 have_oob_data |= 2;
5740             }
5741 #endif
5742             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
5743             return true;
5744         }
5745 
5746         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
5747             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
5748             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
5749             return true;
5750         }
5751 
5752 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5753         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
5754             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
5755             const uint8_t zero[16] = { 0 };
5756             const uint8_t * r_192 = zero;
5757             const uint8_t * c_192 = zero;
5758             const uint8_t * r_256 = zero;
5759             const uint8_t * c_256 = zero;
5760             // verify P-256 OOB
5761             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
5762                 c_256 = connection->classic_oob_c_256;
5763                 if (connection->classic_oob_r_256 != NULL) {
5764                     r_256 = connection->classic_oob_r_256;
5765                 }
5766             }
5767             // verify P-192 OOB
5768             if ((connection->classic_oob_c_192 != NULL)) {
5769                 c_192 = connection->classic_oob_c_192;
5770                 if (connection->classic_oob_r_192 != NULL) {
5771                     r_192 = connection->classic_oob_r_192;
5772                 }
5773             }
5774 
5775             // assess security
5776             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
5777             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
5778             if (need_level_4 && !can_reach_level_4){
5779                 log_info("Level 4 required, but not possible -> abort");
5780                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
5781                 // send oob negative reply
5782                 c_256 = NULL;
5783                 c_192 = NULL;
5784             }
5785 
5786             // Reply
5787             if (c_256 != zero) {
5788                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
5789             } else if (c_192 != zero){
5790                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
5791             } else {
5792                 hci_stack->classic_oob_con_handle = connection->con_handle;
5793                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
5794             }
5795             return true;
5796         }
5797 #endif
5798 
5799         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
5800             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
5801             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
5802             return true;
5803         }
5804 
5805         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
5806             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
5807             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
5808             return true;
5809         }
5810 
5811         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
5812             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
5813             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
5814             return true;
5815         }
5816 
5817         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
5818             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
5819             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
5820             connection->state = SENT_DISCONNECT;
5821             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5822             return true;
5823         }
5824 
5825         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
5826             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
5827             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
5828             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
5829             return true;
5830         }
5831 
5832         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
5833             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
5834             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
5835             return true;
5836         }
5837 
5838         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
5839             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
5840             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
5841             return true;
5842         }
5843 
5844         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
5845             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
5846             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
5847             return true;
5848         }
5849 
5850         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
5851             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
5852             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
5853             return true;
5854         }
5855 
5856         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
5857             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
5858             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
5859             return true;
5860         }
5861 #endif
5862 
5863         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
5864             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
5865 #ifdef ENABLE_CLASSIC
5866             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
5867 #endif
5868             if (connection->state != SENT_DISCONNECT){
5869                 connection->state = SENT_DISCONNECT;
5870                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
5871                 return true;
5872             }
5873         }
5874 
5875 #ifdef ENABLE_CLASSIC
5876         uint16_t sniff_min_interval;
5877         switch (connection->sniff_min_interval){
5878             case 0:
5879                 break;
5880             case 0xffff:
5881                 connection->sniff_min_interval = 0;
5882                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
5883                 return true;
5884             default:
5885                 sniff_min_interval = connection->sniff_min_interval;
5886                 connection->sniff_min_interval = 0;
5887                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
5888                 return true;
5889         }
5890 
5891         if (connection->sniff_subrating_max_latency != 0xffff){
5892             uint16_t max_latency = connection->sniff_subrating_max_latency;
5893             connection->sniff_subrating_max_latency = 0;
5894             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
5895             return true;
5896         }
5897 
5898         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
5899             uint8_t service_type = (uint8_t) connection->qos_service_type;
5900             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
5901             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);
5902             return true;
5903         }
5904 
5905         if (connection->request_role != HCI_ROLE_INVALID){
5906             hci_role_t role = connection->request_role;
5907             connection->request_role = HCI_ROLE_INVALID;
5908             hci_send_cmd(&hci_switch_role_command, connection->address, role);
5909             return true;
5910         }
5911 #endif
5912 
5913         if (connection->gap_connection_tasks != 0){
5914 #ifdef ENABLE_CLASSIC
5915             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
5916                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
5917                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
5918                 return true;
5919             }
5920             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
5921                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
5922                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
5923                 return true;
5924             }
5925 #endif
5926             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
5927                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
5928                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
5929                 return true;
5930             }
5931         }
5932 
5933 #ifdef ENABLE_BLE
5934         switch (connection->le_con_parameter_update_state){
5935             // response to L2CAP CON PARAMETER UPDATE REQUEST
5936             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
5937                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5938                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
5939                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
5940                              0x0000, 0xffff);
5941                 return true;
5942             case CON_PARAMETER_UPDATE_REPLY:
5943                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5944                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
5945                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
5946                              0x0000, 0xffff);
5947                 return true;
5948             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
5949                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
5950                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
5951                 return true;
5952             default:
5953                 break;
5954         }
5955         if (connection->le_phy_update_all_phys != 0xffu){
5956             uint8_t all_phys = connection->le_phy_update_all_phys;
5957             connection->le_phy_update_all_phys = 0xff;
5958             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);
5959             return true;
5960         }
5961 #endif
5962     }
5963     return false;
5964 }
5965 
5966 static void hci_run(void){
5967 
5968     // stack state sub statemachines
5969     // halting needs to be called even if we cannot send command packet now
5970     switch (hci_stack->state) {
5971         case HCI_STATE_INITIALIZING:
5972             hci_initializing_run();
5973             break;
5974         case HCI_STATE_HALTING:
5975             hci_halting_run();
5976             break;
5977         case HCI_STATE_FALLING_ASLEEP:
5978             hci_falling_asleep_run();
5979             break;
5980         default:
5981             break;
5982     }
5983 
5984     bool done;
5985 
5986     // send continuation fragments first, as they block the prepared packet buffer
5987     done = hci_run_acl_fragments();
5988     if (done) return;
5989 
5990 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5991     // send host num completed packets next as they don't require num_cmd_packets > 0
5992     if (!hci_can_send_comand_packet_transport()) return;
5993     if (hci_stack->host_completed_packets){
5994         hci_host_num_completed_packets();
5995         return;
5996     }
5997 #endif
5998 
5999     if (!hci_can_send_command_packet_now()) return;
6000 
6001     // global/non-connection oriented commands
6002 
6003 
6004 #ifdef ENABLE_CLASSIC
6005     // general gap classic
6006     done = hci_run_general_gap_classic();
6007     if (done) return;
6008 #endif
6009 
6010 #ifdef ENABLE_BLE
6011     // general gap le
6012     done = hci_run_general_gap_le();
6013     if (done) return;
6014 #endif
6015 
6016     // send pending HCI commands
6017     hci_run_general_pending_commands();
6018 }
6019 
6020 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
6021     // house-keeping
6022 
6023 #ifdef ENABLE_CLASSIC
6024     bd_addr_t addr;
6025     hci_connection_t * conn;
6026 #endif
6027 #ifdef ENABLE_LE_CENTRAL
6028     uint8_t initiator_filter_policy;
6029 #endif
6030 
6031     uint16_t opcode = little_endian_read_16(packet, 0);
6032     switch (opcode) {
6033         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
6034             hci_stack->loopback_mode = packet[3];
6035             break;
6036 
6037 #ifdef ENABLE_CLASSIC
6038         case HCI_OPCODE_HCI_CREATE_CONNECTION:
6039             reverse_bd_addr(&packet[3], addr);
6040             log_info("Create_connection to %s", bd_addr_to_str(addr));
6041 
6042             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
6043             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
6044                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
6045                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
6046             }
6047 
6048             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6049             if (!conn) {
6050                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6051                 if (!conn) {
6052                     // notify client that alloc failed
6053                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6054                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
6055                 }
6056                 conn->state = SEND_CREATE_CONNECTION;
6057                 conn->role  = HCI_ROLE_MASTER;
6058             }
6059 
6060             conn->con_handle = HCI_CON_HANDLE_INVALID;
6061             conn->role = HCI_ROLE_INVALID;
6062 
6063             log_info("conn state %u", conn->state);
6064             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
6065             switch (conn->state) {
6066                 // if connection active exists
6067                 case OPEN:
6068                     // and OPEN, emit connection complete command
6069                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
6070                     // packet not sent to controller
6071                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6072                 case RECEIVED_DISCONNECTION_COMPLETE:
6073                     // create connection triggered in disconnect complete event, let's do it now
6074                     break;
6075                 case SEND_CREATE_CONNECTION:
6076 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
6077                     if (hci_classic_operation_active()){
6078                         return ERROR_CODE_SUCCESS;
6079                     }
6080 #endif
6081                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
6082                     break;
6083                 default:
6084                     // otherwise, just ignore as it is already in the open process
6085                     // packet not sent to controller
6086                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6087             }
6088             conn->state = SENT_CREATE_CONNECTION;
6089 
6090             // track outgoing connection
6091             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
6092             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
6093             break;
6094 
6095 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
6096         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
6097             // setup_synchronous_connection? Voice setting at offset 22
6098             // TODO: compare to current setting if sco connection already active
6099             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
6100             break;
6101         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
6102             // accept_synchronous_connection? Voice setting at offset 18
6103             // TODO: compare to current setting if sco connection already active
6104             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
6105             // track outgoing connection
6106             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
6107             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
6108             break;
6109 #endif
6110 #endif
6111 
6112 #ifdef ENABLE_BLE
6113 #ifdef ENABLE_LE_CENTRAL
6114         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
6115             // white list used?
6116             initiator_filter_policy = packet[7];
6117             switch (initiator_filter_policy) {
6118                 case 0:
6119                     // whitelist not used
6120                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
6121                     break;
6122                 case 1:
6123                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
6124                     break;
6125                 default:
6126                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
6127                     break;
6128             }
6129             // track outgoing connection
6130             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
6131             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
6132             break;
6133         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
6134             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
6135             break;
6136 #endif
6137 #endif
6138         default:
6139             break;
6140     }
6141 
6142     hci_stack->num_cmd_packets--;
6143 
6144     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
6145     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
6146     if (err != 0){
6147         return ERROR_CODE_HARDWARE_FAILURE;
6148     }
6149     return ERROR_CODE_SUCCESS;
6150 }
6151 
6152 // disconnect because of security block
6153 void hci_disconnect_security_block(hci_con_handle_t con_handle){
6154     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6155     if (!connection) return;
6156     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
6157 }
6158 
6159 
6160 // Configure Secure Simple Pairing
6161 
6162 #ifdef ENABLE_CLASSIC
6163 
6164 // enable will enable SSP during init
6165 void gap_ssp_set_enable(int enable){
6166     hci_stack->ssp_enable = enable;
6167 }
6168 
6169 static int hci_local_ssp_activated(void){
6170     return gap_ssp_supported() && hci_stack->ssp_enable;
6171 }
6172 
6173 // if set, BTstack will respond to io capability request using authentication requirement
6174 void gap_ssp_set_io_capability(int io_capability){
6175     hci_stack->ssp_io_capability = io_capability;
6176 }
6177 void gap_ssp_set_authentication_requirement(int authentication_requirement){
6178     hci_stack->ssp_authentication_requirement = authentication_requirement;
6179 }
6180 
6181 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
6182 void gap_ssp_set_auto_accept(int auto_accept){
6183     hci_stack->ssp_auto_accept = auto_accept;
6184 }
6185 
6186 void gap_secure_connections_enable(bool enable){
6187     hci_stack->secure_connections_enable = enable;
6188 }
6189 bool gap_secure_connections_active(void){
6190     return hci_stack->secure_connections_active;
6191 }
6192 
6193 #endif
6194 
6195 // va_list part of hci_send_cmd
6196 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
6197     if (!hci_can_send_command_packet_now()){
6198         log_error("hci_send_cmd called but cannot send packet now");
6199         return ERROR_CODE_COMMAND_DISALLOWED;
6200     }
6201 
6202     // for HCI INITIALIZATION
6203     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
6204     hci_stack->last_cmd_opcode = cmd->opcode;
6205 
6206     hci_reserve_packet_buffer();
6207     uint8_t * packet = hci_stack->hci_packet_buffer;
6208     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
6209     uint8_t status = hci_send_cmd_packet(packet, size);
6210 
6211     // release packet buffer on error or for synchronous transport implementations
6212     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
6213         hci_release_packet_buffer();
6214         hci_emit_transport_packet_sent();
6215     }
6216 
6217     return status;
6218 }
6219 
6220 /**
6221  * pre: numcmds >= 0 - it's allowed to send a command to the controller
6222  */
6223 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
6224     va_list argptr;
6225     va_start(argptr, cmd);
6226     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
6227     va_end(argptr);
6228     return status;
6229 }
6230 
6231 // Create various non-HCI events.
6232 // TODO: generalize, use table similar to hci_create_command
6233 
6234 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
6235     // dump packet
6236     if (dump) {
6237         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
6238     }
6239 
6240     // dispatch to all event handlers
6241     btstack_linked_list_iterator_t it;
6242     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
6243     while (btstack_linked_list_iterator_has_next(&it)){
6244         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
6245         entry->callback(HCI_EVENT_PACKET, 0, event, size);
6246     }
6247 }
6248 
6249 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
6250     if (!hci_stack->acl_packet_handler) return;
6251     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
6252 }
6253 
6254 #ifdef ENABLE_CLASSIC
6255 static void hci_notify_if_sco_can_send_now(void){
6256     // notify SCO sender if waiting
6257     if (!hci_stack->sco_waiting_for_can_send_now) return;
6258     if (hci_can_send_sco_packet_now()){
6259         hci_stack->sco_waiting_for_can_send_now = 0;
6260         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
6261         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
6262         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
6263     }
6264 }
6265 
6266 // parsing end emitting has been merged to reduce code size
6267 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
6268     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
6269 
6270     uint8_t * eir_data;
6271     ad_context_t context;
6272     const uint8_t * name;
6273     uint8_t         name_len;
6274 
6275     if (size < 3) return;
6276 
6277     int event_type = hci_event_packet_get_type(packet);
6278     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
6279     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
6280 
6281     switch (event_type){
6282         case HCI_EVENT_INQUIRY_RESULT:
6283         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6284             if (size != (3 + (num_responses * 14))) return;
6285             break;
6286         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6287             if (size != 257) return;
6288             if (num_responses != 1) return;
6289             break;
6290         default:
6291             return;
6292     }
6293 
6294     // event[1] is set at the end
6295     int i;
6296     for (i=0; i<num_responses;i++){
6297         memset(event, 0, sizeof(event));
6298         event[0] = GAP_EVENT_INQUIRY_RESULT;
6299         uint8_t event_size = 27;    // if name is not set by EIR
6300 
6301         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
6302         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
6303         (void)memcpy(&event[9],
6304                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
6305                      3); // class of device
6306         (void)memcpy(&event[12],
6307                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
6308                      2); // clock offset
6309 
6310         switch (event_type){
6311             case HCI_EVENT_INQUIRY_RESULT:
6312                 // 14,15,16,17 = 0, size 18
6313                 break;
6314             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6315                 event[14] = 1;
6316                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
6317                 // 16,17 = 0, size 18
6318                 break;
6319             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6320                 event[14] = 1;
6321                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
6322                 // EIR packets only contain a single inquiry response
6323                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
6324                 name = NULL;
6325                 // Iterate over EIR data
6326                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
6327                     uint8_t data_type    = ad_iterator_get_data_type(&context);
6328                     uint8_t data_size    = ad_iterator_get_data_len(&context);
6329                     const uint8_t * data = ad_iterator_get_data(&context);
6330                     // Prefer Complete Local Name over Shortened Local Name
6331                     switch (data_type){
6332                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
6333                             if (name) continue;
6334                             /* fall through */
6335                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
6336                             name = data;
6337                             name_len = data_size;
6338                             break;
6339                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
6340                             if (data_size != 8) break;
6341                             event[16] = 1;
6342                             memcpy(&event[17], data, 8);
6343                             break;
6344                         default:
6345                             break;
6346                     }
6347                 }
6348                 if (name){
6349                     event[25] = 1;
6350                     // truncate name if needed
6351                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
6352                     event[26] = len;
6353                     (void)memcpy(&event[27], name, len);
6354                     event_size += len;
6355                 }
6356                 break;
6357             default:
6358                 return;
6359         }
6360         event[1] = event_size - 2;
6361         hci_emit_event(event, event_size, 1);
6362     }
6363 }
6364 #endif
6365 
6366 void hci_emit_state(void){
6367     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
6368     uint8_t event[3];
6369     event[0] = BTSTACK_EVENT_STATE;
6370     event[1] = sizeof(event) - 2u;
6371     event[2] = hci_stack->state;
6372     hci_emit_event(event, sizeof(event), 1);
6373 }
6374 
6375 #ifdef ENABLE_CLASSIC
6376 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
6377     uint8_t event[13];
6378     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
6379     event[1] = sizeof(event) - 2;
6380     event[2] = status;
6381     little_endian_store_16(event, 3, con_handle);
6382     reverse_bd_addr(address, &event[5]);
6383     event[11] = 1; // ACL connection
6384     event[12] = 0; // encryption disabled
6385     hci_emit_event(event, sizeof(event), 1);
6386 }
6387 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
6388     if (disable_l2cap_timeouts) return;
6389     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
6390     uint8_t event[4];
6391     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
6392     event[1] = sizeof(event) - 2;
6393     little_endian_store_16(event, 2, conn->con_handle);
6394     hci_emit_event(event, sizeof(event), 1);
6395 }
6396 #endif
6397 
6398 #ifdef ENABLE_BLE
6399 #ifdef ENABLE_LE_CENTRAL
6400 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){
6401     uint8_t event[21];
6402     event[0] = HCI_EVENT_LE_META;
6403     event[1] = sizeof(event) - 2u;
6404     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
6405     event[3] = status;
6406     little_endian_store_16(event, 4, con_handle);
6407     event[6] = 0; // TODO: role
6408     event[7] = address_type;
6409     reverse_bd_addr(address, &event[8]);
6410     little_endian_store_16(event, 14, 0); // interval
6411     little_endian_store_16(event, 16, 0); // latency
6412     little_endian_store_16(event, 18, 0); // supervision timeout
6413     event[20] = 0; // master clock accuracy
6414     hci_emit_event(event, sizeof(event), 1);
6415 }
6416 #endif
6417 #endif
6418 
6419 static void hci_emit_transport_packet_sent(void){
6420     // notify upper stack that it might be possible to send again
6421     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
6422     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
6423 }
6424 
6425 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
6426     uint8_t event[6];
6427     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
6428     event[1] = sizeof(event) - 2u;
6429     event[2] = 0; // status = OK
6430     little_endian_store_16(event, 3, con_handle);
6431     event[5] = reason;
6432     hci_emit_event(event, sizeof(event), 1);
6433 }
6434 
6435 static void hci_emit_nr_connections_changed(void){
6436     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
6437     uint8_t event[3];
6438     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
6439     event[1] = sizeof(event) - 2u;
6440     event[2] = nr_hci_connections();
6441     hci_emit_event(event, sizeof(event), 1);
6442 }
6443 
6444 static void hci_emit_hci_open_failed(void){
6445     log_info("BTSTACK_EVENT_POWERON_FAILED");
6446     uint8_t event[2];
6447     event[0] = BTSTACK_EVENT_POWERON_FAILED;
6448     event[1] = sizeof(event) - 2u;
6449     hci_emit_event(event, sizeof(event), 1);
6450 }
6451 
6452 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
6453     log_info("hci_emit_dedicated_bonding_result %u ", status);
6454     uint8_t event[9];
6455     int pos = 0;
6456     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
6457     event[pos++] = sizeof(event) - 2u;
6458     event[pos++] = status;
6459     reverse_bd_addr(address, &event[pos]);
6460     hci_emit_event(event, sizeof(event), 1);
6461 }
6462 
6463 
6464 #ifdef ENABLE_CLASSIC
6465 
6466 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
6467     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
6468     uint8_t event[5];
6469     int pos = 0;
6470     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
6471     event[pos++] = sizeof(event) - 2;
6472     little_endian_store_16(event, 2, con_handle);
6473     pos += 2;
6474     event[pos++] = level;
6475     hci_emit_event(event, sizeof(event), 1);
6476 }
6477 
6478 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
6479     if (!connection) return LEVEL_0;
6480     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
6481     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
6482     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
6483     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
6484     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
6485     // LEVEL 4 always requires 128 bit encrytion key size
6486     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
6487         security_level = LEVEL_3;
6488     }
6489     return security_level;
6490 }
6491 
6492 static void hci_emit_discoverable_enabled(uint8_t enabled){
6493     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
6494     uint8_t event[3];
6495     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
6496     event[1] = sizeof(event) - 2;
6497     event[2] = enabled;
6498     hci_emit_event(event, sizeof(event), 1);
6499 }
6500 
6501 // query if remote side supports eSCO
6502 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
6503     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6504     if (!connection) return false;
6505     return (connection->remote_supported_features[0] & 1) != 0;
6506 }
6507 
6508 static bool hci_ssp_supported(hci_connection_t * connection){
6509     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
6510     return (connection->bonding_flags & mask) == mask;
6511 }
6512 
6513 // query if remote side supports SSP
6514 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
6515     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6516     if (!connection) return false;
6517     return hci_ssp_supported(connection) ? 1 : 0;
6518 }
6519 
6520 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
6521     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
6522 }
6523 
6524 /**
6525  * Check if remote supported features query has completed
6526  */
6527 bool hci_remote_features_available(hci_con_handle_t handle){
6528     hci_connection_t * connection = hci_connection_for_handle(handle);
6529     if (!connection) return false;
6530     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
6531 }
6532 
6533 /**
6534  * Trigger remote supported features query
6535  */
6536 
6537 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
6538     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
6539         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6540     }
6541 }
6542 
6543 void hci_remote_features_query(hci_con_handle_t con_handle){
6544     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6545     if (!connection) return;
6546     hci_trigger_remote_features_for_connection(connection);
6547     hci_run();
6548 }
6549 
6550 // GAP API
6551 /**
6552  * @bbrief enable/disable bonding. default is enabled
6553  * @praram enabled
6554  */
6555 void gap_set_bondable_mode(int enable){
6556     hci_stack->bondable = enable ? 1 : 0;
6557 }
6558 /**
6559  * @brief Get bondable mode.
6560  * @return 1 if bondable
6561  */
6562 int gap_get_bondable_mode(void){
6563     return hci_stack->bondable;
6564 }
6565 
6566 /**
6567  * @brief map link keys to security levels
6568  */
6569 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
6570     switch (link_key_type){
6571         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6572             return LEVEL_4;
6573         case COMBINATION_KEY:
6574         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
6575             return LEVEL_3;
6576         default:
6577             return LEVEL_2;
6578     }
6579 }
6580 
6581 /**
6582  * @brief map link keys to secure connection yes/no
6583  */
6584 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
6585     switch (link_key_type){
6586         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6587         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6588             return true;
6589         default:
6590             return false;
6591     }
6592 }
6593 
6594 /**
6595  * @brief map link keys to authenticated
6596  */
6597 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
6598     switch (link_key_type){
6599         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6600         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
6601             return true;
6602         default:
6603             return false;
6604     }
6605 }
6606 
6607 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
6608     log_info("gap_mitm_protection_required_for_security_level %u", level);
6609     return level > LEVEL_2;
6610 }
6611 
6612 /**
6613  * @brief get current security level
6614  */
6615 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
6616     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6617     if (!connection) return LEVEL_0;
6618     return gap_security_level_for_connection(connection);
6619 }
6620 
6621 /**
6622  * @brief request connection to device to
6623  * @result GAP_AUTHENTICATION_RESULT
6624  */
6625 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
6626     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6627     if (!connection){
6628         hci_emit_security_level(con_handle, LEVEL_0);
6629         return;
6630     }
6631 
6632     btstack_assert(hci_is_le_connection(connection) == false);
6633 
6634     // 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)
6635     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
6636     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
6637         requested_level = LEVEL_4;
6638     }
6639 
6640     gap_security_level_t current_level = gap_security_level(con_handle);
6641     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
6642         requested_level, connection->requested_security_level, current_level);
6643 
6644     // authentication active if authentication request was sent or planned level > 0
6645     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
6646     if (authentication_active){
6647         // authentication already active
6648         if (connection->requested_security_level < requested_level){
6649             // increase requested level as new level is higher
6650             // TODO: handle re-authentication when done
6651             connection->requested_security_level = requested_level;
6652         }
6653     } else {
6654         // no request active, notify if security sufficient
6655         if (requested_level <= current_level){
6656             hci_emit_security_level(con_handle, current_level);
6657             return;
6658         }
6659 
6660         // store request
6661         connection->requested_security_level = requested_level;
6662 
6663         // request remote features if not already active
6664         hci_remote_features_query(con_handle);
6665 
6666         // start to authenticate connection
6667         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
6668         hci_run();
6669     }
6670 }
6671 
6672 /**
6673  * @brief start dedicated bonding with device. disconnect after bonding
6674  * @param device
6675  * @param request MITM protection
6676  * @result GAP_DEDICATED_BONDING_COMPLETE
6677  */
6678 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
6679 
6680     // create connection state machine
6681     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
6682 
6683     if (!connection){
6684         return BTSTACK_MEMORY_ALLOC_FAILED;
6685     }
6686 
6687     // delete linkn key
6688     gap_drop_link_key_for_bd_addr(device);
6689 
6690     // configure LEVEL_2/3, dedicated bonding
6691     connection->state = SEND_CREATE_CONNECTION;
6692     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
6693     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
6694     connection->bonding_flags = BONDING_DEDICATED;
6695 
6696     // wait for GAP Security Result and send GAP Dedicated Bonding complete
6697 
6698     // handle: connnection failure (connection complete != ok)
6699     // handle: authentication failure
6700     // handle: disconnect on done
6701 
6702     hci_run();
6703 
6704     return 0;
6705 }
6706 
6707 void gap_set_local_name(const char * local_name){
6708     hci_stack->local_name = local_name;
6709     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
6710     // also update EIR if not set by user
6711     if (hci_stack->eir_data == NULL){
6712         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
6713     }
6714     hci_run();
6715 }
6716 #endif
6717 
6718 
6719 #ifdef ENABLE_BLE
6720 
6721 #ifdef ENABLE_LE_CENTRAL
6722 void gap_start_scan(void){
6723     hci_stack->le_scanning_enabled = true;
6724     hci_run();
6725 }
6726 
6727 void gap_stop_scan(void){
6728     hci_stack->le_scanning_enabled = false;
6729     hci_run();
6730 }
6731 
6732 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
6733     hci_stack->le_scan_type          = scan_type;
6734     hci_stack->le_scan_filter_policy = scanning_filter_policy;
6735     hci_stack->le_scan_interval      = scan_interval;
6736     hci_stack->le_scan_window        = scan_window;
6737     hci_stack->le_scanning_param_update = true;
6738     hci_run();
6739 }
6740 
6741 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
6742     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
6743 }
6744 
6745 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
6746     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
6747     if (!conn){
6748         // disallow if le connection is already outgoing
6749         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6750             log_error("le connection already active");
6751             return ERROR_CODE_COMMAND_DISALLOWED;
6752         }
6753 
6754         log_info("gap_connect: no connection exists yet, creating context");
6755         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
6756         if (!conn){
6757             // notify client that alloc failed
6758             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6759             log_info("gap_connect: failed to alloc hci_connection_t");
6760             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
6761         }
6762 
6763         // set le connecting state
6764         if (hci_is_le_connection_type(addr_type)){
6765             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
6766         }
6767 
6768         conn->state = SEND_CREATE_CONNECTION;
6769         log_info("gap_connect: send create connection next");
6770         hci_run();
6771         return ERROR_CODE_SUCCESS;
6772     }
6773 
6774     if (!hci_is_le_connection(conn) ||
6775         (conn->state == SEND_CREATE_CONNECTION) ||
6776         (conn->state == SENT_CREATE_CONNECTION)) {
6777         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
6778         log_error("gap_connect: classic connection or connect is already being created");
6779         return GATT_CLIENT_IN_WRONG_STATE;
6780     }
6781 
6782     // check if connection was just disconnected
6783     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
6784         log_info("gap_connect: send create connection (again)");
6785         conn->state = SEND_CREATE_CONNECTION;
6786         hci_run();
6787         return ERROR_CODE_SUCCESS;
6788     }
6789 
6790     log_info("gap_connect: context exists with state %u", conn->state);
6791     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
6792     hci_run();
6793     return ERROR_CODE_SUCCESS;
6794 }
6795 
6796 // @assumption: only a single outgoing LE Connection exists
6797 static hci_connection_t * gap_get_outgoing_connection(void){
6798     btstack_linked_item_t *it;
6799     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6800         hci_connection_t * conn = (hci_connection_t *) it;
6801         if (!hci_is_le_connection(conn)) continue;
6802         switch (conn->state){
6803             case SEND_CREATE_CONNECTION:
6804             case SENT_CREATE_CONNECTION:
6805             case SENT_CANCEL_CONNECTION:
6806                 return conn;
6807             default:
6808                 break;
6809         };
6810     }
6811     return NULL;
6812 }
6813 
6814 uint8_t gap_connect_cancel(void){
6815     hci_connection_t * conn = gap_get_outgoing_connection();
6816     if (!conn) return 0;
6817     switch (conn->state){
6818         case SEND_CREATE_CONNECTION:
6819             // skip sending create connection and emit event instead
6820             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6821             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
6822             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
6823             btstack_memory_hci_connection_free( conn );
6824             break;
6825         case SENT_CREATE_CONNECTION:
6826             // request to send cancel connection
6827             conn->state = SEND_CANCEL_CONNECTION;
6828             hci_run();
6829             break;
6830         default:
6831             break;
6832     }
6833     return 0;
6834 }
6835 
6836 /**
6837  * @brief Set connection parameters for outgoing connections
6838  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
6839  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
6840  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
6841  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
6842  * @param conn_latency, default: 4
6843  * @param supervision_timeout (unit: 10ms), default: 720 ms
6844  * @param min_ce_length (unit: 0.625ms), default: 10 ms
6845  * @param max_ce_length (unit: 0.625ms), default: 30 ms
6846  */
6847 
6848 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
6849     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
6850     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
6851     hci_stack->le_connection_scan_interval = conn_scan_interval;
6852     hci_stack->le_connection_scan_window = conn_scan_window;
6853     hci_stack->le_connection_interval_min = conn_interval_min;
6854     hci_stack->le_connection_interval_max = conn_interval_max;
6855     hci_stack->le_connection_latency = conn_latency;
6856     hci_stack->le_supervision_timeout = supervision_timeout;
6857     hci_stack->le_minimum_ce_length = min_ce_length;
6858     hci_stack->le_maximum_ce_length = max_ce_length;
6859 }
6860 #endif
6861 
6862 /**
6863  * @brief Updates the connection parameters for a given LE connection
6864  * @param handle
6865  * @param conn_interval_min (unit: 1.25ms)
6866  * @param conn_interval_max (unit: 1.25ms)
6867  * @param conn_latency
6868  * @param supervision_timeout (unit: 10ms)
6869  * @return 0 if ok
6870  */
6871 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6872     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6873     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6874     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6875     connection->le_conn_interval_min = conn_interval_min;
6876     connection->le_conn_interval_max = conn_interval_max;
6877     connection->le_conn_latency = conn_latency;
6878     connection->le_supervision_timeout = supervision_timeout;
6879     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
6880     hci_run();
6881     return 0;
6882 }
6883 
6884 /**
6885  * @brief Request an update of the connection parameter for a given LE connection
6886  * @param handle
6887  * @param conn_interval_min (unit: 1.25ms)
6888  * @param conn_interval_max (unit: 1.25ms)
6889  * @param conn_latency
6890  * @param supervision_timeout (unit: 10ms)
6891  * @return 0 if ok
6892  */
6893 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6894     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6895     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6896     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6897     connection->le_conn_interval_min = conn_interval_min;
6898     connection->le_conn_interval_max = conn_interval_max;
6899     connection->le_conn_latency = conn_latency;
6900     connection->le_supervision_timeout = supervision_timeout;
6901     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
6902     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
6903     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
6904     return 0;
6905 }
6906 
6907 #ifdef ENABLE_LE_PERIPHERAL
6908 
6909 /**
6910  * @brief Set Advertisement Data
6911  * @param advertising_data_length
6912  * @param advertising_data (max 31 octets)
6913  * @note data is not copied, pointer has to stay valid
6914  */
6915 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
6916     hci_stack->le_advertisements_data_len = advertising_data_length;
6917     hci_stack->le_advertisements_data = advertising_data;
6918     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6919     hci_run();
6920 }
6921 
6922 /**
6923  * @brief Set Scan Response Data
6924  * @param advertising_data_length
6925  * @param advertising_data (max 31 octets)
6926  * @note data is not copied, pointer has to stay valid
6927  */
6928 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
6929     hci_stack->le_scan_response_data_len = scan_response_data_length;
6930     hci_stack->le_scan_response_data = scan_response_data;
6931     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6932     hci_run();
6933 }
6934 
6935 /**
6936  * @brief Set Advertisement Parameters
6937  * @param adv_int_min
6938  * @param adv_int_max
6939  * @param adv_type
6940  * @param direct_address_type
6941  * @param direct_address
6942  * @param channel_map
6943  * @param filter_policy
6944  *
6945  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
6946  */
6947  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
6948     uint8_t direct_address_typ, bd_addr_t direct_address,
6949     uint8_t channel_map, uint8_t filter_policy) {
6950 
6951     hci_stack->le_advertisements_interval_min = adv_int_min;
6952     hci_stack->le_advertisements_interval_max = adv_int_max;
6953     hci_stack->le_advertisements_type = adv_type;
6954     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
6955     hci_stack->le_advertisements_channel_map = channel_map;
6956     hci_stack->le_advertisements_filter_policy = filter_policy;
6957     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
6958                  6);
6959 
6960     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6961     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
6962     hci_run();
6963  }
6964 
6965 /**
6966  * @brief Enable/Disable Advertisements
6967  * @param enabled
6968  */
6969 void gap_advertisements_enable(int enabled){
6970     if (enabled == 0){
6971         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
6972     } else {
6973         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
6974     }
6975     hci_update_advertisements_enabled_for_current_roles();
6976     hci_run();
6977 }
6978 
6979 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6980 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
6981     btstack_linked_list_iterator_t it;
6982     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6983     while (btstack_linked_list_iterator_has_next(&it)){
6984         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6985         if ( item->advertising_handle == advertising_handle ) {
6986             return item;
6987         }
6988     }
6989     return NULL;
6990 }
6991 
6992 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
6993     // find free advertisement handle
6994     uint8_t advertisement_handle;
6995     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
6996         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
6997     }
6998     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
6999     // clear
7000     memset(storage, 0, sizeof(le_advertising_set_t));
7001     // copy params
7002     storage->advertising_handle = advertisement_handle;
7003     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7004     // add to list
7005     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
7006     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7007     *out_advertising_handle = advertisement_handle;
7008     // set tasks and start
7009     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7010     hci_run();
7011     return ERROR_CODE_SUCCESS;
7012 }
7013 
7014 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
7015     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7016     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7017     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7018     // set tasks and start
7019     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7020     hci_run();
7021     return ERROR_CODE_SUCCESS;
7022 }
7023 
7024 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
7025     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7026     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7027     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
7028     return ERROR_CODE_SUCCESS;
7029 }
7030 
7031 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
7032     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7033     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7034     memcpy(advertising_set->random_address, random_address, 6);
7035     // set tasks and start
7036     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7037     hci_run();
7038     return ERROR_CODE_SUCCESS;
7039 }
7040 
7041 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
7042     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7043     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7044     advertising_set->adv_data = advertising_data;
7045     advertising_set->adv_data_len = advertising_data_length;
7046     // set tasks and start
7047     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7048     hci_run();
7049     return ERROR_CODE_SUCCESS;
7050 }
7051 
7052 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){
7053     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7054     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7055     advertising_set->scan_data = scan_response_data;
7056     advertising_set->scan_data_len = scan_response_data_length;
7057     // set tasks and start
7058     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7059     hci_run();
7060     return ERROR_CODE_SUCCESS;
7061 }
7062 
7063 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
7064     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7065     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7066     advertising_set->enable_timeout = timeout;
7067     advertising_set->enable_max_scan_events = num_extended_advertising_events;
7068     // set tasks and start
7069     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
7070     hci_run();
7071     return ERROR_CODE_SUCCESS;
7072 }
7073 
7074 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
7075     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7076     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7077     // set tasks and start
7078     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7079     hci_run();
7080     return ERROR_CODE_SUCCESS;
7081 }
7082 
7083 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
7084     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7085     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7086     // set tasks and start
7087     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
7088     hci_run();
7089     return ERROR_CODE_SUCCESS;
7090 }
7091 
7092 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7093 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
7094     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7095     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7096     // periodic advertising requires neither connectable, scannable, legacy or anonymous
7097     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7098     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
7099     // set tasks and start
7100     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
7101     hci_run();
7102     return ERROR_CODE_SUCCESS;
7103 }
7104 
7105 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
7106     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7107     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7108     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
7109     return ERROR_CODE_SUCCESS;
7110 }
7111 
7112 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
7113     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7114     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7115     advertising_set->periodic_data = periodic_data;
7116     advertising_set->periodic_data_len = periodic_data_length;
7117     // set tasks and start
7118     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
7119     hci_run();
7120     return ERROR_CODE_SUCCESS;
7121 }
7122 
7123 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
7124     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7125     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7126     // set tasks and start
7127     advertising_set->periodic_include_adi = include_adi;
7128     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7129     hci_run();
7130     return ERROR_CODE_SUCCESS;
7131 }
7132 
7133 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
7134     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7135     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7136     // set tasks and start
7137     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7138     hci_run();
7139     return ERROR_CODE_SUCCESS;
7140 }
7141 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
7142 
7143 #endif
7144 
7145 #endif
7146 
7147 void hci_le_set_own_address_type(uint8_t own_address_type){
7148     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
7149     if (own_address_type == hci_stack->le_own_addr_type) return;
7150     hci_stack->le_own_addr_type = own_address_type;
7151 
7152 #ifdef ENABLE_LE_PERIPHERAL
7153     // update advertisement parameters, too
7154     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7155     hci_run();
7156 #endif
7157 #ifdef ENABLE_LE_CENTRAL
7158     // note: we don't update scan parameters or modify ongoing connection attempts
7159 #endif
7160 }
7161 
7162 void hci_le_random_address_set(const bd_addr_t random_address){
7163     memcpy(hci_stack->le_random_address, random_address, 6);
7164     hci_stack->le_random_address_set = true;
7165     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7166     hci_run();
7167 }
7168 
7169 #endif
7170 
7171 uint8_t gap_disconnect(hci_con_handle_t handle){
7172     hci_connection_t * conn = hci_connection_for_handle(handle);
7173     if (!conn){
7174         hci_emit_disconnection_complete(handle, 0);
7175         return 0;
7176     }
7177     // ignore if already disconnected
7178     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7179         return 0;
7180     }
7181     conn->state = SEND_DISCONNECT;
7182     hci_run();
7183     return 0;
7184 }
7185 
7186 int gap_read_rssi(hci_con_handle_t con_handle){
7187     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7188     if (hci_connection == NULL) return 0;
7189     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
7190     hci_run();
7191     return 1;
7192 }
7193 
7194 /**
7195  * @brief Get connection type
7196  * @param con_handle
7197  * @result connection_type
7198  */
7199 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
7200     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7201     if (!conn) return GAP_CONNECTION_INVALID;
7202     switch (conn->address_type){
7203         case BD_ADDR_TYPE_LE_PUBLIC:
7204         case BD_ADDR_TYPE_LE_RANDOM:
7205             return GAP_CONNECTION_LE;
7206         case BD_ADDR_TYPE_SCO:
7207             return GAP_CONNECTION_SCO;
7208         case BD_ADDR_TYPE_ACL:
7209             return GAP_CONNECTION_ACL;
7210         default:
7211             return GAP_CONNECTION_INVALID;
7212     }
7213 }
7214 
7215 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
7216     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7217     if (!conn) return HCI_ROLE_INVALID;
7218     return (hci_role_t) conn->role;
7219 }
7220 
7221 
7222 #ifdef ENABLE_CLASSIC
7223 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
7224     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7225     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7226     conn->request_role = role;
7227     hci_run();
7228     return ERROR_CODE_SUCCESS;
7229 }
7230 #endif
7231 
7232 #ifdef ENABLE_BLE
7233 
7234 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){
7235     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7236     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7237 
7238     conn->le_phy_update_all_phys    = all_phys;
7239     conn->le_phy_update_tx_phys     = tx_phys;
7240     conn->le_phy_update_rx_phys     = rx_phys;
7241     conn->le_phy_update_phy_options = phy_options;
7242 
7243     hci_run();
7244 
7245     return 0;
7246 }
7247 
7248 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
7249     // check if already in list
7250     btstack_linked_list_iterator_t it;
7251     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7252     while (btstack_linked_list_iterator_has_next(&it)) {
7253         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
7254         if (entry->address_type != address_type) {
7255             continue;
7256         }
7257         if (memcmp(entry->address, address, 6) != 0) {
7258             continue;
7259         }
7260 		// disallow if already scheduled to add
7261 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
7262 			return ERROR_CODE_COMMAND_DISALLOWED;
7263 		}
7264 		// still on controller, but scheduled to remove -> re-add
7265 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
7266 		return ERROR_CODE_SUCCESS;
7267     }
7268     // alloc and add to list
7269     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
7270     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
7271     entry->address_type = address_type;
7272     (void)memcpy(entry->address, address, 6);
7273     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
7274     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
7275     return ERROR_CODE_SUCCESS;
7276 }
7277 
7278 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7279     btstack_linked_list_iterator_t it;
7280     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7281     while (btstack_linked_list_iterator_has_next(&it)){
7282         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7283         if (entry->address_type != address_type) {
7284             continue;
7285         }
7286         if (memcmp(entry->address, address, 6) != 0) {
7287             continue;
7288         }
7289         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7290             // remove from controller if already present
7291             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7292         }  else {
7293             // directly remove entry from whitelist
7294             btstack_linked_list_iterator_remove(&it);
7295             btstack_memory_whitelist_entry_free(entry);
7296         }
7297         return ERROR_CODE_SUCCESS;
7298     }
7299     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7300 }
7301 
7302 static void hci_whitelist_clear(void){
7303     btstack_linked_list_iterator_t it;
7304     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7305     while (btstack_linked_list_iterator_has_next(&it)){
7306         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7307         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7308             // remove from controller if already present
7309             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7310             continue;
7311         }
7312         // directly remove entry from whitelist
7313         btstack_linked_list_iterator_remove(&it);
7314         btstack_memory_whitelist_entry_free(entry);
7315     }
7316 }
7317 
7318 // free all entries unconditionally
7319 static void hci_whitelist_free(void){
7320     btstack_linked_list_iterator_t lit;
7321     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
7322     while (btstack_linked_list_iterator_has_next(&lit)){
7323         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
7324         btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
7325         btstack_memory_whitelist_entry_free(entry);
7326     }
7327 }
7328 
7329 /**
7330  * @brief Clear Whitelist
7331  * @return 0 if ok
7332  */
7333 uint8_t gap_whitelist_clear(void){
7334     hci_whitelist_clear();
7335     hci_run();
7336     return ERROR_CODE_SUCCESS;
7337 }
7338 
7339 /**
7340  * @brief Add Device to Whitelist
7341  * @param address_typ
7342  * @param address
7343  * @return 0 if ok
7344  */
7345 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
7346     uint8_t status = hci_whitelist_add(address_type, address);
7347     if (status){
7348         return status;
7349     }
7350     hci_run();
7351     return ERROR_CODE_SUCCESS;
7352 }
7353 
7354 /**
7355  * @brief Remove Device from Whitelist
7356  * @param address_typ
7357  * @param address
7358  * @return 0 if ok
7359  */
7360 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7361     uint8_t status = hci_whitelist_remove(address_type, address);
7362     if (status){
7363         return status;
7364     }
7365     hci_run();
7366     return ERROR_CODE_SUCCESS;
7367 }
7368 
7369 #ifdef ENABLE_LE_CENTRAL
7370 /**
7371  * @brief Connect with Whitelist
7372  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
7373  * @return - if ok
7374  */
7375 uint8_t gap_connect_with_whitelist(void){
7376     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7377         return ERROR_CODE_COMMAND_DISALLOWED;
7378     }
7379     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
7380     hci_run();
7381     return ERROR_CODE_SUCCESS;
7382 }
7383 
7384 /**
7385  * @brief Auto Connection Establishment - Start Connecting to device
7386  * @param address_typ
7387  * @param address
7388  * @return 0 if ok
7389  */
7390 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
7391     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
7392         return ERROR_CODE_COMMAND_DISALLOWED;
7393     }
7394 
7395     uint8_t status = hci_whitelist_add(address_type, address);
7396     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
7397         return status;
7398     }
7399 
7400     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
7401 
7402     hci_run();
7403     return ERROR_CODE_SUCCESS;
7404 }
7405 
7406 /**
7407  * @brief Auto Connection Establishment - Stop Connecting to device
7408  * @param address_typ
7409  * @param address
7410  * @return 0 if ok
7411  */
7412 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
7413     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
7414         return ERROR_CODE_COMMAND_DISALLOWED;
7415     }
7416 
7417     hci_whitelist_remove(address_type, address);
7418     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
7419         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7420     }
7421     hci_run();
7422     return 0;
7423 }
7424 
7425 /**
7426  * @brief Auto Connection Establishment - Stop everything
7427  * @note  Convenience function to stop all active auto connection attempts
7428  */
7429 uint8_t gap_auto_connection_stop_all(void){
7430     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
7431         return ERROR_CODE_COMMAND_DISALLOWED;
7432     }
7433     hci_whitelist_clear();
7434     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7435     hci_run();
7436     return ERROR_CODE_SUCCESS;
7437 }
7438 
7439 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
7440     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7441     if (!conn) return 0;
7442     return conn->le_connection_interval;
7443 }
7444 #endif
7445 #endif
7446 
7447 #ifdef ENABLE_CLASSIC
7448 /**
7449  * @brief Set Extended Inquiry Response data
7450  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
7451  * @note has to be done before stack starts up
7452  */
7453 void gap_set_extended_inquiry_response(const uint8_t * data){
7454     hci_stack->eir_data = data;
7455     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7456     hci_run();
7457 }
7458 
7459 /**
7460  * @brief Start GAP Classic Inquiry
7461  * @param duration in 1.28s units
7462  * @return 0 if ok
7463  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
7464  */
7465 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
7466     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
7467     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7468     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
7469         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7470     }
7471     hci_stack->inquiry_state = duration_in_1280ms_units;
7472     hci_run();
7473     return 0;
7474 }
7475 
7476 /**
7477  * @brief Stop GAP Classic Inquiry
7478  * @return 0 if ok
7479  */
7480 int gap_inquiry_stop(void){
7481     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
7482         // emit inquiry complete event, before it even started
7483         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
7484         hci_emit_event(event, sizeof(event), 1);
7485         return 0;
7486     }
7487     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
7488     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
7489     hci_run();
7490     return 0;
7491 }
7492 
7493 void gap_inquiry_set_lap(uint32_t lap){
7494     hci_stack->inquiry_lap = lap;
7495 }
7496 
7497 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
7498     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
7499     hci_stack->inquiry_scan_window   = inquiry_scan_window;
7500     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
7501     hci_run();
7502 }
7503 
7504 
7505 /**
7506  * @brief Remote Name Request
7507  * @param addr
7508  * @param page_scan_repetition_mode
7509  * @param clock_offset only used when bit 15 is set
7510  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
7511  */
7512 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
7513     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7514     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
7515     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
7516     hci_stack->remote_name_clock_offset = clock_offset;
7517     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
7518     hci_run();
7519     return 0;
7520 }
7521 
7522 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
7523     hci_stack->gap_pairing_state = state;
7524     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
7525     hci_run();
7526     return 0;
7527 }
7528 
7529 /**
7530  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
7531  * @param addr
7532  * @param pin_data
7533  * @param pin_len
7534  * @return 0 if ok
7535  */
7536 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
7537     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7538     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
7539     hci_stack->gap_pairing_pin_len = pin_len;
7540     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
7541 }
7542 
7543 /**
7544  * @brief Legacy Pairing Pin Code Response
7545  * @param addr
7546  * @param pin
7547  * @return 0 if ok
7548  */
7549 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
7550     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
7551 }
7552 
7553 /**
7554  * @brief Abort Legacy Pairing
7555  * @param addr
7556  * @param pin
7557  * @return 0 if ok
7558  */
7559 int gap_pin_code_negative(bd_addr_t addr){
7560     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7561     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
7562 }
7563 
7564 /**
7565  * @brief SSP Passkey Response
7566  * @param addr
7567  * @param passkey
7568  * @return 0 if ok
7569  */
7570 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
7571     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7572     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
7573     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
7574 }
7575 
7576 /**
7577  * @brief Abort SSP Passkey Entry/Pairing
7578  * @param addr
7579  * @param pin
7580  * @return 0 if ok
7581  */
7582 int gap_ssp_passkey_negative(const bd_addr_t addr){
7583     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7584     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
7585 }
7586 
7587 /**
7588  * @brief Accept SSP Numeric Comparison
7589  * @param addr
7590  * @param passkey
7591  * @return 0 if ok
7592  */
7593 int gap_ssp_confirmation_response(const bd_addr_t addr){
7594     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7595     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
7596 }
7597 
7598 /**
7599  * @brief Abort SSP Numeric Comparison/Pairing
7600  * @param addr
7601  * @param pin
7602  * @return 0 if ok
7603  */
7604 int gap_ssp_confirmation_negative(const bd_addr_t addr){
7605     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7606     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
7607 }
7608 
7609 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
7610 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
7611     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7612     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7613     connectionSetAuthenticationFlags(conn, flag);
7614     hci_run();
7615     return ERROR_CODE_SUCCESS;
7616 }
7617 #endif
7618 
7619 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
7620 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
7621     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7622 }
7623 
7624 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
7625     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
7626 }
7627 #endif
7628 
7629 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7630 /**
7631  * @brief Report Remote OOB Data
7632  * @param bd_addr
7633  * @param c_192 Simple Pairing Hash C derived from P-192 public key
7634  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
7635  * @param c_256 Simple Pairing Hash C derived from P-256 public key
7636  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
7637  */
7638 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){
7639     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7640     if (connection == NULL) {
7641         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7642     }
7643     connection->classic_oob_c_192 = c_192;
7644     connection->classic_oob_r_192 = r_192;
7645 
7646     // ignore P-256 if not supported by us
7647     if (hci_stack->secure_connections_active){
7648         connection->classic_oob_c_256 = c_256;
7649         connection->classic_oob_r_256 = r_256;
7650     }
7651 
7652     return ERROR_CODE_SUCCESS;
7653 }
7654 /**
7655  * @brief Generate new OOB data
7656  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
7657  */
7658 void gap_ssp_generate_oob_data(void){
7659     hci_stack->classic_read_local_oob_data = true;
7660     hci_run();
7661 }
7662 
7663 #endif
7664 
7665 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
7666 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
7667     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7668     if (connection == NULL) {
7669         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7670     }
7671 
7672     memcpy(connection->link_key, link_key, sizeof(link_key_t));
7673     connection->link_key_type = type;
7674 
7675     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
7676 }
7677 
7678 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
7679 /**
7680  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
7681  * @param inquiry_mode see bluetooth_defines.h
7682  */
7683 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
7684     hci_stack->inquiry_mode = inquiry_mode;
7685 }
7686 
7687 /**
7688  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
7689  */
7690 void hci_set_sco_voice_setting(uint16_t voice_setting){
7691     hci_stack->sco_voice_setting = voice_setting;
7692 }
7693 
7694 /**
7695  * @brief Get SCO Voice Setting
7696  * @return current voice setting
7697  */
7698 uint16_t hci_get_sco_voice_setting(void){
7699     return hci_stack->sco_voice_setting;
7700 }
7701 
7702 static int hci_have_usb_transport(void){
7703     if (!hci_stack->hci_transport) return 0;
7704     const char * transport_name = hci_stack->hci_transport->name;
7705     if (!transport_name) return 0;
7706     return (transport_name[0] == 'H') && (transport_name[1] == '2');
7707 }
7708 
7709 /** @brief Get SCO packet length for current SCO Voice setting
7710  *  @note  Using SCO packets of the exact length is required for USB transfer
7711  *  @return Length of SCO packets in bytes (not audio frames)
7712  */
7713 uint16_t hci_get_sco_packet_length(void){
7714     uint16_t sco_packet_length = 0;
7715 
7716 #ifdef ENABLE_SCO_OVER_HCI
7717     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
7718     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
7719 
7720     if (hci_have_usb_transport()){
7721         // see Core Spec for H2 USB Transfer.
7722         // 3 byte SCO header + 24 bytes per connection
7723         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
7724         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
7725     } else {
7726         // 3 byte SCO header + SCO packet size over the air (60 bytes)
7727         sco_packet_length = 3 + 60 * multiplier;
7728         // assert that it still fits inside an SCO buffer
7729         if (sco_packet_length > hci_stack->sco_data_packet_length){
7730             sco_packet_length = 3 + 60;
7731         }
7732     }
7733 #endif
7734 
7735 #ifdef HAVE_SCO_TRANSPORT
7736     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
7737     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
7738     sco_packet_length = 3 + 60 * multiplier;
7739 #endif
7740     return sco_packet_length;
7741 }
7742 
7743 /**
7744 * @brief Sets the master/slave policy
7745 * @param policy (0: attempt to become master, 1: let connecting device decide)
7746 */
7747 void hci_set_master_slave_policy(uint8_t policy){
7748     hci_stack->master_slave_policy = policy;
7749 }
7750 
7751 #endif
7752 
7753 HCI_STATE hci_get_state(void){
7754     return hci_stack->state;
7755 }
7756 
7757 #ifdef ENABLE_CLASSIC
7758 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
7759     hci_stack->gap_classic_accept_callback = accept_callback;
7760 }
7761 #endif
7762 
7763 /**
7764  * @brief Set callback for Bluetooth Hardware Error
7765  */
7766 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
7767     hci_stack->hardware_error_callback = fn;
7768 }
7769 
7770 void hci_disconnect_all(void){
7771     btstack_linked_list_iterator_t it;
7772     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
7773     while (btstack_linked_list_iterator_has_next(&it)){
7774         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
7775         if (con->state == SENT_DISCONNECT) continue;
7776         con->state = SEND_DISCONNECT;
7777     }
7778     hci_run();
7779 }
7780 
7781 uint16_t hci_get_manufacturer(void){
7782     return hci_stack->manufacturer;
7783 }
7784 
7785 #ifdef ENABLE_BLE
7786 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
7787     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
7788     if (!hci_con) return NULL;
7789     return &hci_con->sm_connection;
7790 }
7791 
7792 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
7793 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
7794 #endif
7795 
7796 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
7797     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7798     if (hci_connection == NULL) return 0;
7799     if (hci_is_le_connection(hci_connection)){
7800 #ifdef ENABLE_BLE
7801         sm_connection_t * sm_conn = &hci_connection->sm_connection;
7802         if (sm_conn->sm_connection_encrypted) {
7803             return sm_conn->sm_actual_encryption_key_size;
7804         }
7805 #endif
7806     } else {
7807 #ifdef ENABLE_CLASSIC
7808         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
7809             return hci_connection->encryption_key_size;
7810         }
7811 #endif
7812     }
7813     return 0;
7814 }
7815 
7816 bool gap_authenticated(hci_con_handle_t con_handle){
7817     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7818     if (hci_connection == NULL) return false;
7819 
7820     switch (hci_connection->address_type){
7821 #ifdef ENABLE_BLE
7822         case BD_ADDR_TYPE_LE_PUBLIC:
7823         case BD_ADDR_TYPE_LE_RANDOM:
7824             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
7825             return hci_connection->sm_connection.sm_connection_authenticated != 0;
7826 #endif
7827 #ifdef ENABLE_CLASSIC
7828         case BD_ADDR_TYPE_SCO:
7829         case BD_ADDR_TYPE_ACL:
7830             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
7831 #endif
7832         default:
7833             return false;
7834     }
7835 }
7836 
7837 bool gap_secure_connection(hci_con_handle_t con_handle){
7838     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7839     if (hci_connection == NULL) return 0;
7840 
7841     switch (hci_connection->address_type){
7842 #ifdef ENABLE_BLE
7843         case BD_ADDR_TYPE_LE_PUBLIC:
7844         case BD_ADDR_TYPE_LE_RANDOM:
7845             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
7846             return hci_connection->sm_connection.sm_connection_sc != 0;
7847 #endif
7848 #ifdef ENABLE_CLASSIC
7849         case BD_ADDR_TYPE_SCO:
7850         case BD_ADDR_TYPE_ACL:
7851             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
7852 #endif
7853         default:
7854             return false;
7855     }
7856 }
7857 
7858 bool gap_bonded(hci_con_handle_t con_handle){
7859 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7860 	if (hci_connection == NULL) return 0;
7861 
7862 #ifdef ENABLE_CLASSIC
7863 	link_key_t link_key;
7864 	link_key_type_t link_key_type;
7865 #endif
7866 	switch (hci_connection->address_type){
7867 #ifdef ENABLE_BLE
7868 		case BD_ADDR_TYPE_LE_PUBLIC:
7869 		case BD_ADDR_TYPE_LE_RANDOM:
7870 			return hci_connection->sm_connection.sm_le_db_index >= 0;
7871 #endif
7872 #ifdef ENABLE_CLASSIC
7873 		case BD_ADDR_TYPE_SCO:
7874 		case BD_ADDR_TYPE_ACL:
7875 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
7876 #endif
7877 		default:
7878 			return false;
7879 	}
7880 }
7881 
7882 #ifdef ENABLE_BLE
7883 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
7884     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
7885     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
7886     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
7887     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
7888     return sm_conn->sm_connection_authorization_state;
7889 }
7890 #endif
7891 
7892 #ifdef ENABLE_CLASSIC
7893 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){
7894     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7895     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7896     conn->sniff_min_interval = sniff_min_interval;
7897     conn->sniff_max_interval = sniff_max_interval;
7898     conn->sniff_attempt = sniff_attempt;
7899     conn->sniff_timeout = sniff_timeout;
7900     hci_run();
7901     return 0;
7902 }
7903 
7904 /**
7905  * @brief Exit Sniff mode
7906  * @param con_handle
7907  @ @return 0 if ok
7908  */
7909 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
7910     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7911     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7912     conn->sniff_min_interval = 0xffff;
7913     hci_run();
7914     return 0;
7915 }
7916 
7917 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){
7918     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7919     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7920     conn->sniff_subrating_max_latency = max_latency;
7921     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
7922     conn->sniff_subrating_min_local_timeout = min_local_timeout;
7923     hci_run();
7924     return ERROR_CODE_SUCCESS;
7925 }
7926 
7927 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){
7928     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7929     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7930     conn->qos_service_type = service_type;
7931     conn->qos_token_rate = token_rate;
7932     conn->qos_peak_bandwidth = peak_bandwidth;
7933     conn->qos_latency = latency;
7934     conn->qos_delay_variation = delay_variation;
7935     hci_run();
7936     return ERROR_CODE_SUCCESS;
7937 }
7938 
7939 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
7940     hci_stack->new_page_scan_interval = page_scan_interval;
7941     hci_stack->new_page_scan_window = page_scan_window;
7942     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
7943     hci_run();
7944 }
7945 
7946 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
7947     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
7948     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
7949     hci_run();
7950 }
7951 
7952 void gap_set_page_timeout(uint16_t page_timeout){
7953     hci_stack->page_timeout = page_timeout;
7954     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
7955     hci_run();
7956 }
7957 
7958 #endif
7959 
7960 void hci_halting_defer(void){
7961     if (hci_stack->state != HCI_STATE_HALTING) return;
7962     switch (hci_stack->substate){
7963         case HCI_HALTING_READY_FOR_CLOSE:
7964             hci_stack->substate = HCI_HALTING_DEFER_CLOSE;
7965             break;
7966         default:
7967             break;
7968     }
7969 }
7970 
7971 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
7972 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
7973     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
7974     if (le_device_db_index >= le_device_db_max_count()) return;
7975     uint8_t offset = le_device_db_index >> 3;
7976     uint8_t mask = 1 << (le_device_db_index & 7);
7977     hci_stack->le_resolving_list_add_entries[offset] |= mask;
7978     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
7979     	// note: go back to remove entries, otherwise, a remove + add will skip the add
7980         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
7981     }
7982 }
7983 
7984 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
7985 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
7986 	if (le_device_db_index >= le_device_db_max_count()) return;
7987 	uint8_t offset = le_device_db_index >> 3;
7988 	uint8_t mask = 1 << (le_device_db_index & 7);
7989 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
7990 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
7991 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
7992 	}
7993 }
7994 
7995 uint8_t gap_load_resolving_list_from_le_device_db(void){
7996     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
7997 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
7998 	}
7999 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
8000 		// restart le resolving list update
8001 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
8002 	}
8003 	return ERROR_CODE_SUCCESS;
8004 }
8005 #endif
8006 
8007 #ifdef ENABLE_BLE
8008 #ifdef ENABLE_LE_CENTRAL
8009 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8010 
8011 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8012     // check if already in list
8013     btstack_linked_list_iterator_t it;
8014     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8015     while (btstack_linked_list_iterator_has_next(&it)) {
8016         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
8017         if (entry->sid != advertising_sid) {
8018             continue;
8019         }
8020         if (entry->address_type != address_type) {
8021             continue;
8022         }
8023         if (memcmp(entry->address, address, 6) != 0) {
8024             continue;
8025         }
8026         // disallow if already scheduled to add
8027         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
8028             return ERROR_CODE_COMMAND_DISALLOWED;
8029         }
8030         // still on controller, but scheduled to remove -> re-add
8031         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8032         return ERROR_CODE_SUCCESS;
8033     }
8034     // alloc and add to list
8035     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
8036     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8037     entry->sid = advertising_sid;
8038     entry->address_type = address_type;
8039     (void)memcpy(entry->address, address, 6);
8040     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8041     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
8042     return ERROR_CODE_SUCCESS;
8043 }
8044 
8045 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8046     btstack_linked_list_iterator_t it;
8047     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8048     while (btstack_linked_list_iterator_has_next(&it)){
8049         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8050         if (entry->sid != advertising_sid) {
8051             continue;
8052         }
8053         if (entry->address_type != address_type) {
8054             continue;
8055         }
8056         if (memcmp(entry->address, address, 6) != 0) {
8057             continue;
8058         }
8059         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8060             // remove from controller if already present
8061             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8062         }  else {
8063             // directly remove entry from whitelist
8064             btstack_linked_list_iterator_remove(&it);
8065             btstack_memory_periodic_advertiser_list_entry_free(entry);
8066         }
8067         return ERROR_CODE_SUCCESS;
8068     }
8069     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8070 }
8071 
8072 static void hci_periodic_advertiser_list_clear(void){
8073     btstack_linked_list_iterator_t it;
8074     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8075     while (btstack_linked_list_iterator_has_next(&it)){
8076         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8077         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8078             // remove from controller if already present
8079             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8080             continue;
8081         }
8082         // directly remove entry from whitelist
8083         btstack_linked_list_iterator_remove(&it);
8084         btstack_memory_periodic_advertiser_list_entry_free(entry);
8085     }
8086 }
8087 
8088 // free all entries unconditionally
8089 static void hci_periodic_advertiser_list_free(void){
8090     btstack_linked_list_iterator_t lit;
8091     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
8092     while (btstack_linked_list_iterator_has_next(&lit)){
8093         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
8094         btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
8095         btstack_memory_periodic_advertiser_list_entry_free(entry);
8096     }
8097 }
8098 
8099 uint8_t gap_periodic_advertiser_list_clear(void){
8100     hci_periodic_advertiser_list_clear();
8101     hci_run();
8102     return ERROR_CODE_SUCCESS;
8103 }
8104 
8105 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8106     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
8107     if (status){
8108         return status;
8109     }
8110     hci_run();
8111     return ERROR_CODE_SUCCESS;
8112 }
8113 
8114 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8115     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
8116     if (status){
8117         return status;
8118     }
8119     hci_run();
8120     return ERROR_CODE_SUCCESS;
8121 }
8122 
8123 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
8124                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
8125     // abort if already active
8126     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
8127         return ERROR_CODE_COMMAND_DISALLOWED;
8128     }
8129     // store request
8130     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
8131     hci_stack->le_periodic_sync_options = options;
8132     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
8133     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
8134     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
8135     hci_stack->le_periodic_sync_skip = skip;
8136     hci_stack->le_periodic_sync_timeout = sync_timeout;
8137     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
8138 
8139     hci_run();
8140     return ERROR_CODE_SUCCESS;
8141 }
8142 
8143 uint8_t gap_periodic_advertising_create_sync_cancel(void){
8144     // abort if not requested
8145     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
8146         return ERROR_CODE_COMMAND_DISALLOWED;
8147     }
8148     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
8149     hci_run();
8150     return ERROR_CODE_SUCCESS;
8151 }
8152 
8153 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
8154     // how do we track these syncs?
8155     return ERROR_CODE_UNKNOWN_HCI_COMMAND;
8156 }
8157 
8158 #endif
8159 #endif
8160 #endif
8161 
8162 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
8163 void hci_setup_test_connections_fuzz(void){
8164     hci_connection_t * conn;
8165 
8166     // default address: 66:55:44:33:00:01
8167     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
8168 
8169     // setup Controller info
8170     hci_stack->num_cmd_packets = 255;
8171     hci_stack->acl_packets_total_num = 255;
8172 
8173     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
8174     addr[5] = 0x01;
8175     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8176     conn->con_handle = addr[5];
8177     conn->role  = HCI_ROLE_SLAVE;
8178     conn->state = RECEIVED_CONNECTION_REQUEST;
8179     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8180 
8181     // setup incoming Classic SCO connection with con handle 0x0002
8182     addr[5] = 0x02;
8183     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
8184     conn->con_handle = addr[5];
8185     conn->role  = HCI_ROLE_SLAVE;
8186     conn->state = RECEIVED_CONNECTION_REQUEST;
8187     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8188 
8189     // setup ready Classic ACL connection with con handle 0x0003
8190     addr[5] = 0x03;
8191     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8192     conn->con_handle = addr[5];
8193     conn->role  = HCI_ROLE_SLAVE;
8194     conn->state = OPEN;
8195     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8196 
8197     // setup ready Classic SCO connection with con handle 0x0004
8198     addr[5] = 0x04;
8199     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
8200     conn->con_handle = addr[5];
8201     conn->role  = HCI_ROLE_SLAVE;
8202     conn->state = OPEN;
8203     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8204 
8205     // setup ready LE ACL connection with con handle 0x005 and public address
8206     addr[5] = 0x05;
8207     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
8208     conn->con_handle = addr[5];
8209     conn->role  = HCI_ROLE_SLAVE;
8210     conn->state = OPEN;
8211     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8212     conn->sm_connection.sm_connection_encrypted = 1;
8213 }
8214 
8215 void hci_free_connections_fuzz(void){
8216     btstack_linked_list_iterator_t it;
8217     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
8218     while (btstack_linked_list_iterator_has_next(&it)){
8219         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
8220         btstack_linked_list_iterator_remove(&it);
8221         btstack_memory_hci_connection_free(con);
8222     }
8223 }
8224 void hci_simulate_working_fuzz(void){
8225     hci_stack->le_scanning_param_update = false;
8226     hci_init_done();
8227     hci_stack->num_cmd_packets = 255;
8228 }
8229 #endif
8230