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