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