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