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