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