xref: /btstack/src/hci.c (revision dbf84c8a4e5f19f37bf9128db249cb40829b9966)
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     switch (hci_stack->state) {
6056         case HCI_STATE_INITIALIZING:
6057             hci_initializing_run();
6058             break;
6059         case HCI_STATE_HALTING:
6060             hci_halting_run();
6061             break;
6062         case HCI_STATE_FALLING_ASLEEP:
6063             hci_falling_asleep_run();
6064             break;
6065         default:
6066             break;
6067     }
6068 
6069     // allow to run after initialization to working transition
6070     if (hci_stack->state != HCI_STATE_WORKING){
6071         return;
6072     }
6073 
6074     bool done;
6075 
6076     // send continuation fragments first, as they block the prepared packet buffer
6077     done = hci_run_acl_fragments();
6078     if (done) return;
6079 
6080 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
6081     // send host num completed packets next as they don't require num_cmd_packets > 0
6082     if (!hci_can_send_comand_packet_transport()) return;
6083     if (hci_stack->host_completed_packets){
6084         hci_host_num_completed_packets();
6085         return;
6086     }
6087 #endif
6088 
6089     if (!hci_can_send_command_packet_now()) return;
6090 
6091     // global/non-connection oriented commands
6092 
6093 
6094 #ifdef ENABLE_CLASSIC
6095     // general gap classic
6096     done = hci_run_general_gap_classic();
6097     if (done) return;
6098 #endif
6099 
6100 #ifdef ENABLE_BLE
6101     // general gap le
6102     done = hci_run_general_gap_le();
6103     if (done) return;
6104 #endif
6105 
6106     // send pending HCI commands
6107     hci_run_general_pending_commands();
6108 }
6109 
6110 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
6111     // house-keeping
6112 
6113 #ifdef ENABLE_CLASSIC
6114     bd_addr_t addr;
6115     hci_connection_t * conn;
6116 #endif
6117 #ifdef ENABLE_LE_CENTRAL
6118     uint8_t initiator_filter_policy;
6119 #endif
6120 
6121     uint16_t opcode = little_endian_read_16(packet, 0);
6122     switch (opcode) {
6123         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
6124             hci_stack->loopback_mode = packet[3];
6125             break;
6126 
6127 #ifdef ENABLE_CLASSIC
6128         case HCI_OPCODE_HCI_CREATE_CONNECTION:
6129             reverse_bd_addr(&packet[3], addr);
6130             log_info("Create_connection to %s", bd_addr_to_str(addr));
6131 
6132             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
6133             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
6134                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
6135                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
6136             }
6137 
6138             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6139             if (!conn) {
6140                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6141                 if (!conn) {
6142                     // notify client that alloc failed
6143                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6144                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
6145                 }
6146                 conn->state = SEND_CREATE_CONNECTION;
6147                 conn->role  = HCI_ROLE_MASTER;
6148             }
6149 
6150             log_info("conn state %u", conn->state);
6151             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
6152             switch (conn->state) {
6153                 // if connection active exists
6154                 case OPEN:
6155                     // and OPEN, emit connection complete command
6156                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
6157                     // packet not sent to controller
6158                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6159                 case RECEIVED_DISCONNECTION_COMPLETE:
6160                     // create connection triggered in disconnect complete event, let's do it now
6161                     break;
6162                 case SEND_CREATE_CONNECTION:
6163 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
6164                     if (hci_classic_operation_active()){
6165                         return ERROR_CODE_SUCCESS;
6166                     }
6167 #endif
6168                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
6169                     break;
6170                 default:
6171                     // otherwise, just ignore as it is already in the open process
6172                     // packet not sent to controller
6173                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6174             }
6175             conn->state = SENT_CREATE_CONNECTION;
6176 
6177             // track outgoing connection
6178             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
6179             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
6180             break;
6181 
6182 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
6183         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
6184             // setup_synchronous_connection? Voice setting at offset 22
6185             // TODO: compare to current setting if sco connection already active
6186             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
6187             break;
6188         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
6189             // accept_synchronous_connection? Voice setting at offset 18
6190             // TODO: compare to current setting if sco connection already active
6191             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
6192             // track outgoing connection
6193             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
6194             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
6195             break;
6196 #endif
6197 #endif
6198 
6199 #ifdef ENABLE_BLE
6200 #ifdef ENABLE_LE_CENTRAL
6201         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
6202             // white list used?
6203             initiator_filter_policy = packet[7];
6204             switch (initiator_filter_policy) {
6205                 case 0:
6206                     // whitelist not used
6207                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
6208                     break;
6209                 case 1:
6210                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
6211                     break;
6212                 default:
6213                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
6214                     break;
6215             }
6216             // track outgoing connection
6217             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
6218             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
6219             break;
6220         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
6221             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
6222             break;
6223 #endif
6224 #endif
6225         default:
6226             break;
6227     }
6228 
6229     hci_stack->num_cmd_packets--;
6230 
6231     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
6232     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
6233     if (err != 0){
6234         return ERROR_CODE_HARDWARE_FAILURE;
6235     }
6236     return ERROR_CODE_SUCCESS;
6237 }
6238 
6239 // disconnect because of security block
6240 void hci_disconnect_security_block(hci_con_handle_t con_handle){
6241     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6242     if (!connection) return;
6243     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
6244 }
6245 
6246 
6247 // Configure Secure Simple Pairing
6248 
6249 #ifdef ENABLE_CLASSIC
6250 
6251 // enable will enable SSP during init
6252 void gap_ssp_set_enable(int enable){
6253     hci_stack->ssp_enable = enable;
6254 }
6255 
6256 static int hci_local_ssp_activated(void){
6257     return gap_ssp_supported() && hci_stack->ssp_enable;
6258 }
6259 
6260 // if set, BTstack will respond to io capability request using authentication requirement
6261 void gap_ssp_set_io_capability(int io_capability){
6262     hci_stack->ssp_io_capability = io_capability;
6263 }
6264 void gap_ssp_set_authentication_requirement(int authentication_requirement){
6265     hci_stack->ssp_authentication_requirement = authentication_requirement;
6266 }
6267 
6268 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
6269 void gap_ssp_set_auto_accept(int auto_accept){
6270     hci_stack->ssp_auto_accept = auto_accept;
6271 }
6272 
6273 void gap_secure_connections_enable(bool enable){
6274     hci_stack->secure_connections_enable = enable;
6275 }
6276 bool gap_secure_connections_active(void){
6277     return hci_stack->secure_connections_active;
6278 }
6279 
6280 #endif
6281 
6282 // va_list part of hci_send_cmd
6283 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
6284     if (!hci_can_send_command_packet_now()){
6285         log_error("hci_send_cmd called but cannot send packet now");
6286         return ERROR_CODE_COMMAND_DISALLOWED;
6287     }
6288 
6289     // for HCI INITIALIZATION
6290     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
6291     hci_stack->last_cmd_opcode = cmd->opcode;
6292 
6293     hci_reserve_packet_buffer();
6294     uint8_t * packet = hci_stack->hci_packet_buffer;
6295     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
6296     uint8_t status = hci_send_cmd_packet(packet, size);
6297 
6298     // release packet buffer on error or for synchronous transport implementations
6299     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
6300         hci_release_packet_buffer();
6301         hci_emit_transport_packet_sent();
6302     }
6303 
6304     return status;
6305 }
6306 
6307 /**
6308  * pre: numcmds >= 0 - it's allowed to send a command to the controller
6309  */
6310 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
6311     va_list argptr;
6312     va_start(argptr, cmd);
6313     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
6314     va_end(argptr);
6315     return status;
6316 }
6317 
6318 // Create various non-HCI events.
6319 // TODO: generalize, use table similar to hci_create_command
6320 
6321 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
6322     // dump packet
6323     if (dump) {
6324         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
6325     }
6326 
6327     // dispatch to all event handlers
6328     btstack_linked_list_iterator_t it;
6329     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
6330     while (btstack_linked_list_iterator_has_next(&it)){
6331         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
6332         entry->callback(HCI_EVENT_PACKET, 0, event, size);
6333     }
6334 }
6335 
6336 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
6337     if (!hci_stack->acl_packet_handler) return;
6338     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
6339 }
6340 
6341 #ifdef ENABLE_CLASSIC
6342 static void hci_notify_if_sco_can_send_now(void){
6343     // notify SCO sender if waiting
6344     if (!hci_stack->sco_waiting_for_can_send_now) return;
6345     if (hci_can_send_sco_packet_now()){
6346         hci_stack->sco_waiting_for_can_send_now = 0;
6347         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
6348         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
6349         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
6350     }
6351 }
6352 
6353 // parsing end emitting has been merged to reduce code size
6354 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
6355     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
6356 
6357     uint8_t * eir_data;
6358     ad_context_t context;
6359     const uint8_t * name;
6360     uint8_t         name_len;
6361 
6362     if (size < 3) return;
6363 
6364     int event_type = hci_event_packet_get_type(packet);
6365     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
6366     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
6367 
6368     switch (event_type){
6369         case HCI_EVENT_INQUIRY_RESULT:
6370         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6371             if (size != (3 + (num_responses * 14))) return;
6372             break;
6373         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6374             if (size != 257) return;
6375             if (num_responses != 1) return;
6376             break;
6377         default:
6378             return;
6379     }
6380 
6381     // event[1] is set at the end
6382     int i;
6383     for (i=0; i<num_responses;i++){
6384         memset(event, 0, sizeof(event));
6385         event[0] = GAP_EVENT_INQUIRY_RESULT;
6386         uint8_t event_size = 27;    // if name is not set by EIR
6387 
6388         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
6389         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
6390         (void)memcpy(&event[9],
6391                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
6392                      3); // class of device
6393         (void)memcpy(&event[12],
6394                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
6395                      2); // clock offset
6396 
6397         switch (event_type){
6398             case HCI_EVENT_INQUIRY_RESULT:
6399                 // 14,15,16,17 = 0, size 18
6400                 break;
6401             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
6402                 event[14] = 1;
6403                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
6404                 // 16,17 = 0, size 18
6405                 break;
6406             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
6407                 event[14] = 1;
6408                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
6409                 // EIR packets only contain a single inquiry response
6410                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
6411                 name = NULL;
6412                 // Iterate over EIR data
6413                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
6414                     uint8_t data_type    = ad_iterator_get_data_type(&context);
6415                     uint8_t data_size    = ad_iterator_get_data_len(&context);
6416                     const uint8_t * data = ad_iterator_get_data(&context);
6417                     // Prefer Complete Local Name over Shortened Local Name
6418                     switch (data_type){
6419                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
6420                             if (name) continue;
6421                             /* fall through */
6422                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
6423                             name = data;
6424                             name_len = data_size;
6425                             break;
6426                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
6427                             if (data_size != 8) break;
6428                             event[16] = 1;
6429                             memcpy(&event[17], data, 8);
6430                             break;
6431                         default:
6432                             break;
6433                     }
6434                 }
6435                 if (name){
6436                     event[25] = 1;
6437                     // truncate name if needed
6438                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
6439                     event[26] = len;
6440                     (void)memcpy(&event[27], name, len);
6441                     event_size += len;
6442                 }
6443                 break;
6444             default:
6445                 return;
6446         }
6447         event[1] = event_size - 2;
6448         hci_emit_event(event, event_size, 1);
6449     }
6450 }
6451 #endif
6452 
6453 void hci_emit_state(void){
6454     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
6455     uint8_t event[3];
6456     event[0] = BTSTACK_EVENT_STATE;
6457     event[1] = sizeof(event) - 2u;
6458     event[2] = hci_stack->state;
6459     hci_emit_event(event, sizeof(event), 1);
6460 }
6461 
6462 #ifdef ENABLE_CLASSIC
6463 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
6464     uint8_t event[13];
6465     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
6466     event[1] = sizeof(event) - 2;
6467     event[2] = status;
6468     little_endian_store_16(event, 3, con_handle);
6469     reverse_bd_addr(address, &event[5]);
6470     event[11] = 1; // ACL connection
6471     event[12] = 0; // encryption disabled
6472     hci_emit_event(event, sizeof(event), 1);
6473 }
6474 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
6475     if (disable_l2cap_timeouts) return;
6476     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
6477     uint8_t event[4];
6478     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
6479     event[1] = sizeof(event) - 2;
6480     little_endian_store_16(event, 2, conn->con_handle);
6481     hci_emit_event(event, sizeof(event), 1);
6482 }
6483 #endif
6484 
6485 #ifdef ENABLE_BLE
6486 #ifdef ENABLE_LE_CENTRAL
6487 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){
6488     uint8_t event[21];
6489     event[0] = HCI_EVENT_LE_META;
6490     event[1] = sizeof(event) - 2u;
6491     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
6492     event[3] = status;
6493     little_endian_store_16(event, 4, con_handle);
6494     event[6] = 0; // TODO: role
6495     event[7] = address_type;
6496     reverse_bd_addr(address, &event[8]);
6497     little_endian_store_16(event, 14, 0); // interval
6498     little_endian_store_16(event, 16, 0); // latency
6499     little_endian_store_16(event, 18, 0); // supervision timeout
6500     event[20] = 0; // master clock accuracy
6501     hci_emit_event(event, sizeof(event), 1);
6502 }
6503 #endif
6504 #endif
6505 
6506 static void hci_emit_transport_packet_sent(void){
6507     // notify upper stack that it might be possible to send again
6508     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
6509     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
6510 }
6511 
6512 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
6513     uint8_t event[6];
6514     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
6515     event[1] = sizeof(event) - 2u;
6516     event[2] = 0; // status = OK
6517     little_endian_store_16(event, 3, con_handle);
6518     event[5] = reason;
6519     hci_emit_event(event, sizeof(event), 1);
6520 }
6521 
6522 static void hci_emit_nr_connections_changed(void){
6523     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
6524     uint8_t event[3];
6525     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
6526     event[1] = sizeof(event) - 2u;
6527     event[2] = nr_hci_connections();
6528     hci_emit_event(event, sizeof(event), 1);
6529 }
6530 
6531 static void hci_emit_hci_open_failed(void){
6532     log_info("BTSTACK_EVENT_POWERON_FAILED");
6533     uint8_t event[2];
6534     event[0] = BTSTACK_EVENT_POWERON_FAILED;
6535     event[1] = sizeof(event) - 2u;
6536     hci_emit_event(event, sizeof(event), 1);
6537 }
6538 
6539 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
6540     log_info("hci_emit_dedicated_bonding_result %u ", status);
6541     uint8_t event[9];
6542     int pos = 0;
6543     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
6544     event[pos++] = sizeof(event) - 2u;
6545     event[pos++] = status;
6546     reverse_bd_addr(address, &event[pos]);
6547     hci_emit_event(event, sizeof(event), 1);
6548 }
6549 
6550 
6551 #ifdef ENABLE_CLASSIC
6552 
6553 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
6554     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
6555     uint8_t event[5];
6556     int pos = 0;
6557     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
6558     event[pos++] = sizeof(event) - 2;
6559     little_endian_store_16(event, 2, con_handle);
6560     pos += 2;
6561     event[pos++] = level;
6562     hci_emit_event(event, sizeof(event), 1);
6563 }
6564 
6565 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
6566     if (!connection) return LEVEL_0;
6567     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
6568     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
6569     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
6570     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
6571     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
6572     // LEVEL 4 always requires 128 bit encrytion key size
6573     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
6574         security_level = LEVEL_3;
6575     }
6576     return security_level;
6577 }
6578 
6579 static void hci_emit_discoverable_enabled(uint8_t enabled){
6580     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
6581     uint8_t event[3];
6582     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
6583     event[1] = sizeof(event) - 2;
6584     event[2] = enabled;
6585     hci_emit_event(event, sizeof(event), 1);
6586 }
6587 
6588 // query if remote side supports eSCO
6589 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
6590     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6591     if (!connection) return false;
6592     return (connection->remote_supported_features[0] & 1) != 0;
6593 }
6594 
6595 static bool hci_ssp_supported(hci_connection_t * connection){
6596     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
6597     return (connection->bonding_flags & mask) == mask;
6598 }
6599 
6600 // query if remote side supports SSP
6601 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
6602     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6603     if (!connection) return false;
6604     return hci_ssp_supported(connection) ? 1 : 0;
6605 }
6606 
6607 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
6608     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
6609 }
6610 
6611 /**
6612  * Check if remote supported features query has completed
6613  */
6614 bool hci_remote_features_available(hci_con_handle_t handle){
6615     hci_connection_t * connection = hci_connection_for_handle(handle);
6616     if (!connection) return false;
6617     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
6618 }
6619 
6620 /**
6621  * Trigger remote supported features query
6622  */
6623 
6624 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
6625     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
6626         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6627     }
6628 }
6629 
6630 void hci_remote_features_query(hci_con_handle_t con_handle){
6631     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6632     if (!connection) return;
6633     hci_trigger_remote_features_for_connection(connection);
6634     hci_run();
6635 }
6636 
6637 // GAP API
6638 /**
6639  * @bbrief enable/disable bonding. default is enabled
6640  * @praram enabled
6641  */
6642 void gap_set_bondable_mode(int enable){
6643     hci_stack->bondable = enable ? 1 : 0;
6644 }
6645 /**
6646  * @brief Get bondable mode.
6647  * @return 1 if bondable
6648  */
6649 int gap_get_bondable_mode(void){
6650     return hci_stack->bondable;
6651 }
6652 
6653 /**
6654  * @brief map link keys to security levels
6655  */
6656 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
6657     switch (link_key_type){
6658         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6659             return LEVEL_4;
6660         case COMBINATION_KEY:
6661         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
6662             return LEVEL_3;
6663         default:
6664             return LEVEL_2;
6665     }
6666 }
6667 
6668 /**
6669  * @brief map link keys to secure connection yes/no
6670  */
6671 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
6672     switch (link_key_type){
6673         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6674         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6675             return true;
6676         default:
6677             return false;
6678     }
6679 }
6680 
6681 /**
6682  * @brief map link keys to authenticated
6683  */
6684 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
6685     switch (link_key_type){
6686         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
6687         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
6688             return true;
6689         default:
6690             return false;
6691     }
6692 }
6693 
6694 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
6695     log_info("gap_mitm_protection_required_for_security_level %u", level);
6696     return level > LEVEL_2;
6697 }
6698 
6699 /**
6700  * @brief get current security level
6701  */
6702 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
6703     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6704     if (!connection) return LEVEL_0;
6705     return gap_security_level_for_connection(connection);
6706 }
6707 
6708 /**
6709  * @brief request connection to device to
6710  * @result GAP_AUTHENTICATION_RESULT
6711  */
6712 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
6713     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6714     if (!connection){
6715         hci_emit_security_level(con_handle, LEVEL_0);
6716         return;
6717     }
6718 
6719     btstack_assert(hci_is_le_connection(connection) == false);
6720 
6721     // 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)
6722     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
6723     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
6724         requested_level = LEVEL_4;
6725     }
6726 
6727     gap_security_level_t current_level = gap_security_level(con_handle);
6728     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
6729         requested_level, connection->requested_security_level, current_level);
6730 
6731     // authentication active if authentication request was sent or planned level > 0
6732     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
6733     if (authentication_active){
6734         // authentication already active
6735         if (connection->requested_security_level < requested_level){
6736             // increase requested level as new level is higher
6737             // TODO: handle re-authentication when done
6738             connection->requested_security_level = requested_level;
6739         }
6740     } else {
6741         // no request active, notify if security sufficient
6742         if (requested_level <= current_level){
6743             hci_emit_security_level(con_handle, current_level);
6744             return;
6745         }
6746 
6747         // store request
6748         connection->requested_security_level = requested_level;
6749 
6750         // request remote features if not already active
6751         hci_remote_features_query(con_handle);
6752 
6753         // start to authenticate connection
6754         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
6755         hci_run();
6756     }
6757 }
6758 
6759 /**
6760  * @brief start dedicated bonding with device. disconnect after bonding
6761  * @param device
6762  * @param request MITM protection
6763  * @result GAP_DEDICATED_BONDING_COMPLETE
6764  */
6765 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
6766 
6767     // create connection state machine
6768     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
6769 
6770     if (!connection){
6771         return BTSTACK_MEMORY_ALLOC_FAILED;
6772     }
6773 
6774     // delete linkn key
6775     gap_drop_link_key_for_bd_addr(device);
6776 
6777     // configure LEVEL_2/3, dedicated bonding
6778     connection->state = SEND_CREATE_CONNECTION;
6779     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
6780     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
6781     connection->bonding_flags = BONDING_DEDICATED;
6782 
6783     // wait for GAP Security Result and send GAP Dedicated Bonding complete
6784 
6785     // handle: connnection failure (connection complete != ok)
6786     // handle: authentication failure
6787     // handle: disconnect on done
6788 
6789     hci_run();
6790 
6791     return 0;
6792 }
6793 
6794 void gap_set_local_name(const char * local_name){
6795     hci_stack->local_name = local_name;
6796     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
6797     // also update EIR if not set by user
6798     if (hci_stack->eir_data == NULL){
6799         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
6800     }
6801     hci_run();
6802 }
6803 #endif
6804 
6805 
6806 #ifdef ENABLE_BLE
6807 
6808 #ifdef ENABLE_LE_CENTRAL
6809 void gap_start_scan(void){
6810     hci_stack->le_scanning_enabled = true;
6811     hci_run();
6812 }
6813 
6814 void gap_stop_scan(void){
6815     hci_stack->le_scanning_enabled = false;
6816     hci_run();
6817 }
6818 
6819 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
6820     hci_stack->le_scan_type          = scan_type;
6821     hci_stack->le_scan_filter_policy = scanning_filter_policy;
6822     hci_stack->le_scan_interval      = scan_interval;
6823     hci_stack->le_scan_window        = scan_window;
6824     hci_stack->le_scanning_param_update = true;
6825     hci_run();
6826 }
6827 
6828 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
6829     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
6830 }
6831 
6832 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
6833     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
6834     if (!conn){
6835         // disallow if le connection is already outgoing
6836         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6837             log_error("le connection already active");
6838             return ERROR_CODE_COMMAND_DISALLOWED;
6839         }
6840 
6841         log_info("gap_connect: no connection exists yet, creating context");
6842         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
6843         if (!conn){
6844             // notify client that alloc failed
6845             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6846             log_info("gap_connect: failed to alloc hci_connection_t");
6847             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
6848         }
6849 
6850         // set le connecting state
6851         if (hci_is_le_connection_type(addr_type)){
6852             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
6853         }
6854 
6855         conn->state = SEND_CREATE_CONNECTION;
6856         log_info("gap_connect: send create connection next");
6857         hci_run();
6858         return ERROR_CODE_SUCCESS;
6859     }
6860 
6861     if (!hci_is_le_connection(conn) ||
6862         (conn->state == SEND_CREATE_CONNECTION) ||
6863         (conn->state == SENT_CREATE_CONNECTION)) {
6864         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
6865         log_error("gap_connect: classic connection or connect is already being created");
6866         return GATT_CLIENT_IN_WRONG_STATE;
6867     }
6868 
6869     // check if connection was just disconnected
6870     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
6871         log_info("gap_connect: send create connection (again)");
6872         conn->state = SEND_CREATE_CONNECTION;
6873         hci_run();
6874         return ERROR_CODE_SUCCESS;
6875     }
6876 
6877     log_info("gap_connect: context exists with state %u", conn->state);
6878     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
6879     hci_run();
6880     return ERROR_CODE_SUCCESS;
6881 }
6882 
6883 // @assumption: only a single outgoing LE Connection exists
6884 static hci_connection_t * gap_get_outgoing_connection(void){
6885     btstack_linked_item_t *it;
6886     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6887         hci_connection_t * conn = (hci_connection_t *) it;
6888         if (!hci_is_le_connection(conn)) continue;
6889         switch (conn->state){
6890             case SEND_CREATE_CONNECTION:
6891             case SENT_CREATE_CONNECTION:
6892             case SENT_CANCEL_CONNECTION:
6893                 return conn;
6894             default:
6895                 break;
6896         };
6897     }
6898     return NULL;
6899 }
6900 
6901 uint8_t gap_connect_cancel(void){
6902     hci_connection_t * conn = gap_get_outgoing_connection();
6903     if (!conn) return 0;
6904     switch (conn->state){
6905         case SEND_CREATE_CONNECTION:
6906             // skip sending create connection and emit event instead
6907             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6908             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
6909             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
6910             btstack_memory_hci_connection_free( conn );
6911             break;
6912         case SENT_CREATE_CONNECTION:
6913             // request to send cancel connection
6914             conn->state = SEND_CANCEL_CONNECTION;
6915             hci_run();
6916             break;
6917         default:
6918             break;
6919     }
6920     return 0;
6921 }
6922 
6923 /**
6924  * @brief Set connection parameters for outgoing connections
6925  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
6926  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
6927  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
6928  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
6929  * @param conn_latency, default: 4
6930  * @param supervision_timeout (unit: 10ms), default: 720 ms
6931  * @param min_ce_length (unit: 0.625ms), default: 10 ms
6932  * @param max_ce_length (unit: 0.625ms), default: 30 ms
6933  */
6934 
6935 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
6936     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
6937     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
6938     hci_stack->le_connection_scan_interval = conn_scan_interval;
6939     hci_stack->le_connection_scan_window = conn_scan_window;
6940     hci_stack->le_connection_interval_min = conn_interval_min;
6941     hci_stack->le_connection_interval_max = conn_interval_max;
6942     hci_stack->le_connection_latency = conn_latency;
6943     hci_stack->le_supervision_timeout = supervision_timeout;
6944     hci_stack->le_minimum_ce_length = min_ce_length;
6945     hci_stack->le_maximum_ce_length = max_ce_length;
6946 }
6947 #endif
6948 
6949 /**
6950  * @brief Updates the connection parameters for a given LE connection
6951  * @param handle
6952  * @param conn_interval_min (unit: 1.25ms)
6953  * @param conn_interval_max (unit: 1.25ms)
6954  * @param conn_latency
6955  * @param supervision_timeout (unit: 10ms)
6956  * @return 0 if ok
6957  */
6958 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6959     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6960     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6961     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6962     connection->le_conn_interval_min = conn_interval_min;
6963     connection->le_conn_interval_max = conn_interval_max;
6964     connection->le_conn_latency = conn_latency;
6965     connection->le_supervision_timeout = supervision_timeout;
6966     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
6967     hci_run();
6968     return 0;
6969 }
6970 
6971 /**
6972  * @brief Request an update of the connection parameter for a given LE connection
6973  * @param handle
6974  * @param conn_interval_min (unit: 1.25ms)
6975  * @param conn_interval_max (unit: 1.25ms)
6976  * @param conn_latency
6977  * @param supervision_timeout (unit: 10ms)
6978  * @return 0 if ok
6979  */
6980 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6981     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6982     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6983     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6984     connection->le_conn_interval_min = conn_interval_min;
6985     connection->le_conn_interval_max = conn_interval_max;
6986     connection->le_conn_latency = conn_latency;
6987     connection->le_supervision_timeout = supervision_timeout;
6988     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
6989     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
6990     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
6991     return 0;
6992 }
6993 
6994 #ifdef ENABLE_LE_PERIPHERAL
6995 
6996 /**
6997  * @brief Set Advertisement Data
6998  * @param advertising_data_length
6999  * @param advertising_data (max 31 octets)
7000  * @note data is not copied, pointer has to stay valid
7001  */
7002 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
7003     hci_stack->le_advertisements_data_len = advertising_data_length;
7004     hci_stack->le_advertisements_data = advertising_data;
7005     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7006     hci_run();
7007 }
7008 
7009 /**
7010  * @brief Set Scan Response Data
7011  * @param advertising_data_length
7012  * @param advertising_data (max 31 octets)
7013  * @note data is not copied, pointer has to stay valid
7014  */
7015 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
7016     hci_stack->le_scan_response_data_len = scan_response_data_length;
7017     hci_stack->le_scan_response_data = scan_response_data;
7018     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7019     hci_run();
7020 }
7021 
7022 /**
7023  * @brief Set Advertisement Parameters
7024  * @param adv_int_min
7025  * @param adv_int_max
7026  * @param adv_type
7027  * @param direct_address_type
7028  * @param direct_address
7029  * @param channel_map
7030  * @param filter_policy
7031  *
7032  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
7033  */
7034  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
7035     uint8_t direct_address_typ, bd_addr_t direct_address,
7036     uint8_t channel_map, uint8_t filter_policy) {
7037 
7038     hci_stack->le_advertisements_interval_min = adv_int_min;
7039     hci_stack->le_advertisements_interval_max = adv_int_max;
7040     hci_stack->le_advertisements_type = adv_type;
7041     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
7042     hci_stack->le_advertisements_channel_map = channel_map;
7043     hci_stack->le_advertisements_filter_policy = filter_policy;
7044     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
7045                  6);
7046 
7047     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7048     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
7049     hci_run();
7050  }
7051 
7052 /**
7053  * @brief Enable/Disable Advertisements
7054  * @param enabled
7055  */
7056 void gap_advertisements_enable(int enabled){
7057     if (enabled == 0){
7058         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7059     } else {
7060         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
7061     }
7062     hci_update_advertisements_enabled_for_current_roles();
7063     hci_run();
7064 }
7065 
7066 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7067 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
7068     btstack_linked_list_iterator_t it;
7069     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
7070     while (btstack_linked_list_iterator_has_next(&it)){
7071         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
7072         if ( item->advertising_handle == advertising_handle ) {
7073             return item;
7074         }
7075     }
7076     return NULL;
7077 }
7078 
7079 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
7080     // find free advertisement handle
7081     uint8_t advertisement_handle;
7082     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
7083         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
7084     }
7085     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7086     // clear
7087     memset(storage, 0, sizeof(le_advertising_set_t));
7088     // copy params
7089     storage->advertising_handle = advertisement_handle;
7090     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7091     // add to list
7092     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
7093     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7094     *out_advertising_handle = advertisement_handle;
7095     // set tasks and start
7096     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7097     hci_run();
7098     return ERROR_CODE_SUCCESS;
7099 }
7100 
7101 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
7102     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7103     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7104     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7105     // set tasks and start
7106     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7107     hci_run();
7108     return ERROR_CODE_SUCCESS;
7109 }
7110 
7111 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
7112     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7113     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7114     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
7115     return ERROR_CODE_SUCCESS;
7116 }
7117 
7118 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
7119     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7120     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7121     memcpy(advertising_set->random_address, random_address, 6);
7122     // set tasks and start
7123     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7124     hci_run();
7125     return ERROR_CODE_SUCCESS;
7126 }
7127 
7128 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
7129     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7130     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7131     advertising_set->adv_data = advertising_data;
7132     advertising_set->adv_data_len = advertising_data_length;
7133     // set tasks and start
7134     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7135     hci_run();
7136     return ERROR_CODE_SUCCESS;
7137 }
7138 
7139 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){
7140     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7141     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7142     advertising_set->scan_data = scan_response_data;
7143     advertising_set->scan_data_len = scan_response_data_length;
7144     // set tasks and start
7145     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7146     hci_run();
7147     return ERROR_CODE_SUCCESS;
7148 }
7149 
7150 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
7151     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7152     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7153     advertising_set->enable_timeout = timeout;
7154     advertising_set->enable_max_scan_events = num_extended_advertising_events;
7155     // set tasks and start
7156     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
7157     hci_run();
7158     return ERROR_CODE_SUCCESS;
7159 }
7160 
7161 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
7162     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7163     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7164     // set tasks and start
7165     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7166     hci_run();
7167     return ERROR_CODE_SUCCESS;
7168 }
7169 
7170 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
7171     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7172     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7173     // set tasks and start
7174     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
7175     hci_run();
7176     return ERROR_CODE_SUCCESS;
7177 }
7178 
7179 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7180 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
7181     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7182     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7183     // periodic advertising requires neither connectable, scannable, legacy or anonymous
7184     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7185     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
7186     // set tasks and start
7187     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
7188     hci_run();
7189     return ERROR_CODE_SUCCESS;
7190 }
7191 
7192 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
7193     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7194     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7195     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
7196     return ERROR_CODE_SUCCESS;
7197 }
7198 
7199 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
7200     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7201     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7202     advertising_set->periodic_data = periodic_data;
7203     advertising_set->periodic_data_len = periodic_data_length;
7204     // set tasks and start
7205     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
7206     hci_run();
7207     return ERROR_CODE_SUCCESS;
7208 }
7209 
7210 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
7211     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7212     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7213     // set tasks and start
7214     advertising_set->periodic_include_adi = include_adi;
7215     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7216     hci_run();
7217     return ERROR_CODE_SUCCESS;
7218 }
7219 
7220 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
7221     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7222     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7223     // set tasks and start
7224     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
7225     hci_run();
7226     return ERROR_CODE_SUCCESS;
7227 }
7228 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
7229 
7230 #endif
7231 
7232 #endif
7233 
7234 void hci_le_set_own_address_type(uint8_t own_address_type){
7235     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
7236     if (own_address_type == hci_stack->le_own_addr_type) return;
7237     hci_stack->le_own_addr_type = own_address_type;
7238 
7239 #ifdef ENABLE_LE_PERIPHERAL
7240     // update advertisement parameters, too
7241     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7242     hci_run();
7243 #endif
7244 #ifdef ENABLE_LE_CENTRAL
7245     // note: we don't update scan parameters or modify ongoing connection attempts
7246 #endif
7247 }
7248 
7249 void hci_le_random_address_set(const bd_addr_t random_address){
7250     memcpy(hci_stack->le_random_address, random_address, 6);
7251     hci_stack->le_random_address_set = true;
7252     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7253     hci_run();
7254 }
7255 
7256 #endif
7257 
7258 uint8_t gap_disconnect(hci_con_handle_t handle){
7259     hci_connection_t * conn = hci_connection_for_handle(handle);
7260     if (!conn){
7261         hci_emit_disconnection_complete(handle, 0);
7262         return 0;
7263     }
7264     // ignore if already disconnected
7265     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7266         return 0;
7267     }
7268     conn->state = SEND_DISCONNECT;
7269     hci_run();
7270     return 0;
7271 }
7272 
7273 int gap_read_rssi(hci_con_handle_t con_handle){
7274     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7275     if (hci_connection == NULL) return 0;
7276     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
7277     hci_run();
7278     return 1;
7279 }
7280 
7281 /**
7282  * @brief Get connection type
7283  * @param con_handle
7284  * @result connection_type
7285  */
7286 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
7287     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7288     if (!conn) return GAP_CONNECTION_INVALID;
7289     switch (conn->address_type){
7290         case BD_ADDR_TYPE_LE_PUBLIC:
7291         case BD_ADDR_TYPE_LE_RANDOM:
7292             return GAP_CONNECTION_LE;
7293         case BD_ADDR_TYPE_SCO:
7294             return GAP_CONNECTION_SCO;
7295         case BD_ADDR_TYPE_ACL:
7296             return GAP_CONNECTION_ACL;
7297         default:
7298             return GAP_CONNECTION_INVALID;
7299     }
7300 }
7301 
7302 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
7303     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7304     if (!conn) return HCI_ROLE_INVALID;
7305     return (hci_role_t) conn->role;
7306 }
7307 
7308 
7309 #ifdef ENABLE_CLASSIC
7310 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
7311     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7312     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7313     conn->request_role = role;
7314     hci_run();
7315     return ERROR_CODE_SUCCESS;
7316 }
7317 #endif
7318 
7319 #ifdef ENABLE_BLE
7320 
7321 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){
7322     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7323     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7324 
7325     conn->le_phy_update_all_phys    = all_phys;
7326     conn->le_phy_update_tx_phys     = tx_phys;
7327     conn->le_phy_update_rx_phys     = rx_phys;
7328     conn->le_phy_update_phy_options = phy_options;
7329 
7330     hci_run();
7331 
7332     return 0;
7333 }
7334 
7335 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
7336     // check if already in list
7337     btstack_linked_list_iterator_t it;
7338     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7339     while (btstack_linked_list_iterator_has_next(&it)) {
7340         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
7341         if (entry->address_type != address_type) {
7342             continue;
7343         }
7344         if (memcmp(entry->address, address, 6) != 0) {
7345             continue;
7346         }
7347 		// disallow if already scheduled to add
7348 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
7349 			return ERROR_CODE_COMMAND_DISALLOWED;
7350 		}
7351 		// still on controller, but scheduled to remove -> re-add
7352 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
7353 		return ERROR_CODE_SUCCESS;
7354     }
7355     // alloc and add to list
7356     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
7357     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
7358     entry->address_type = address_type;
7359     (void)memcpy(entry->address, address, 6);
7360     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
7361     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
7362     return ERROR_CODE_SUCCESS;
7363 }
7364 
7365 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7366     btstack_linked_list_iterator_t it;
7367     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7368     while (btstack_linked_list_iterator_has_next(&it)){
7369         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7370         if (entry->address_type != address_type) {
7371             continue;
7372         }
7373         if (memcmp(entry->address, address, 6) != 0) {
7374             continue;
7375         }
7376         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7377             // remove from controller if already present
7378             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7379         }  else {
7380             // directly remove entry from whitelist
7381             btstack_linked_list_iterator_remove(&it);
7382             btstack_memory_whitelist_entry_free(entry);
7383         }
7384         return ERROR_CODE_SUCCESS;
7385     }
7386     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7387 }
7388 
7389 static void hci_whitelist_clear(void){
7390     btstack_linked_list_iterator_t it;
7391     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7392     while (btstack_linked_list_iterator_has_next(&it)){
7393         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
7394         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7395             // remove from controller if already present
7396             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7397             continue;
7398         }
7399         // directly remove entry from whitelist
7400         btstack_linked_list_iterator_remove(&it);
7401         btstack_memory_whitelist_entry_free(entry);
7402     }
7403 }
7404 
7405 // free all entries unconditionally
7406 static void hci_whitelist_free(void){
7407     btstack_linked_list_iterator_t lit;
7408     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
7409     while (btstack_linked_list_iterator_has_next(&lit)){
7410         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
7411         btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
7412         btstack_memory_whitelist_entry_free(entry);
7413     }
7414 }
7415 
7416 /**
7417  * @brief Clear Whitelist
7418  * @return 0 if ok
7419  */
7420 uint8_t gap_whitelist_clear(void){
7421     hci_whitelist_clear();
7422     hci_run();
7423     return ERROR_CODE_SUCCESS;
7424 }
7425 
7426 /**
7427  * @brief Add Device to Whitelist
7428  * @param address_typ
7429  * @param address
7430  * @return 0 if ok
7431  */
7432 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
7433     uint8_t status = hci_whitelist_add(address_type, address);
7434     if (status){
7435         return status;
7436     }
7437     hci_run();
7438     return ERROR_CODE_SUCCESS;
7439 }
7440 
7441 /**
7442  * @brief Remove Device from Whitelist
7443  * @param address_typ
7444  * @param address
7445  * @return 0 if ok
7446  */
7447 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7448     uint8_t status = hci_whitelist_remove(address_type, address);
7449     if (status){
7450         return status;
7451     }
7452     hci_run();
7453     return ERROR_CODE_SUCCESS;
7454 }
7455 
7456 #ifdef ENABLE_LE_CENTRAL
7457 /**
7458  * @brief Connect with Whitelist
7459  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
7460  * @return - if ok
7461  */
7462 uint8_t gap_connect_with_whitelist(void){
7463     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7464         return ERROR_CODE_COMMAND_DISALLOWED;
7465     }
7466     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
7467     hci_run();
7468     return ERROR_CODE_SUCCESS;
7469 }
7470 
7471 /**
7472  * @brief Auto Connection Establishment - Start Connecting to device
7473  * @param address_typ
7474  * @param address
7475  * @return 0 if ok
7476  */
7477 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
7478     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
7479         return ERROR_CODE_COMMAND_DISALLOWED;
7480     }
7481 
7482     uint8_t status = hci_whitelist_add(address_type, address);
7483     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
7484         return status;
7485     }
7486 
7487     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
7488 
7489     hci_run();
7490     return ERROR_CODE_SUCCESS;
7491 }
7492 
7493 /**
7494  * @brief Auto Connection Establishment - Stop Connecting to device
7495  * @param address_typ
7496  * @param address
7497  * @return 0 if ok
7498  */
7499 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
7500     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
7501         return ERROR_CODE_COMMAND_DISALLOWED;
7502     }
7503 
7504     hci_whitelist_remove(address_type, address);
7505     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
7506         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7507     }
7508     hci_run();
7509     return 0;
7510 }
7511 
7512 /**
7513  * @brief Auto Connection Establishment - Stop everything
7514  * @note  Convenience function to stop all active auto connection attempts
7515  */
7516 uint8_t gap_auto_connection_stop_all(void){
7517     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
7518         return ERROR_CODE_COMMAND_DISALLOWED;
7519     }
7520     hci_whitelist_clear();
7521     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7522     hci_run();
7523     return ERROR_CODE_SUCCESS;
7524 }
7525 
7526 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
7527     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7528     if (!conn) return 0;
7529     return conn->le_connection_interval;
7530 }
7531 #endif
7532 #endif
7533 
7534 #ifdef ENABLE_CLASSIC
7535 /**
7536  * @brief Set Extended Inquiry Response data
7537  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
7538  * @note has to be done before stack starts up
7539  */
7540 void gap_set_extended_inquiry_response(const uint8_t * data){
7541     hci_stack->eir_data = data;
7542     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7543     hci_run();
7544 }
7545 
7546 /**
7547  * @brief Start GAP Classic Inquiry
7548  * @param duration in 1.28s units
7549  * @return 0 if ok
7550  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
7551  */
7552 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
7553     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
7554     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7555     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
7556         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7557     }
7558     hci_stack->inquiry_state = duration_in_1280ms_units;
7559     hci_stack->inquiry_max_period_length = 0;
7560     hci_stack->inquiry_min_period_length = 0;
7561     hci_run();
7562     return 0;
7563 }
7564 
7565 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
7566     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
7567     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
7568     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7569     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7570     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
7571     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
7572 
7573     hci_stack->inquiry_state = duration;
7574     hci_stack->inquiry_max_period_length = max_period_length;
7575     hci_stack->inquiry_min_period_length = min_period_length;
7576     hci_run();
7577     return 0;
7578 }
7579 
7580 /**
7581  * @brief Stop GAP Classic Inquiry
7582  * @return 0 if ok
7583  */
7584 int gap_inquiry_stop(void){
7585     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
7586         // emit inquiry complete event, before it even started
7587         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
7588         hci_emit_event(event, sizeof(event), 1);
7589         return 0;
7590     }
7591     switch (hci_stack->inquiry_state){
7592         case GAP_INQUIRY_STATE_ACTIVE:
7593             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
7594             hci_run();
7595             return ERROR_CODE_SUCCESS;
7596         case GAP_INQUIRY_STATE_PERIODIC:
7597             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
7598             hci_run();
7599             return ERROR_CODE_SUCCESS;
7600         default:
7601             return ERROR_CODE_COMMAND_DISALLOWED;
7602     }
7603 }
7604 
7605 void gap_inquiry_set_lap(uint32_t lap){
7606     hci_stack->inquiry_lap = lap;
7607 }
7608 
7609 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
7610     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
7611     hci_stack->inquiry_scan_window   = inquiry_scan_window;
7612     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
7613     hci_run();
7614 }
7615 
7616 
7617 /**
7618  * @brief Remote Name Request
7619  * @param addr
7620  * @param page_scan_repetition_mode
7621  * @param clock_offset only used when bit 15 is set
7622  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
7623  */
7624 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
7625     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7626     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
7627     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
7628     hci_stack->remote_name_clock_offset = clock_offset;
7629     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
7630     hci_run();
7631     return 0;
7632 }
7633 
7634 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
7635     hci_stack->gap_pairing_state = state;
7636     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
7637     hci_run();
7638     return 0;
7639 }
7640 
7641 /**
7642  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
7643  * @param addr
7644  * @param pin_data
7645  * @param pin_len
7646  * @return 0 if ok
7647  */
7648 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
7649     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7650     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
7651     hci_stack->gap_pairing_pin_len = pin_len;
7652     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
7653 }
7654 
7655 /**
7656  * @brief Legacy Pairing Pin Code Response
7657  * @param addr
7658  * @param pin
7659  * @return 0 if ok
7660  */
7661 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
7662     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
7663 }
7664 
7665 /**
7666  * @brief Abort Legacy Pairing
7667  * @param addr
7668  * @param pin
7669  * @return 0 if ok
7670  */
7671 int gap_pin_code_negative(bd_addr_t addr){
7672     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7673     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
7674 }
7675 
7676 /**
7677  * @brief SSP Passkey Response
7678  * @param addr
7679  * @param passkey
7680  * @return 0 if ok
7681  */
7682 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
7683     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7684     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
7685     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
7686 }
7687 
7688 /**
7689  * @brief Abort SSP Passkey Entry/Pairing
7690  * @param addr
7691  * @param pin
7692  * @return 0 if ok
7693  */
7694 int gap_ssp_passkey_negative(const bd_addr_t addr){
7695     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7696     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
7697 }
7698 
7699 /**
7700  * @brief Accept SSP Numeric Comparison
7701  * @param addr
7702  * @param passkey
7703  * @return 0 if ok
7704  */
7705 int gap_ssp_confirmation_response(const bd_addr_t addr){
7706     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7707     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
7708 }
7709 
7710 /**
7711  * @brief Abort SSP Numeric Comparison/Pairing
7712  * @param addr
7713  * @param pin
7714  * @return 0 if ok
7715  */
7716 int gap_ssp_confirmation_negative(const bd_addr_t addr){
7717     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
7718     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
7719 }
7720 
7721 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
7722 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
7723     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7724     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7725     connectionSetAuthenticationFlags(conn, flag);
7726     hci_run();
7727     return ERROR_CODE_SUCCESS;
7728 }
7729 #endif
7730 
7731 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
7732 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
7733     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7734 }
7735 
7736 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
7737     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
7738 }
7739 #endif
7740 
7741 #ifdef ENABLE_CLASSIC_PAIRING_OOB
7742 /**
7743  * @brief Report Remote OOB Data
7744  * @param bd_addr
7745  * @param c_192 Simple Pairing Hash C derived from P-192 public key
7746  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
7747  * @param c_256 Simple Pairing Hash C derived from P-256 public key
7748  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
7749  */
7750 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){
7751     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7752     if (connection == NULL) {
7753         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7754     }
7755     connection->classic_oob_c_192 = c_192;
7756     connection->classic_oob_r_192 = r_192;
7757 
7758     // ignore P-256 if not supported by us
7759     if (hci_stack->secure_connections_active){
7760         connection->classic_oob_c_256 = c_256;
7761         connection->classic_oob_r_256 = r_256;
7762     }
7763 
7764     return ERROR_CODE_SUCCESS;
7765 }
7766 /**
7767  * @brief Generate new OOB data
7768  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
7769  */
7770 void gap_ssp_generate_oob_data(void){
7771     hci_stack->classic_read_local_oob_data = true;
7772     hci_run();
7773 }
7774 
7775 #endif
7776 
7777 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
7778 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
7779     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7780     if (connection == NULL) {
7781         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7782     }
7783 
7784     memcpy(connection->link_key, link_key, sizeof(link_key_t));
7785     connection->link_key_type = type;
7786 
7787     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
7788 }
7789 
7790 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
7791 /**
7792  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
7793  * @param inquiry_mode see bluetooth_defines.h
7794  */
7795 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
7796     hci_stack->inquiry_mode = inquiry_mode;
7797 }
7798 
7799 /**
7800  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
7801  */
7802 void hci_set_sco_voice_setting(uint16_t voice_setting){
7803     hci_stack->sco_voice_setting = voice_setting;
7804 }
7805 
7806 /**
7807  * @brief Get SCO Voice Setting
7808  * @return current voice setting
7809  */
7810 uint16_t hci_get_sco_voice_setting(void){
7811     return hci_stack->sco_voice_setting;
7812 }
7813 
7814 static int hci_have_usb_transport(void){
7815     if (!hci_stack->hci_transport) return 0;
7816     const char * transport_name = hci_stack->hci_transport->name;
7817     if (!transport_name) return 0;
7818     return (transport_name[0] == 'H') && (transport_name[1] == '2');
7819 }
7820 
7821 /** @brief Get SCO packet length for current SCO Voice setting
7822  *  @note  Using SCO packets of the exact length is required for USB transfer
7823  *  @return Length of SCO packets in bytes (not audio frames)
7824  */
7825 uint16_t hci_get_sco_packet_length(void){
7826     uint16_t sco_packet_length = 0;
7827 
7828 #ifdef ENABLE_SCO_OVER_HCI
7829     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
7830     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
7831 
7832     if (hci_have_usb_transport()){
7833         // see Core Spec for H2 USB Transfer.
7834         // 3 byte SCO header + 24 bytes per connection
7835         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
7836         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
7837     } else {
7838         // 3 byte SCO header + SCO packet size over the air (60 bytes)
7839         sco_packet_length = 3 + 60 * multiplier;
7840         // assert that it still fits inside an SCO buffer
7841         if (sco_packet_length > hci_stack->sco_data_packet_length){
7842             sco_packet_length = 3 + 60;
7843         }
7844     }
7845 #endif
7846 
7847 #ifdef HAVE_SCO_TRANSPORT
7848     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
7849     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
7850     sco_packet_length = 3 + 60 * multiplier;
7851 #endif
7852     return sco_packet_length;
7853 }
7854 
7855 /**
7856 * @brief Sets the master/slave policy
7857 * @param policy (0: attempt to become master, 1: let connecting device decide)
7858 */
7859 void hci_set_master_slave_policy(uint8_t policy){
7860     hci_stack->master_slave_policy = policy;
7861 }
7862 
7863 #endif
7864 
7865 HCI_STATE hci_get_state(void){
7866     return hci_stack->state;
7867 }
7868 
7869 #ifdef ENABLE_CLASSIC
7870 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
7871     hci_stack->gap_classic_accept_callback = accept_callback;
7872 }
7873 #endif
7874 
7875 /**
7876  * @brief Set callback for Bluetooth Hardware Error
7877  */
7878 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
7879     hci_stack->hardware_error_callback = fn;
7880 }
7881 
7882 void hci_disconnect_all(void){
7883     btstack_linked_list_iterator_t it;
7884     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
7885     while (btstack_linked_list_iterator_has_next(&it)){
7886         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
7887         if (con->state == SENT_DISCONNECT) continue;
7888         con->state = SEND_DISCONNECT;
7889     }
7890     hci_run();
7891 }
7892 
7893 uint16_t hci_get_manufacturer(void){
7894     return hci_stack->manufacturer;
7895 }
7896 
7897 #ifdef ENABLE_BLE
7898 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
7899     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
7900     if (!hci_con) return NULL;
7901     return &hci_con->sm_connection;
7902 }
7903 
7904 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
7905 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
7906 #endif
7907 
7908 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
7909     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7910     if (hci_connection == NULL) return 0;
7911     if (hci_is_le_connection(hci_connection)){
7912 #ifdef ENABLE_BLE
7913         sm_connection_t * sm_conn = &hci_connection->sm_connection;
7914         if (sm_conn->sm_connection_encrypted) {
7915             return sm_conn->sm_actual_encryption_key_size;
7916         }
7917 #endif
7918     } else {
7919 #ifdef ENABLE_CLASSIC
7920         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
7921             return hci_connection->encryption_key_size;
7922         }
7923 #endif
7924     }
7925     return 0;
7926 }
7927 
7928 bool gap_authenticated(hci_con_handle_t con_handle){
7929     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7930     if (hci_connection == NULL) return false;
7931 
7932     switch (hci_connection->address_type){
7933 #ifdef ENABLE_BLE
7934         case BD_ADDR_TYPE_LE_PUBLIC:
7935         case BD_ADDR_TYPE_LE_RANDOM:
7936             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
7937             return hci_connection->sm_connection.sm_connection_authenticated != 0;
7938 #endif
7939 #ifdef ENABLE_CLASSIC
7940         case BD_ADDR_TYPE_SCO:
7941         case BD_ADDR_TYPE_ACL:
7942             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
7943 #endif
7944         default:
7945             return false;
7946     }
7947 }
7948 
7949 bool gap_secure_connection(hci_con_handle_t con_handle){
7950     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7951     if (hci_connection == NULL) return 0;
7952 
7953     switch (hci_connection->address_type){
7954 #ifdef ENABLE_BLE
7955         case BD_ADDR_TYPE_LE_PUBLIC:
7956         case BD_ADDR_TYPE_LE_RANDOM:
7957             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
7958             return hci_connection->sm_connection.sm_connection_sc != 0;
7959 #endif
7960 #ifdef ENABLE_CLASSIC
7961         case BD_ADDR_TYPE_SCO:
7962         case BD_ADDR_TYPE_ACL:
7963             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
7964 #endif
7965         default:
7966             return false;
7967     }
7968 }
7969 
7970 bool gap_bonded(hci_con_handle_t con_handle){
7971 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7972 	if (hci_connection == NULL) return 0;
7973 
7974 #ifdef ENABLE_CLASSIC
7975 	link_key_t link_key;
7976 	link_key_type_t link_key_type;
7977 #endif
7978 	switch (hci_connection->address_type){
7979 #ifdef ENABLE_BLE
7980 		case BD_ADDR_TYPE_LE_PUBLIC:
7981 		case BD_ADDR_TYPE_LE_RANDOM:
7982 			return hci_connection->sm_connection.sm_le_db_index >= 0;
7983 #endif
7984 #ifdef ENABLE_CLASSIC
7985 		case BD_ADDR_TYPE_SCO:
7986 		case BD_ADDR_TYPE_ACL:
7987 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
7988 #endif
7989 		default:
7990 			return false;
7991 	}
7992 }
7993 
7994 #ifdef ENABLE_BLE
7995 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
7996     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
7997     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
7998     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
7999     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
8000     return sm_conn->sm_connection_authorization_state;
8001 }
8002 #endif
8003 
8004 #ifdef ENABLE_CLASSIC
8005 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){
8006     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8007     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8008     conn->sniff_min_interval = sniff_min_interval;
8009     conn->sniff_max_interval = sniff_max_interval;
8010     conn->sniff_attempt = sniff_attempt;
8011     conn->sniff_timeout = sniff_timeout;
8012     hci_run();
8013     return 0;
8014 }
8015 
8016 /**
8017  * @brief Exit Sniff mode
8018  * @param con_handle
8019  @ @return 0 if ok
8020  */
8021 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
8022     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8023     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8024     conn->sniff_min_interval = 0xffff;
8025     hci_run();
8026     return 0;
8027 }
8028 
8029 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){
8030     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8031     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8032     conn->sniff_subrating_max_latency = max_latency;
8033     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
8034     conn->sniff_subrating_min_local_timeout = min_local_timeout;
8035     hci_run();
8036     return ERROR_CODE_SUCCESS;
8037 }
8038 
8039 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){
8040     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8041     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8042     conn->qos_service_type = service_type;
8043     conn->qos_token_rate = token_rate;
8044     conn->qos_peak_bandwidth = peak_bandwidth;
8045     conn->qos_latency = latency;
8046     conn->qos_delay_variation = delay_variation;
8047     hci_run();
8048     return ERROR_CODE_SUCCESS;
8049 }
8050 
8051 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
8052     hci_stack->new_page_scan_interval = page_scan_interval;
8053     hci_stack->new_page_scan_window = page_scan_window;
8054     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
8055     hci_run();
8056 }
8057 
8058 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
8059     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
8060     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
8061     hci_run();
8062 }
8063 
8064 void gap_set_page_timeout(uint16_t page_timeout){
8065     hci_stack->page_timeout = page_timeout;
8066     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
8067     hci_run();
8068 }
8069 
8070 #endif
8071 
8072 void hci_halting_defer(void){
8073     if (hci_stack->state != HCI_STATE_HALTING) return;
8074     switch (hci_stack->substate){
8075         case HCI_HALTING_READY_FOR_CLOSE:
8076             hci_stack->substate = HCI_HALTING_DEFER_CLOSE;
8077             break;
8078         default:
8079             break;
8080     }
8081 }
8082 
8083 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
8084 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
8085     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
8086     if (le_device_db_index >= le_device_db_max_count()) return;
8087     uint8_t offset = le_device_db_index >> 3;
8088     uint8_t mask = 1 << (le_device_db_index & 7);
8089     hci_stack->le_resolving_list_add_entries[offset] |= mask;
8090     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
8091     	// note: go back to remove entries, otherwise, a remove + add will skip the add
8092         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
8093     }
8094 }
8095 
8096 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
8097 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
8098 	if (le_device_db_index >= le_device_db_max_count()) return;
8099 	uint8_t offset = le_device_db_index >> 3;
8100 	uint8_t mask = 1 << (le_device_db_index & 7);
8101 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
8102 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
8103 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
8104 	}
8105 }
8106 
8107 uint8_t gap_load_resolving_list_from_le_device_db(void){
8108     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
8109 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
8110 	}
8111 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
8112 		// restart le resolving list update
8113 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
8114 	}
8115 	return ERROR_CODE_SUCCESS;
8116 }
8117 #endif
8118 
8119 #ifdef ENABLE_BLE
8120 #ifdef ENABLE_LE_CENTRAL
8121 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8122 
8123 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8124     // check if already in list
8125     btstack_linked_list_iterator_t it;
8126     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8127     while (btstack_linked_list_iterator_has_next(&it)) {
8128         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
8129         if (entry->sid != advertising_sid) {
8130             continue;
8131         }
8132         if (entry->address_type != address_type) {
8133             continue;
8134         }
8135         if (memcmp(entry->address, address, 6) != 0) {
8136             continue;
8137         }
8138         // disallow if already scheduled to add
8139         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
8140             return ERROR_CODE_COMMAND_DISALLOWED;
8141         }
8142         // still on controller, but scheduled to remove -> re-add
8143         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8144         return ERROR_CODE_SUCCESS;
8145     }
8146     // alloc and add to list
8147     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
8148     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8149     entry->sid = advertising_sid;
8150     entry->address_type = address_type;
8151     (void)memcpy(entry->address, address, 6);
8152     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8153     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
8154     return ERROR_CODE_SUCCESS;
8155 }
8156 
8157 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8158     btstack_linked_list_iterator_t it;
8159     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8160     while (btstack_linked_list_iterator_has_next(&it)){
8161         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8162         if (entry->sid != advertising_sid) {
8163             continue;
8164         }
8165         if (entry->address_type != address_type) {
8166             continue;
8167         }
8168         if (memcmp(entry->address, address, 6) != 0) {
8169             continue;
8170         }
8171         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8172             // remove from controller if already present
8173             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8174         }  else {
8175             // directly remove entry from whitelist
8176             btstack_linked_list_iterator_remove(&it);
8177             btstack_memory_periodic_advertiser_list_entry_free(entry);
8178         }
8179         return ERROR_CODE_SUCCESS;
8180     }
8181     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8182 }
8183 
8184 static void hci_periodic_advertiser_list_clear(void){
8185     btstack_linked_list_iterator_t it;
8186     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8187     while (btstack_linked_list_iterator_has_next(&it)){
8188         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8189         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8190             // remove from controller if already present
8191             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8192             continue;
8193         }
8194         // directly remove entry from whitelist
8195         btstack_linked_list_iterator_remove(&it);
8196         btstack_memory_periodic_advertiser_list_entry_free(entry);
8197     }
8198 }
8199 
8200 // free all entries unconditionally
8201 static void hci_periodic_advertiser_list_free(void){
8202     btstack_linked_list_iterator_t lit;
8203     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
8204     while (btstack_linked_list_iterator_has_next(&lit)){
8205         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
8206         btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
8207         btstack_memory_periodic_advertiser_list_entry_free(entry);
8208     }
8209 }
8210 
8211 uint8_t gap_periodic_advertiser_list_clear(void){
8212     hci_periodic_advertiser_list_clear();
8213     hci_run();
8214     return ERROR_CODE_SUCCESS;
8215 }
8216 
8217 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8218     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
8219     if (status){
8220         return status;
8221     }
8222     hci_run();
8223     return ERROR_CODE_SUCCESS;
8224 }
8225 
8226 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8227     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
8228     if (status){
8229         return status;
8230     }
8231     hci_run();
8232     return ERROR_CODE_SUCCESS;
8233 }
8234 
8235 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
8236                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
8237     // abort if already active
8238     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
8239         return ERROR_CODE_COMMAND_DISALLOWED;
8240     }
8241     // store request
8242     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
8243     hci_stack->le_periodic_sync_options = options;
8244     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
8245     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
8246     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
8247     hci_stack->le_periodic_sync_skip = skip;
8248     hci_stack->le_periodic_sync_timeout = sync_timeout;
8249     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
8250 
8251     hci_run();
8252     return ERROR_CODE_SUCCESS;
8253 }
8254 
8255 uint8_t gap_periodic_advertising_create_sync_cancel(void){
8256     // abort if not requested
8257     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
8258         return ERROR_CODE_COMMAND_DISALLOWED;
8259     }
8260     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
8261     hci_run();
8262     return ERROR_CODE_SUCCESS;
8263 }
8264 
8265 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
8266     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
8267         return ERROR_CODE_COMMAND_DISALLOWED;
8268     }
8269     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
8270     hci_run();
8271     return ERROR_CODE_SUCCESS;
8272 }
8273 
8274 #endif
8275 #endif
8276 #endif
8277 
8278 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
8279 void hci_setup_test_connections_fuzz(void){
8280     hci_connection_t * conn;
8281 
8282     // default address: 66:55:44:33:00:01
8283     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
8284 
8285     // setup Controller info
8286     hci_stack->num_cmd_packets = 255;
8287     hci_stack->acl_packets_total_num = 255;
8288 
8289     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
8290     addr[5] = 0x01;
8291     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8292     conn->con_handle = addr[5];
8293     conn->role  = HCI_ROLE_SLAVE;
8294     conn->state = RECEIVED_CONNECTION_REQUEST;
8295     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8296 
8297     // setup incoming Classic SCO connection with con handle 0x0002
8298     addr[5] = 0x02;
8299     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
8300     conn->con_handle = addr[5];
8301     conn->role  = HCI_ROLE_SLAVE;
8302     conn->state = RECEIVED_CONNECTION_REQUEST;
8303     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8304 
8305     // setup ready Classic ACL connection with con handle 0x0003
8306     addr[5] = 0x03;
8307     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8308     conn->con_handle = addr[5];
8309     conn->role  = HCI_ROLE_SLAVE;
8310     conn->state = OPEN;
8311     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8312 
8313     // setup ready Classic SCO connection with con handle 0x0004
8314     addr[5] = 0x04;
8315     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
8316     conn->con_handle = addr[5];
8317     conn->role  = HCI_ROLE_SLAVE;
8318     conn->state = OPEN;
8319     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8320 
8321     // setup ready LE ACL connection with con handle 0x005 and public address
8322     addr[5] = 0x05;
8323     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
8324     conn->con_handle = addr[5];
8325     conn->role  = HCI_ROLE_SLAVE;
8326     conn->state = OPEN;
8327     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
8328     conn->sm_connection.sm_connection_encrypted = 1;
8329 }
8330 
8331 void hci_free_connections_fuzz(void){
8332     btstack_linked_list_iterator_t it;
8333     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
8334     while (btstack_linked_list_iterator_has_next(&it)){
8335         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
8336         btstack_linked_list_iterator_remove(&it);
8337         btstack_memory_hci_connection_free(con);
8338     }
8339 }
8340 void hci_simulate_working_fuzz(void){
8341     hci_stack->le_scanning_param_update = false;
8342     hci_init_done();
8343     hci_stack->num_cmd_packets = 255;
8344 }
8345 #endif
8346