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