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