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