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