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