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