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