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