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