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