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