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