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