xref: /btstack/src/hci.c (revision d9a1d8eddc7ed7db5e263b1004ca50ab93be73d0)
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                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
1217                 conn->acl_recombination_pos = 0;
1218             }
1219 
1220             // peek into L2CAP packet!
1221             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
1222 
1223             // compare fragment size to L2CAP packet size
1224             if (acl_length >= (l2cap_length + 4u)){
1225                 // forward fragment as L2CAP packet
1226                 hci_emit_acl_packet(packet, acl_length + 4u);
1227             } else {
1228 
1229                 if (acl_length > HCI_ACL_BUFFER_SIZE){
1230                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
1231                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
1232                     return;
1233                 }
1234 
1235                 // store first fragment and tweak acl length for complete package
1236                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
1237                              packet, acl_length + 4u);
1238                 conn->acl_recombination_pos    = acl_length + 4u;
1239                 conn->acl_recombination_length = l2cap_length;
1240                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
1241             }
1242             break;
1243 
1244         }
1245         default:
1246             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
1247             return;
1248     }
1249 
1250     // execute main loop
1251     hci_run();
1252 }
1253 
1254 static void hci_connection_stop_timer(hci_connection_t * conn){
1255     btstack_run_loop_remove_timer(&conn->timeout);
1256 #ifdef ENABLE_CLASSIC
1257     btstack_run_loop_remove_timer(&conn->timeout_sco);
1258 #endif
1259 }
1260 
1261 static void hci_shutdown_connection(hci_connection_t *conn){
1262     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
1263 
1264 #ifdef ENABLE_CLASSIC
1265 #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1266     bd_addr_type_t addr_type = conn->address_type;
1267 #endif
1268 #ifdef HAVE_SCO_TRANSPORT
1269     hci_con_handle_t con_handle = conn->con_handle;
1270 #endif
1271 #endif
1272 
1273     hci_connection_stop_timer(conn);
1274 
1275     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1276     btstack_memory_hci_connection_free( conn );
1277 
1278     // now it's gone
1279     hci_emit_nr_connections_changed();
1280 
1281 #ifdef ENABLE_CLASSIC
1282 #ifdef ENABLE_SCO_OVER_HCI
1283     // update SCO
1284     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1285         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1286     }
1287 #endif
1288 #ifdef HAVE_SCO_TRANSPORT
1289     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1290         hci_stack->sco_transport->close(con_handle);
1291     }
1292 #endif
1293 #endif
1294 }
1295 
1296 #ifdef ENABLE_CLASSIC
1297 
1298 static const uint16_t packet_type_sizes[] = {
1299     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
1300     HCI_ACL_DH1_SIZE, 0, 0, 0,
1301     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
1302     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
1303 };
1304 static const uint8_t  packet_type_feature_requirement_bit[] = {
1305      0, // 3 slot packets
1306      1, // 5 slot packets
1307     25, // EDR 2 mpbs
1308     26, // EDR 3 mbps
1309     39, // 3 slot EDR packts
1310     40, // 5 slot EDR packet
1311 };
1312 static const uint16_t packet_type_feature_packet_mask[] = {
1313     0x0f00, // 3 slot packets
1314     0xf000, // 5 slot packets
1315     0x1102, // EDR 2 mpbs
1316     0x2204, // EDR 3 mbps
1317     0x0300, // 3 slot EDR packts
1318     0x3000, // 5 slot EDR packet
1319 };
1320 
1321 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
1322     // enable packet types based on size
1323     uint16_t packet_types = 0;
1324     unsigned int i;
1325     for (i=0;i<16;i++){
1326         if (packet_type_sizes[i] == 0) continue;
1327         if (packet_type_sizes[i] <= buffer_size){
1328             packet_types |= 1 << i;
1329         }
1330     }
1331     // disable packet types due to missing local supported features
1332     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
1333         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
1334         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1335         if (feature_set) continue;
1336         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
1337         packet_types &= ~packet_type_feature_packet_mask[i];
1338     }
1339     // flip bits for "may not be used"
1340     packet_types ^= 0x3306;
1341     return packet_types;
1342 }
1343 
1344 uint16_t hci_usable_acl_packet_types(void){
1345     return hci_stack->packet_types;
1346 }
1347 #endif
1348 
1349 uint8_t* hci_get_outgoing_packet_buffer(void){
1350     // hci packet buffer is >= acl data packet length
1351     return hci_stack->hci_packet_buffer;
1352 }
1353 
1354 uint16_t hci_max_acl_data_packet_length(void){
1355     return hci_stack->acl_data_packet_length;
1356 }
1357 
1358 #ifdef ENABLE_CLASSIC
1359 bool hci_extended_sco_link_supported(void){
1360     // No. 31, byte 3, bit 7
1361     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
1362 }
1363 #endif
1364 
1365 bool hci_non_flushable_packet_boundary_flag_supported(void){
1366     // No. 54, byte 6, bit 6
1367     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
1368 }
1369 
1370 #ifdef ENABLE_CLASSIC
1371 static int gap_ssp_supported(void){
1372     // No. 51, byte 6, bit 3
1373     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1374 }
1375 #endif
1376 
1377 static int hci_classic_supported(void){
1378 #ifdef ENABLE_CLASSIC
1379     // No. 37, byte 4, bit 5, = No BR/EDR Support
1380     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
1381 #else
1382     return 0;
1383 #endif
1384 }
1385 
1386 static int hci_le_supported(void){
1387 #ifdef ENABLE_BLE
1388     // No. 37, byte 4, bit 6 = LE Supported (Controller)
1389     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1390 #else
1391     return 0;
1392 #endif
1393 }
1394 
1395 static bool hci_command_supported(uint8_t command_index){
1396     return (hci_stack->local_supported_commands & (1LU << command_index)) != 0;
1397 }
1398 
1399 #ifdef ENABLE_BLE
1400 
1401 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1402 static bool hci_extended_advertising_supported(void){
1403     return hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE);
1404 }
1405 #endif
1406 
1407 static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
1408     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
1409         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
1410     } else {
1411         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
1412     }
1413 }
1414 
1415 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
1416     *addr_type = hci_stack->le_own_addr_type;
1417     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
1418 }
1419 
1420 #ifdef ENABLE_LE_PERIPHERAL
1421 void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
1422     *addr_type = hci_stack->le_advertisements_own_addr_type;
1423     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
1424 };
1425 #endif
1426 
1427 #ifdef ENABLE_LE_CENTRAL
1428 
1429 /**
1430  * @brief Get own addr type and address used for LE connections (Central)
1431  */
1432 void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
1433     *addr_type = hci_stack->le_connection_own_addr_type;
1434     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
1435 }
1436 
1437 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
1438 
1439     uint16_t offset = 3;
1440     uint8_t num_reports = packet[offset];
1441     offset += 1;
1442 
1443     uint16_t i;
1444     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1445     for (i=0; (i<num_reports) && (offset < size);i++){
1446         // sanity checks on data_length:
1447         uint8_t data_length = packet[offset + 8];
1448         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1449         if ((offset + 9u + data_length + 1u) > size)    return;
1450         // setup event
1451         uint8_t event_size = 10u + data_length;
1452         uint16_t pos = 0;
1453         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1454         event[pos++] = event_size;
1455         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1456         offset += 8;
1457         pos += 8;
1458         event[pos++] = packet[offset + 1 + data_length]; // rssi
1459         event[pos++] = data_length;
1460         offset++;
1461         (void)memcpy(&event[pos], &packet[offset], data_length);
1462         pos +=    data_length;
1463         offset += data_length + 1u; // rssi
1464         hci_emit_event(event, pos, 1);
1465     }
1466 }
1467 
1468 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1469 void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size) {
1470     uint16_t offset = 3;
1471     uint8_t num_reports = packet[offset++];
1472     uint8_t event[2 + 255]; // use upper bound to avoid var size automatic var
1473     uint8_t i;
1474     for (i=0; (i<num_reports) && (offset < size);i++){
1475         // sanity checks on data_length:
1476         uint16_t data_length = packet[offset + 23];
1477         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1478         if ((offset + 24u + data_length) > size)    return;
1479         uint16_t event_type = little_endian_read_16(packet, offset);
1480         offset += 2;
1481         if ((event_type & 0x10) != 0) {
1482            // setup legacy event
1483             uint8_t legacy_event_type;
1484             switch (event_type){
1485                 case 0b0010011:
1486                     // ADV_IND
1487                     legacy_event_type = 0;
1488                     break;
1489                 case 0b0010101:
1490                     // ADV_DIRECT_IND
1491                     legacy_event_type = 1;
1492                     break;
1493                 case 0b0010010:
1494                     // ADV_SCAN_IND
1495                     legacy_event_type = 2;
1496                     break;
1497                 case 0b0010000:
1498                     // ADV_NONCONN_IND
1499                     legacy_event_type = 3;
1500                     break;
1501                 case 0b0011011:
1502                 case 0b0011010:
1503                     // SCAN_RSP
1504                     legacy_event_type = 4;
1505                     break;
1506                 default:
1507                     legacy_event_type = 0;
1508                     break;
1509             }
1510             uint16_t pos = 0;
1511             event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1512             event[pos++] = 10u + data_length;
1513             event[pos++] = legacy_event_type;
1514             // copy address type + address
1515             (void) memcpy(&event[pos], &packet[offset], 1 + 6);
1516             offset += 7;
1517             pos += 7;
1518             // skip primary_phy, secondary_phy, advertising_sid, tx_power
1519             offset += 4;
1520             // copy rssi
1521             event[pos++] = packet[offset++];
1522             // skip periodic advertising interval and direct address
1523             offset += 9;
1524             // copy data len + data;
1525             (void) memcpy(&event[pos], &packet[offset], 1 + data_length);
1526             pos    += 1 +data_length;
1527             offset += 1+ data_length;
1528             hci_emit_event(event, pos, 1);
1529         } else {
1530             event[0] = GAP_EVENT_EXTENDED_ADVERTISING_REPORT;
1531             uint8_t report_len = 24 + data_length;
1532             event[1] = report_len;
1533             little_endian_store_16(event, 2, event_type);
1534             memcpy(&event[4], &packet[offset], report_len);
1535             offset += report_len;
1536             hci_emit_event(event, 2 + report_len, 1);
1537         }
1538     }
1539 }
1540 #endif
1541 
1542 #endif
1543 #endif
1544 
1545 #ifdef ENABLE_BLE
1546 #ifdef ENABLE_LE_PERIPHERAL
1547 static void hci_update_advertisements_enabled_for_current_roles(void){
1548     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ENABLED) != 0){
1549         // get number of active le slave connections
1550         int num_slave_connections = 0;
1551         btstack_linked_list_iterator_t it;
1552         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
1553         while (btstack_linked_list_iterator_has_next(&it)){
1554             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
1555             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
1556             if (con->state != OPEN) continue;
1557             if (con->role  != HCI_ROLE_SLAVE) continue;
1558             if (!hci_is_le_connection(con)) continue;
1559             num_slave_connections++;
1560         }
1561         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1562         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1563     } else {
1564         hci_stack->le_advertisements_enabled_for_current_roles = false;
1565     }
1566 }
1567 #endif
1568 #endif
1569 
1570 #ifdef ENABLE_CLASSIC
1571 static void gap_run_set_local_name(void){
1572     hci_reserve_packet_buffer();
1573     uint8_t * packet = hci_stack->hci_packet_buffer;
1574     // construct HCI Command and send
1575     uint16_t opcode = hci_write_local_name.opcode;
1576     hci_stack->last_cmd_opcode = opcode;
1577     packet[0] = opcode & 0xff;
1578     packet[1] = opcode >> 8;
1579     packet[2] = DEVICE_NAME_LEN;
1580     memset(&packet[3], 0, DEVICE_NAME_LEN);
1581     uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1582     uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
1583     // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
1584     (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
1585     // expand '00:00:00:00:00:00' in name with bd_addr
1586     btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
1587     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1588 }
1589 
1590 static void gap_run_set_eir_data(void){
1591     hci_reserve_packet_buffer();
1592     uint8_t * packet = hci_stack->hci_packet_buffer;
1593     // construct HCI Command in-place and send
1594     uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1595     hci_stack->last_cmd_opcode = opcode;
1596     uint16_t offset = 0;
1597     packet[offset++] = opcode & 0xff;
1598     packet[offset++] = opcode >> 8;
1599     packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
1600     packet[offset++] = 0;  // FEC not required
1601     memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1602     if (hci_stack->eir_data){
1603         // copy items and expand '00:00:00:00:00:00' in name with bd_addr
1604         ad_context_t context;
1605         for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
1606             uint8_t data_type   = ad_iterator_get_data_type(&context);
1607             uint8_t size        = ad_iterator_get_data_len(&context);
1608             const uint8_t *data = ad_iterator_get_data(&context);
1609             // copy item
1610             packet[offset++] = size + 1;
1611             packet[offset++] = data_type;
1612             memcpy(&packet[offset], data, size);
1613             // update name item
1614             if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
1615                 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
1616             }
1617             offset += size;
1618         }
1619     } else {
1620         uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
1621         uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
1622         packet[offset++] = bytes_to_copy + 1;
1623         packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1624         (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
1625         // expand '00:00:00:00:00:00' in name with bd_addr
1626         btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
1627     }
1628     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1629 }
1630 
1631 static void hci_run_gap_tasks_classic(void){
1632     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
1633         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
1634         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1635         return;
1636     }
1637     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_LOCAL_NAME) != 0) {
1638         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_LOCAL_NAME;
1639         gap_run_set_local_name();
1640         return;
1641     }
1642     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_EIR_DATA) != 0) {
1643         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_EIR_DATA;
1644         gap_run_set_eir_data();
1645         return;
1646     }
1647     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
1648         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
1649         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1650         return;
1651     }
1652     // write page scan activity
1653     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) {
1654         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
1655         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
1656         return;
1657     }
1658     // write page scan type
1659     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) {
1660         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE;
1661         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
1662         return;
1663     }
1664     // write page timeout
1665     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_TIMEOUT) != 0) {
1666         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_TIMEOUT;
1667         hci_send_cmd(&hci_write_page_timeout, hci_stack->page_timeout);
1668         return;
1669     }
1670     // send scan enable
1671     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_SCAN_ENABLE) != 0) {
1672         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_SCAN_ENABLE;
1673         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1674         return;
1675     }
1676     // send write scan activity
1677     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY) != 0) {
1678         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
1679         hci_send_cmd(&hci_write_inquiry_scan_activity, hci_stack->inquiry_scan_interval, hci_stack->inquiry_scan_window);
1680         return;
1681     }
1682 }
1683 #endif
1684 
1685 #ifndef HAVE_HOST_CONTROLLER_API
1686 
1687 static uint32_t hci_transport_uart_get_main_baud_rate(void){
1688     if (!hci_stack->config) return 0;
1689     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1690     // Limit baud rate for Broadcom chipsets to 3 mbps
1691     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
1692         baud_rate = 3000000;
1693     }
1694     return baud_rate;
1695 }
1696 
1697 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
1698     UNUSED(ds);
1699 
1700     switch (hci_stack->substate){
1701         case HCI_INIT_W4_SEND_RESET:
1702             log_info("Resend HCI Reset");
1703             hci_stack->substate = HCI_INIT_SEND_RESET;
1704             hci_stack->num_cmd_packets = 1;
1705             hci_run();
1706             break;
1707         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
1708             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
1709             if (hci_stack->hci_transport->reset_link){
1710                 hci_stack->hci_transport->reset_link();
1711             }
1712 
1713             /* fall through */
1714 
1715         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1716             log_info("Resend HCI Reset - CSR Warm Boot");
1717             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1718             hci_stack->num_cmd_packets = 1;
1719             hci_run();
1720             break;
1721         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1722             if (hci_stack->hci_transport->set_baudrate){
1723                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1724                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
1725                 hci_stack->hci_transport->set_baudrate(baud_rate);
1726             }
1727             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
1728             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1729                 if (hci_stack->hci_transport->reset_link){
1730                     log_info("Link Reset");
1731                     hci_stack->hci_transport->reset_link();
1732                 }
1733                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1734                 hci_run();
1735             }
1736             break;
1737         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1738             // otherwise continue
1739             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1740             hci_send_cmd(&hci_read_local_supported_commands);
1741             break;
1742         default:
1743             break;
1744     }
1745 }
1746 #endif
1747 
1748 static void hci_initializing_next_state(void){
1749     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
1750 }
1751 
1752 static void hci_init_done(void){
1753     // done. tell the app
1754     log_info("hci_init_done -> HCI_STATE_WORKING");
1755     hci_stack->state = HCI_STATE_WORKING;
1756     hci_emit_state();
1757 }
1758 
1759 // assumption: hci_can_send_command_packet_now() == true
1760 static void hci_initializing_run(void){
1761     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1762 
1763     if (!hci_can_send_command_packet_now()) return;
1764 
1765 #ifndef HAVE_HOST_CONTROLLER_API
1766     bool need_baud_change = hci_stack->config
1767             && hci_stack->chipset
1768             && hci_stack->chipset->set_baudrate_command
1769             && hci_stack->hci_transport->set_baudrate
1770             && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1771 #endif
1772 
1773     switch (hci_stack->substate){
1774         case HCI_INIT_SEND_RESET:
1775             hci_state_reset();
1776 
1777 #ifndef HAVE_HOST_CONTROLLER_API
1778             // prepare reset if command complete not received in 100ms
1779             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1780             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1781             btstack_run_loop_add_timer(&hci_stack->timeout);
1782 #endif
1783             // send command
1784             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1785             hci_send_cmd(&hci_reset);
1786             break;
1787         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1788             hci_send_cmd(&hci_read_local_version_information);
1789             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1790             break;
1791 
1792 #ifndef HAVE_HOST_CONTROLLER_API
1793         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1794             hci_state_reset();
1795             // prepare reset if command complete not received in 100ms
1796             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1797             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1798             btstack_run_loop_add_timer(&hci_stack->timeout);
1799             // send command
1800             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1801             hci_send_cmd(&hci_reset);
1802             break;
1803         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1804             hci_state_reset();
1805             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1806             hci_send_cmd(&hci_reset);
1807             break;
1808         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1809             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1810             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1811             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1812             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1813             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1814             break;
1815         }
1816         case HCI_INIT_SET_BD_ADDR:
1817             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1818             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1819             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1820             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1821             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1822             break;
1823         case HCI_INIT_SEND_READ_LOCAL_NAME:
1824 #ifdef ENABLE_CLASSIC
1825             hci_send_cmd(&hci_read_local_name);
1826             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1827             break;
1828 #endif
1829             /* fall through */
1830 
1831         case HCI_INIT_SEND_BAUD_CHANGE:
1832             if (need_baud_change) {
1833                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1834                 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1835                 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1836                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1837                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1838                 // STLC25000D: baudrate change happens within 0.5 s after command was send,
1839                 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1840                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1841                     btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1842                     btstack_run_loop_add_timer(&hci_stack->timeout);
1843                }
1844                break;
1845             }
1846 
1847             /* fall through */
1848 
1849         case HCI_INIT_CUSTOM_INIT:
1850             // Custom initialization
1851             if (hci_stack->chipset && hci_stack->chipset->next_command){
1852                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1853                 bool send_cmd = false;
1854                 switch (hci_stack->chipset_result){
1855                     case BTSTACK_CHIPSET_VALID_COMMAND:
1856                         send_cmd = true;
1857                         hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1858                         break;
1859                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1860                         send_cmd = true;
1861                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1862                         log_info("CSR Warm Boot");
1863                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1864                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1865                         btstack_run_loop_add_timer(&hci_stack->timeout);
1866                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1867                             && hci_stack->config
1868                             && hci_stack->chipset
1869                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
1870                             && hci_stack->hci_transport->set_baudrate
1871                             && hci_transport_uart_get_main_baud_rate()){
1872                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1873                         } else {
1874                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1875                         }
1876                         break;
1877                     default:
1878                         break;
1879                 }
1880 
1881                 if (send_cmd){
1882                     int size = 3u + hci_stack->hci_packet_buffer[2u];
1883                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1884                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1885                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1886                     break;
1887                 }
1888                 log_info("Init script done");
1889 
1890                 // Init script download on Broadcom chipsets causes:
1891                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1892                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
1893                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
1894 
1895                     // - baud rate to reset, restore UART baud rate if needed
1896                     if (need_baud_change) {
1897                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1898                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
1899                         hci_stack->hci_transport->set_baudrate(baud_rate);
1900                     }
1901 
1902                     uint16_t bcm_delay_ms = 300;
1903                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
1904                     //   -> Work around: wait here.
1905                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
1906                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1907                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
1908                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1909                     btstack_run_loop_add_timer(&hci_stack->timeout);
1910                     break;
1911                 }
1912             }
1913 #endif
1914             /* fall through */
1915 
1916         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1917             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1918             hci_send_cmd(&hci_read_local_supported_commands);
1919             break;
1920         case HCI_INIT_READ_BD_ADDR:
1921             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1922             hci_send_cmd(&hci_read_bd_addr);
1923             break;
1924         case HCI_INIT_READ_BUFFER_SIZE:
1925             // only read buffer size if supported
1926             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE)){
1927                 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1928                 hci_send_cmd(&hci_read_buffer_size);
1929                 break;
1930             }
1931 
1932             /* fall through */
1933 
1934         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1935             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1936             hci_send_cmd(&hci_read_local_supported_features);
1937             break;
1938 
1939 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1940         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
1941             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
1942             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
1943             break;
1944         case HCI_INIT_HOST_BUFFER_SIZE:
1945             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
1946             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
1947                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
1948             break;
1949 #endif
1950 
1951         case HCI_INIT_SET_EVENT_MASK:
1952             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1953             if (hci_le_supported()){
1954                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
1955             } else {
1956                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1957                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
1958             }
1959             break;
1960 
1961         case HCI_INIT_SET_EVENT_MASK_2:
1962             // On Bluettooth PTS dongle (BL 654) with PacketCraft HCI Firmware (LMP subversion) 0x5244,
1963             // setting Event Mask 2 causes Controller to drop Encryption Change events.
1964             if (hci_command_supported(SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2)
1965             && (hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC)){
1966                 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK_2;
1967                 // Encryption Change Event v2 - bit 25
1968                 hci_send_cmd(&hci_set_event_mask_2,0x02000000U, 0x0);
1969                 break;
1970             }
1971 
1972 #ifdef ENABLE_CLASSIC
1973             /* fall through */
1974 
1975         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1976             if (hci_classic_supported() && gap_ssp_supported()){
1977                 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1978                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1979                 break;
1980             }
1981 
1982             /* fall through */
1983 
1984         case HCI_INIT_WRITE_INQUIRY_MODE:
1985             if (hci_classic_supported()){
1986                 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1987                 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1988                 break;
1989             }
1990 
1991             /* fall through */
1992 
1993         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
1994             // skip write secure connections host support if not supported or disabled
1995             if (hci_classic_supported() && hci_stack->secure_connections_enable
1996             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST)) {
1997                 hci_stack->secure_connections_active = true;
1998                 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
1999                 hci_send_cmd(&hci_write_secure_connections_host_support, 1);
2000                 break;
2001             }
2002 
2003             /* fall through */
2004 
2005         case HCI_INIT_SET_MIN_ENCRYPTION_KEY_SIZE:
2006             // skip set min encryption key size
2007             if (hci_classic_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE)) {
2008                 hci_stack->substate = HCI_INIT_W4_SET_MIN_ENCRYPTION_KEY_SIZE;
2009                 hci_send_cmd(&hci_set_min_encryption_key_size, hci_stack->gap_required_encyrption_key_size);
2010                 break;
2011             }
2012 
2013 #ifdef ENABLE_SCO_OVER_HCI
2014             /* fall through */
2015 
2016         // only sent if ENABLE_SCO_OVER_HCI is defined
2017         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2018             // skip write synchronous flow control if not supported
2019             if (hci_classic_supported()
2020             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)) {
2021                 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
2022                 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
2023                 break;
2024             }
2025             /* fall through */
2026 
2027         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
2028             // skip write default erroneous data reporting if not supported
2029             if (hci_classic_supported()
2030             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) {
2031                 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
2032                 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
2033                 break;
2034             }
2035 #endif
2036 
2037 #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM)
2038             /* fall through */
2039 
2040         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
2041         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
2042             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2043                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
2044 #ifdef ENABLE_SCO_OVER_HCI
2045                 log_info("BCM: Route SCO data via HCI transport");
2046                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
2047 #endif
2048 #ifdef ENABLE_SCO_OVER_PCM
2049                 log_info("BCM: Route SCO data via PCM interface");
2050 #ifdef ENABLE_BCM_PCM_WBS
2051                 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz
2052                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
2053 #else
2054                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
2055                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
2056 #endif
2057 #endif
2058                 break;
2059             }
2060 #endif
2061 
2062 #ifdef ENABLE_SCO_OVER_PCM
2063             /* fall through */
2064 
2065         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
2066             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2067                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
2068                 log_info("BCM: Config PCM interface for I2S");
2069 #ifdef ENABLE_BCM_PCM_WBS
2070                 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
2071                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
2072 #else
2073                 // 256 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, 1);
2075 #endif
2076                 break;
2077             }
2078 #endif
2079 #endif
2080 
2081 #ifdef ENABLE_BLE
2082             /* fall through */
2083 
2084         // LE INIT
2085         case HCI_INIT_LE_READ_BUFFER_SIZE:
2086             if (hci_le_supported()){
2087                 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
2088                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2)){
2089                     hci_send_cmd(&hci_le_read_buffer_size_v2);
2090                 } else {
2091                     hci_send_cmd(&hci_le_read_buffer_size);
2092                 }
2093                 break;
2094             }
2095 
2096             /* fall through */
2097 
2098         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
2099             // skip write le host if not supported (e.g. on LE only EM9301)
2100             if (hci_le_supported()
2101             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED)) {
2102                 // LE Supported Host = 1, Simultaneous Host = 0
2103                 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
2104                 hci_send_cmd(&hci_write_le_host_supported, 1, 0);
2105                 break;
2106             }
2107 
2108             /* fall through */
2109 
2110         case HCI_INIT_LE_SET_EVENT_MASK:
2111             if (hci_le_supported()){
2112                 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
2113                 hci_send_cmd(&hci_le_set_event_mask, 0xfffffdff, 0x07); // all events from core v5.3 without LE Enhanced Connection Complete
2114                 break;
2115             }
2116 #endif
2117 
2118 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2119             /* fall through */
2120 
2121         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
2122             if (hci_le_supported()
2123             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH)) {
2124                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
2125                 hci_send_cmd(&hci_le_read_maximum_data_length);
2126                 break;
2127             }
2128 
2129             /* fall through */
2130 
2131         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
2132             if (hci_le_supported()
2133             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH)) {
2134                 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
2135                 hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
2136                 break;
2137             }
2138 #endif
2139 
2140 #ifdef ENABLE_LE_CENTRAL
2141             /* fall through */
2142 
2143         case HCI_INIT_READ_WHITE_LIST_SIZE:
2144             if (hci_le_supported()){
2145                 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
2146                 hci_send_cmd(&hci_le_read_white_list_size);
2147                 break;
2148             }
2149 
2150 #endif
2151 
2152 #ifdef ENABLE_LE_PERIPHERAL
2153 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
2154             /* fall through */
2155 
2156         case HCI_INIT_LE_READ_MAX_ADV_DATA_LEN:
2157             if (hci_extended_advertising_supported()){
2158                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_ADV_DATA_LEN;
2159                 hci_send_cmd(&hci_le_read_maximum_advertising_data_length);
2160                 break;
2161             }
2162 #endif
2163 #endif
2164             /* fall through */
2165 
2166 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2167     case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS:
2168             if (hci_le_supported()) {
2169                 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS;
2170                 hci_send_cmd(&hci_le_set_host_feature, 32, 1);
2171                 break;
2172             }
2173 #endif
2174 
2175             /* fall through */
2176 
2177         case HCI_INIT_DONE:
2178             hci_stack->substate = HCI_INIT_DONE;
2179             // main init sequence complete
2180 #ifdef ENABLE_CLASSIC
2181             // check if initial Classic GAP Tasks are completed
2182             if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) {
2183                 hci_run_gap_tasks_classic();
2184                 break;
2185             }
2186 #endif
2187 #ifdef ENABLE_BLE
2188 #ifdef ENABLE_LE_CENTRAL
2189             // check if initial LE GAP Tasks are completed
2190             if (hci_le_supported() && hci_stack->le_scanning_param_update) {
2191                 hci_run_general_gap_le();
2192                 break;
2193             }
2194 #endif
2195 #endif
2196             hci_init_done();
2197             break;
2198 
2199         default:
2200             return;
2201     }
2202 }
2203 
2204 static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
2205     bool command_completed = false;
2206     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
2207         uint16_t opcode = little_endian_read_16(packet,3);
2208         if (opcode == hci_stack->last_cmd_opcode){
2209             command_completed = true;
2210             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
2211         } else {
2212             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
2213         }
2214     }
2215 
2216     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
2217         uint8_t  status = packet[2];
2218         uint16_t opcode = little_endian_read_16(packet,4);
2219         if (opcode == hci_stack->last_cmd_opcode){
2220             if (status){
2221                 command_completed = true;
2222                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
2223             } else {
2224                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
2225             }
2226         } else {
2227             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
2228         }
2229     }
2230 #ifndef HAVE_HOST_CONTROLLER_API
2231     // Vendor == CSR
2232     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2233         // TODO: track actual command
2234         command_completed = true;
2235     }
2236 
2237     // Vendor == Toshiba
2238     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2239         // TODO: track actual command
2240         command_completed = true;
2241         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
2242         hci_stack->num_cmd_packets = 1;
2243     }
2244 #endif
2245 
2246     return command_completed;
2247 }
2248 
2249 static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
2250 
2251     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
2252 
2253     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
2254 
2255 #ifndef HAVE_HOST_CONTROLLER_API
2256 
2257     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
2258     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
2259     //
2260     // HCI Reset
2261     // Timeout 100 ms
2262     // HCI Reset
2263     // Command Complete Reset
2264     // HCI Read Local Version Information
2265     // Command Complete Reset - but we expected Command Complete Read Local Version Information
2266     // hang...
2267     //
2268     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
2269     if (!command_completed
2270             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2271             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
2272 
2273         uint16_t opcode = little_endian_read_16(packet,3);
2274         if (opcode == hci_reset.opcode){
2275             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
2276             return;
2277         }
2278     }
2279 
2280     // CSR & H5
2281     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
2282     if (!command_completed
2283             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2284             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
2285 
2286         uint16_t opcode = little_endian_read_16(packet,3);
2287         if (opcode == hci_reset.opcode){
2288             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
2289             return;
2290         }
2291     }
2292 
2293     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
2294     // fix: Correct substate and behave as command below
2295     if (command_completed){
2296         switch (hci_stack->substate){
2297             case HCI_INIT_SEND_RESET:
2298                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
2299                 break;
2300             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
2301                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
2302                 break;
2303             default:
2304                 break;
2305         }
2306     }
2307 
2308 #endif
2309 
2310     if (!command_completed) return;
2311 
2312     bool need_baud_change = false;
2313     bool need_addr_change = false;
2314 
2315 #ifndef HAVE_HOST_CONTROLLER_API
2316     need_baud_change = hci_stack->config
2317                         && hci_stack->chipset
2318                         && hci_stack->chipset->set_baudrate_command
2319                         && hci_stack->hci_transport->set_baudrate
2320                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
2321 
2322     need_addr_change = hci_stack->custom_bd_addr_set
2323                         && hci_stack->chipset
2324                         && hci_stack->chipset->set_bd_addr_command;
2325 #endif
2326 
2327     switch(hci_stack->substate){
2328 
2329 #ifndef HAVE_HOST_CONTROLLER_API
2330         case HCI_INIT_SEND_RESET:
2331             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
2332             // fix: just correct substate and behave as command below
2333 
2334             /* fall through */
2335 #endif
2336 
2337         case HCI_INIT_W4_SEND_RESET:
2338             btstack_run_loop_remove_timer(&hci_stack->timeout);
2339             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
2340             return;
2341 
2342 #ifndef HAVE_HOST_CONTROLLER_API
2343         case HCI_INIT_W4_SEND_BAUD_CHANGE:
2344             // for STLC2500D, baud rate change already happened.
2345             // for others, baud rate gets changed now
2346             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
2347                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2348                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
2349                 hci_stack->hci_transport->set_baudrate(baud_rate);
2350             }
2351             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2352             return;
2353         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
2354             btstack_run_loop_remove_timer(&hci_stack->timeout);
2355             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2356             return;
2357         case HCI_INIT_W4_CUSTOM_INIT:
2358             // repeat custom init
2359             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2360             return;
2361 #endif
2362 
2363         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
2364             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2365               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
2366                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
2367                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
2368                 return;
2369             }
2370             if (need_addr_change){
2371                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2372                 return;
2373             }
2374             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2375             return;
2376 #ifndef HAVE_HOST_CONTROLLER_API
2377         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
2378             if (need_baud_change){
2379                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2380                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
2381                 hci_stack->hci_transport->set_baudrate(baud_rate);
2382             }
2383             if (need_addr_change){
2384                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2385                 return;
2386             }
2387             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2388             return;
2389         case HCI_INIT_W4_SET_BD_ADDR:
2390             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
2391             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
2392             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
2393                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
2394                 return;
2395             }
2396             // skipping st warm boot
2397             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2398             return;
2399         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
2400             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2401             return;
2402 #endif
2403 
2404         case HCI_INIT_DONE:
2405             // set state if we came here by fall through
2406             hci_stack->substate = HCI_INIT_DONE;
2407             return;
2408 
2409         default:
2410             break;
2411     }
2412     hci_initializing_next_state();
2413 }
2414 
2415 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
2416     // CC2564C might emit Connection Complete for rejected incoming SCO connection
2417     // To prevent accidentally free'ing the HCI connection for the ACL connection,
2418     // check if we have been aware of the HCI connection
2419     switch (conn->state){
2420         case SENT_CREATE_CONNECTION:
2421         case RECEIVED_CONNECTION_REQUEST:
2422             break;
2423         default:
2424             return;
2425     }
2426 
2427     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
2428     bd_addr_t bd_address;
2429     (void)memcpy(&bd_address, conn->address, 6);
2430 
2431 #ifdef ENABLE_CLASSIC
2432     // cache needed data
2433     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
2434 #endif
2435 
2436     // connection failed, remove entry
2437     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2438     btstack_memory_hci_connection_free( conn );
2439 
2440 #ifdef ENABLE_CLASSIC
2441     // notify client if dedicated bonding
2442     if (notify_dedicated_bonding_failed){
2443         log_info("hci notify_dedicated_bonding_failed");
2444         hci_emit_dedicated_bonding_result(bd_address, status);
2445     }
2446 
2447     // if authentication error, also delete link key
2448     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
2449         gap_drop_link_key_for_bd_addr(bd_address);
2450     }
2451 #else
2452     UNUSED(status);
2453 #endif
2454 }
2455 
2456 #ifdef ENABLE_CLASSIC
2457 static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
2458     // SSP Controller
2459     if (features[6] & (1 << 3)){
2460         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
2461     }
2462     // eSCO
2463     if (features[3] & (1<<7)){
2464         conn->remote_supported_features[0] |= 1;
2465     }
2466     // Extended features
2467     if (features[7] & (1<<7)){
2468         conn->remote_supported_features[0] |= 2;
2469     }
2470 }
2471 
2472 static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
2473     // SSP Host
2474     if (features[0] & (1 << 0)){
2475         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
2476     }
2477     // SC Host
2478     if (features[0] & (1 << 3)){
2479         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
2480     }
2481 }
2482 
2483 static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
2484     // SC Controller
2485     if (features[1] & (1 << 0)){
2486         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2487     }
2488 }
2489 
2490 static void hci_handle_remote_features_received(hci_connection_t * conn){
2491     conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE;
2492     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2493     log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags);
2494     if (conn->bonding_flags & BONDING_DEDICATED){
2495         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2496     }
2497 }
2498 static bool hci_remote_sc_enabled(hci_connection_t * connection){
2499     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2500     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2501 }
2502 
2503 #endif
2504 
2505 static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
2506     // handle BT initialization
2507     if (hci_stack->state == HCI_STATE_INITIALIZING) {
2508         hci_initializing_event_handler(packet, size);
2509     }
2510 
2511     // help with BT sleep
2512     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
2513         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
2514         && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
2515         && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){
2516         hci_initializing_next_state();
2517     }
2518 }
2519 
2520 #ifdef ENABLE_CLASSIC
2521 static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
2522     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2523     conn->encryption_key_size = encryption_key_size;
2524     gap_security_level_t security_level = gap_security_level_for_connection(conn);
2525 
2526     // trigger disconnect for dedicated bonding, skip emit security level as disconnect is pending
2527     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
2528         conn->bonding_flags &= ~BONDING_DEDICATED;
2529         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2530         conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS;
2531         return;
2532     }
2533 
2534     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
2535         conn->requested_security_level = LEVEL_0;
2536         hci_emit_security_level(conn->con_handle, security_level);
2537         return;
2538     }
2539 
2540     // Request remote features if not already done
2541     hci_trigger_remote_features_for_connection(conn);
2542 
2543     // Request Authentication if not already done
2544     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
2545     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2546 }
2547 #endif
2548 
2549 static void hci_store_local_supported_commands(const uint8_t * packet){
2550     // create mapping table
2551 #define X(name, offset, bit) { offset, bit },
2552     static struct {
2553         uint8_t byte_offset;
2554         uint8_t bit_position;
2555     } supported_hci_commands_map [] = {
2556         SUPPORTED_HCI_COMMANDS
2557     };
2558 #undef X
2559 
2560     // create names for debug purposes
2561 #ifdef ENABLE_LOG_DEBUG
2562 #define X(name, offset, bit) #name,
2563     static const char * command_names[] = {
2564         SUPPORTED_HCI_COMMANDS
2565     };
2566 #undef X
2567 #endif
2568 
2569     hci_stack->local_supported_commands = 0;
2570     const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1];
2571     uint16_t i;
2572     for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){
2573         if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){
2574 #ifdef ENABLE_LOG_DEBUG
2575             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);
2576 #else
2577             log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
2578 #endif
2579             hci_stack->local_supported_commands |= (1LU << i);
2580         }
2581     }
2582     log_info("Local supported commands summary %04x", hci_stack->local_supported_commands);
2583 }
2584 
2585 static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2586     UNUSED(size);
2587 
2588     uint16_t manufacturer;
2589 #ifdef ENABLE_CLASSIC
2590     hci_con_handle_t handle;
2591     hci_connection_t * conn;
2592 #endif
2593 #if defined(ENABLE_CLASSIC) || (defined(ENABLE_BLE) && defined(ENABLE_LE_ISOCHRONOUS_STREAMS))
2594     uint8_t status;
2595 #endif
2596     // get num cmd packets - limit to 1 to reduce complexity
2597     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
2598 
2599     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2600     switch (opcode){
2601         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2602             if (packet[5]) break;
2603             // terminate, name 248 chars
2604             packet[6+248] = 0;
2605             log_info("local name: %s", &packet[6]);
2606             break;
2607         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
2608             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2609             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2610                 uint16_t acl_len = little_endian_read_16(packet, 6);
2611                 uint16_t sco_len = packet[8];
2612 
2613                 // determine usable ACL/SCO payload size
2614                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2615                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2616 
2617                 hci_stack->acl_packets_total_num = (uint8_t) little_endian_read_16(packet, 9);
2618                 hci_stack->sco_packets_total_num = (uint8_t) little_endian_read_16(packet, 11);
2619 
2620                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2621                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
2622                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2623             }
2624             break;
2625         case HCI_OPCODE_HCI_READ_RSSI:
2626             if (packet[5] == ERROR_CODE_SUCCESS){
2627                 uint8_t event[5];
2628                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2629                 event[1] = 3;
2630                 (void)memcpy(&event[2], &packet[6], 3);
2631                 hci_emit_event(event, sizeof(event), 1);
2632             }
2633             break;
2634 #ifdef ENABLE_BLE
2635         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2:
2636             hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9);
2637             hci_stack->le_iso_packets_total_num = packet[11];
2638             log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u",
2639                      hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num);
2640 
2641             /* fall through */
2642 
2643         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2644             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2645             hci_stack->le_acl_packets_total_num = packet[8];
2646             // determine usable ACL payload size
2647             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
2648                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
2649             }
2650             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);
2651             break;
2652 #endif
2653 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2654         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2655             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2656             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2657             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);
2658             break;
2659 #endif
2660 #ifdef ENABLE_LE_CENTRAL
2661         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2662             hci_stack->le_whitelist_capacity = packet[6];
2663             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2664             break;
2665 #endif
2666 #ifdef ENABLE_LE_PERIPHERAL
2667 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
2668         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH:
2669             hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6);
2670             break;
2671         case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS:
2672             if (hci_stack->le_advertising_set_in_current_command != 0) {
2673                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2674                 hci_stack->le_advertising_set_in_current_command = 0;
2675                 if (advertising_set == NULL) break;
2676                 uint8_t adv_status = packet[6];
2677                 uint8_t tx_power   = packet[7];
2678                 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 };
2679                 if (adv_status == 0){
2680                     advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
2681                 }
2682                 hci_emit_event(event, sizeof(event), 1);
2683             }
2684             break;
2685         case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET:
2686             if (hci_stack->le_advertising_set_in_current_command != 0) {
2687                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
2688                 hci_stack->le_advertising_set_in_current_command = 0;
2689                 if (advertising_set == NULL) break;
2690                 uint8_t adv_status = packet[5];
2691                 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, adv_status };
2692                 if (adv_status == 0){
2693                     btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set);
2694                 }
2695                 hci_emit_event(event, sizeof(event), 1);
2696             }
2697             break;
2698 #endif
2699 #endif
2700         case HCI_OPCODE_HCI_READ_BD_ADDR:
2701             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2702             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));
2703 #ifdef ENABLE_CLASSIC
2704             if (hci_stack->link_key_db){
2705                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
2706             }
2707 #endif
2708             break;
2709 #ifdef ENABLE_CLASSIC
2710         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
2711             hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
2712             break;
2713         case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE:
2714             status = hci_event_command_complete_get_return_parameters(packet)[0];
2715             if (status == ERROR_CODE_SUCCESS) {
2716                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC;
2717             } else {
2718                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2719             }
2720             break;
2721         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2722         case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE:
2723             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2724                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2725                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2726                 hci_emit_event(event, sizeof(event), 1);
2727             }
2728             break;
2729 #endif
2730         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
2731             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
2732 
2733 #ifdef ENABLE_CLASSIC
2734             // determine usable ACL packet types based on host buffer size and supported features
2735             hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
2736             log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
2737 #endif
2738             // Classic/LE
2739             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2740             break;
2741         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2742             manufacturer = little_endian_read_16(packet, 10);
2743             // map Cypress to Broadcom
2744             if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2745                 log_info("Treat Cypress as Broadcom");
2746                 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2747                 little_endian_store_16(packet, 10, manufacturer);
2748             }
2749             hci_stack->manufacturer = manufacturer;
2750             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2751             break;
2752         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2753             hci_store_local_supported_commands(packet);
2754             break;
2755 #ifdef ENABLE_CLASSIC
2756         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2757             if (packet[5]) return;
2758             hci_stack->synchronous_flow_control_enabled = 1;
2759             break;
2760         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2761             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2762             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2763             conn   = hci_connection_for_handle(handle);
2764             if (conn != NULL) {
2765                 uint8_t key_size = 0;
2766                 if (status == 0){
2767                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
2768                     log_info("Handle %04x key Size: %u", handle, key_size);
2769                 } else {
2770                     key_size = 1;
2771                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2772                 }
2773                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2774             }
2775             break;
2776         // assert pairing complete event is emitted.
2777         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
2778         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
2779         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
2780         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
2781             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2782             // lookup connection by gap pairing addr
2783             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
2784             if (conn == NULL) break;
2785             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2786             break;
2787 
2788 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2789         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
2790         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
2791             uint8_t event[67];
2792             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
2793             event[1] = 65;
2794             (void)memset(&event[2], 0, 65);
2795             if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){
2796                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
2797                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
2798                     event[2] = 3;
2799                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
2800                 } else {
2801                     event[2] = 1;
2802                 }
2803             }
2804             hci_emit_event(event, sizeof(event), 0);
2805             break;
2806         }
2807 
2808         // note: only needed if user does not provide OOB data
2809         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
2810             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
2811             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
2812             if (conn == NULL) break;
2813             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2814             break;
2815 #endif
2816 #endif
2817 #ifdef ENABLE_BLE
2818 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2819         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
2820         case HCI_OPCODE_HCI_LE_CREATE_CIS:
2821             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2822             if (status != ERROR_CODE_SUCCESS){
2823                 hci_iso_stream_requested_finalize(0xff);
2824             }
2825             break;
2826         case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: {
2827             // lookup BIG by state
2828             btstack_linked_list_iterator_t it;
2829             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
2830             while (btstack_linked_list_iterator_has_next(&it)) {
2831                 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
2832                 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
2833                     status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2834                     if (status == ERROR_CODE_SUCCESS){
2835                         big->state_vars.next_bis++;
2836                         if (big->state_vars.next_bis == big->num_bis){
2837                             big->state = LE_AUDIO_BIG_STATE_ACTIVE;
2838                             hci_emit_big_created(big, ERROR_CODE_SUCCESS);
2839                         } else {
2840                             big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
2841                         }
2842                     } else {
2843                         big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
2844                         big->state_vars.status = status;
2845                     }
2846                     return;
2847                 }
2848             }
2849             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
2850             while (btstack_linked_list_iterator_has_next(&it)) {
2851                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
2852                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
2853                     status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2854                     if (status == ERROR_CODE_SUCCESS){
2855                         big_sync->state_vars.next_bis++;
2856                         if (big_sync->state_vars.next_bis == big_sync->num_bis){
2857                             big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE;
2858                             hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS);
2859                         } else {
2860                             big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
2861                         }
2862                     } else {
2863                         big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
2864                         big_sync->state_vars.status = status;
2865                     }
2866                     return;
2867                 }
2868             }
2869             break;
2870         }
2871         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
2872             // lookup BIG by state
2873             btstack_linked_list_iterator_t it;
2874             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
2875             while (btstack_linked_list_iterator_has_next(&it)) {
2876                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
2877                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED){
2878                     btstack_linked_list_iterator_remove(&it);
2879                     switch (big_sync->state){
2880                         case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
2881                             hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
2882                             break;
2883                         default:
2884                             hci_emit_big_sync_stopped(big_sync);
2885                             break;
2886                     }
2887                     return;
2888                 }
2889             }
2890             break;
2891         }
2892 #endif
2893 #endif
2894         default:
2895             break;
2896     }
2897 }
2898 
2899 static void handle_command_status_event(uint8_t * packet, uint16_t size) {
2900     UNUSED(size);
2901 
2902     // get num cmd packets - limit to 1 to reduce complexity
2903     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2904 
2905     // get opcode and command status
2906     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
2907 
2908 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
2909     uint8_t status = hci_event_command_status_get_status(packet);
2910 #endif
2911 
2912 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
2913     bd_addr_type_t addr_type;
2914 #endif
2915 
2916     switch (opcode){
2917 #ifdef ENABLE_CLASSIC
2918         case HCI_OPCODE_HCI_CREATE_CONNECTION:
2919         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
2920 #endif
2921 #ifdef ENABLE_LE_CENTRAL
2922         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
2923 #endif
2924 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
2925             addr_type = hci_stack->outgoing_addr_type;
2926 
2927             // reset outgoing address info
2928             memset(hci_stack->outgoing_addr, 0, 6);
2929             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2930 
2931             // on error
2932             if (status != ERROR_CODE_SUCCESS){
2933 #ifdef ENABLE_LE_CENTRAL
2934                 if (hci_is_le_connection_type(addr_type)){
2935                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2936                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2937                 }
2938 #endif
2939                 // error => outgoing connection failed
2940                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
2941                 if (conn != NULL){
2942                     hci_handle_connection_failed(conn, status);
2943                 }
2944             }
2945             break;
2946 #endif
2947 #ifdef ENABLE_CLASSIC
2948         case HCI_OPCODE_HCI_INQUIRY:
2949             if (status == ERROR_CODE_SUCCESS) {
2950                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2951             } else {
2952                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2953             }
2954             break;
2955 #endif
2956 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2957         case HCI_OPCODE_HCI_LE_CREATE_CIS:
2958         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
2959             if (status == ERROR_CODE_SUCCESS){
2960                 hci_iso_stream_requested_confirm(0xff);
2961             } else {
2962                 hci_iso_stream_requested_finalize(0xff);
2963             }
2964             break;
2965 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
2966         default:
2967             break;
2968     }
2969 }
2970 
2971 #ifdef ENABLE_BLE
2972 static void event_handle_le_connection_complete(const uint8_t * packet){
2973 	bd_addr_t addr;
2974 	bd_addr_type_t addr_type;
2975 	hci_connection_t * conn;
2976 
2977 	// Connection management
2978 	reverse_bd_addr(&packet[8], addr);
2979 	addr_type = (bd_addr_type_t)packet[7];
2980 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2981 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2982 
2983 #ifdef ENABLE_LE_CENTRAL
2984 	// handle error: error is reported only to the initiator -> outgoing connection
2985 	if (packet[3]){
2986 
2987 		// handle cancelled outgoing connection
2988 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2989 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2990 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2991 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2992 		    // reset state
2993             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
2994             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2995 			// get outgoing connection conn struct for direct connect
2996 			conn = gap_get_outgoing_connection();
2997 		}
2998 
2999 		// outgoing le connection establishment is done
3000 		if (conn){
3001 			// remove entry
3002 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3003 			btstack_memory_hci_connection_free( conn );
3004 		}
3005 		return;
3006 	}
3007 #endif
3008 
3009 	// on success, both hosts receive connection complete event
3010 	if (packet[6] == HCI_ROLE_MASTER){
3011 #ifdef ENABLE_LE_CENTRAL
3012 		// if we're master on an le connection, it was an outgoing connection and we're done with it
3013 		// note: no hci_connection_t object exists yet for connect with whitelist
3014 		if (hci_is_le_connection_type(addr_type)){
3015 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
3016 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3017 		}
3018 #endif
3019 	} else {
3020 #ifdef ENABLE_LE_PERIPHERAL
3021 		// if we're slave, it was an incoming connection, advertisements have stopped
3022         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
3023 #endif
3024 	}
3025 
3026 	// LE connections are auto-accepted, so just create a connection if there isn't one already
3027 	if (!conn){
3028 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3029 	}
3030 
3031 	// no memory, sorry.
3032 	if (!conn){
3033 		return;
3034 	}
3035 
3036 	conn->state = OPEN;
3037 	conn->role  = packet[6];
3038 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
3039 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
3040 
3041 #ifdef ENABLE_LE_PERIPHERAL
3042 	if (packet[6] == HCI_ROLE_SLAVE){
3043 		hci_update_advertisements_enabled_for_current_roles();
3044 	}
3045 #endif
3046 
3047     // init unenhanced att bearer mtu
3048     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3049     conn->att_connection.mtu_exchanged = false;
3050 
3051     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
3052 
3053 	// restart timer
3054 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3055 	// btstack_run_loop_add_timer(&conn->timeout);
3056 
3057 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3058 
3059 	hci_emit_nr_connections_changed();
3060 }
3061 #endif
3062 
3063 #ifdef ENABLE_CLASSIC
3064 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){
3065     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
3066     // LEVEL_4 is tested by l2cap
3067     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
3068     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
3069     if (level >= LEVEL_3){
3070         // MITM not possible without keyboard or display
3071         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3072         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
3073 
3074         // MITM possible if one side has keyboard and the other has keyboard or display
3075         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3076         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
3077 
3078         // MITM not possible if one side has only display and other side has no keyboard
3079         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3080         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
3081     }
3082     // LEVEL 2 requires SSP, which is a given
3083     return true;
3084 }
3085 
3086 static bool btstack_is_null(uint8_t * data, uint16_t size){
3087     uint16_t i;
3088     for (i=0; i < size ; i++){
3089         if (data[i] != 0) {
3090             return false;
3091         }
3092     }
3093     return true;
3094 }
3095 
3096 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
3097     // get requested security level
3098     gap_security_level_t requested_security_level = conn->requested_security_level;
3099     if (hci_stack->gap_secure_connections_only_mode){
3100         requested_security_level = LEVEL_4;
3101     }
3102 
3103     // assess security: LEVEL 4 requires SC
3104     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
3105     if ((requested_security_level == LEVEL_4) &&
3106         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
3107         !hci_remote_sc_enabled(conn)){
3108         log_info("Level 4 required, but SC not supported -> abort");
3109         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3110         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3111         return;
3112     }
3113 
3114     // assess security based on io capabilities
3115     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3116         // responder: fully validate io caps of both sides as well as OOB data
3117         bool security_possible = false;
3118         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3119 
3120 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3121         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3122         // so we merge the OOB data availability
3123         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3124         if (conn->classic_oob_c_192 != NULL){
3125             have_oob_data |= 1;
3126         }
3127         if (conn->classic_oob_c_256 != NULL){
3128             have_oob_data |= 2;
3129         }
3130         // for up to Level 3, either P-192 as well as P-256 will do
3131         // 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
3132         // if remote does not SC, we should not receive P-256 data either
3133         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3134             security_possible = true;
3135         }
3136         // for Level 4, P-256 is needed
3137         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3138             security_possible = true;
3139         }
3140 #endif
3141 
3142         if (security_possible == false){
3143             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3144             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3145             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3146             return;
3147         }
3148     } else {
3149         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
3150 #ifndef ENABLE_CLASSIC_PAIRING_OOB
3151 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3152         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3153             log_info("Level 3+ required, but no input/output -> abort");
3154             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3155             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3156             return;
3157         }
3158 #endif
3159 #endif
3160     }
3161 
3162 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3163     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3164         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3165     } else {
3166         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3167     }
3168 #endif
3169 }
3170 
3171 #endif
3172 
3173 static void event_handler(uint8_t *packet, uint16_t size){
3174 
3175     uint16_t event_length = packet[1];
3176 
3177     // assert packet is complete
3178     if (size != (event_length + 2u)){
3179         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
3180         return;
3181     }
3182 
3183     hci_con_handle_t handle;
3184     hci_connection_t * conn;
3185     int i;
3186 
3187 #ifdef ENABLE_CLASSIC
3188     hci_link_type_t link_type;
3189     bd_addr_t addr;
3190     bd_addr_type_t addr_type;
3191 #endif
3192 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3193     hci_iso_stream_t * iso_stream;
3194     le_audio_big_t   * big;
3195     le_audio_big_sync_t * big_sync;
3196 #endif
3197 
3198     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
3199 
3200     switch (hci_event_packet_get_type(packet)) {
3201 
3202         case HCI_EVENT_COMMAND_COMPLETE:
3203             handle_command_complete_event(packet, size);
3204             break;
3205 
3206         case HCI_EVENT_COMMAND_STATUS:
3207             handle_command_status_event(packet, size);
3208             break;
3209 
3210         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
3211             if (size < 3) return;
3212             uint16_t num_handles = packet[2];
3213             if (size != (3u + num_handles * 4u)) return;
3214 #ifdef ENABLE_CLASSIC
3215             bool notify_sco = false;
3216 #endif
3217 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3218             bool notify_iso = false;
3219 #endif
3220             uint16_t offset = 3;
3221             for (i=0; i<num_handles;i++){
3222                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
3223                 offset += 2u;
3224                 uint16_t num_packets = little_endian_read_16(packet, offset);
3225                 offset += 2u;
3226 
3227                 conn = hci_connection_for_handle(handle);
3228                 if (conn != NULL) {
3229 
3230                     if (conn->num_packets_sent >= num_packets) {
3231                         conn->num_packets_sent -= num_packets;
3232                     } else {
3233                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3234                         conn->num_packets_sent = 0;
3235                     }
3236                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3237 #ifdef ENABLE_CLASSIC
3238                     if (conn->address_type == BD_ADDR_TYPE_SCO){
3239                         notify_sco = true;
3240                     }
3241 #endif
3242                 }
3243 
3244 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
3245                 hci_controller_dump_packets();
3246 #endif
3247 
3248 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3249                 if (conn == NULL){
3250                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle);
3251                     if (iso_stream != NULL){
3252                         if (iso_stream->num_packets_sent >= num_packets) {
3253                             iso_stream->num_packets_sent -= num_packets;
3254                         } else {
3255                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3256                             iso_stream->num_packets_sent = 0;
3257                         }
3258                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3259                                  num_packets, handle, iso_stream->num_packets_sent);
3260                         notify_iso = true;
3261                     }
3262                 }
3263 #endif
3264             }
3265 
3266 #ifdef ENABLE_CLASSIC
3267             if (notify_sco){
3268                 hci_notify_if_sco_can_send_now();
3269             }
3270 #endif
3271 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3272             if (notify_iso){
3273                 hci_iso_notify_can_send_now();
3274             }
3275 #endif
3276             break;
3277         }
3278 
3279 #ifdef ENABLE_CLASSIC
3280         case HCI_EVENT_FLUSH_OCCURRED:
3281             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
3282             handle = hci_event_flush_occurred_get_handle(packet);
3283             conn = hci_connection_for_handle(handle);
3284             if (conn) {
3285                 log_info("Flush occurred, disconnect 0x%04x", handle);
3286                 conn->state = SEND_DISCONNECT;
3287             }
3288             break;
3289 
3290         case HCI_EVENT_INQUIRY_COMPLETE:
3291             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3292                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3293                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
3294                 hci_emit_event(event, sizeof(event), 1);
3295             }
3296             break;
3297         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3298             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3299                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3300             }
3301             break;
3302         case HCI_EVENT_CONNECTION_REQUEST:
3303             reverse_bd_addr(&packet[2], addr);
3304             link_type = (hci_link_type_t) packet[11];
3305 
3306             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
3307             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
3308                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
3309                 bd_addr_copy(hci_stack->decline_addr, addr);
3310                 break;
3311             }
3312 
3313             if (hci_stack->gap_classic_accept_callback != NULL){
3314                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3315                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
3316                     bd_addr_copy(hci_stack->decline_addr, addr);
3317                     break;
3318                 }
3319             }
3320 
3321             // TODO: eval COD 8-10
3322             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
3323             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
3324             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3325             if (!conn) {
3326                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3327             }
3328             if (!conn) {
3329                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
3330                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3331                 bd_addr_copy(hci_stack->decline_addr, addr);
3332                 hci_run();
3333                 // avoid event to higher layer
3334                 return;
3335             }
3336             conn->role  = HCI_ROLE_SLAVE;
3337             conn->state = RECEIVED_CONNECTION_REQUEST;
3338             // store info about eSCO
3339             if (link_type == HCI_LINK_TYPE_ESCO){
3340                 conn->remote_supported_features[0] |= 1;
3341             }
3342             hci_run();
3343             break;
3344 
3345         case HCI_EVENT_CONNECTION_COMPLETE:
3346             // Connection management
3347             reverse_bd_addr(&packet[5], addr);
3348             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3349             addr_type = BD_ADDR_TYPE_ACL;
3350             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3351             if (conn) {
3352                 if (!packet[2]){
3353                     conn->state = OPEN;
3354                     conn->con_handle = little_endian_read_16(packet, 3);
3355 
3356                     // trigger write supervision timeout if we're master
3357                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
3358                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
3359                     }
3360 
3361                     // trigger write automatic flush timeout
3362                     if (hci_stack->automatic_flush_timeout != 0){
3363                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
3364                     }
3365 
3366                     // restart timer
3367                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3368                     btstack_run_loop_add_timer(&conn->timeout);
3369 
3370                     // trigger remote features for dedicated bonding
3371                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3372                         hci_trigger_remote_features_for_connection(conn);
3373                     }
3374 
3375                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
3376 
3377                     hci_emit_nr_connections_changed();
3378                 } else {
3379                     // connection failed
3380                     hci_handle_connection_failed(conn, packet[2]);
3381                 }
3382             }
3383             break;
3384 
3385         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3386             reverse_bd_addr(&packet[5], addr);
3387             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3388             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3389             if (packet[2]){
3390                 // connection failed
3391                 if (conn){
3392                     hci_handle_connection_failed(conn, packet[2]);
3393                 }
3394                 break;
3395             }
3396             if (!conn) {
3397                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3398             }
3399             if (!conn) {
3400                 break;
3401             }
3402             conn->state = OPEN;
3403             conn->con_handle = little_endian_read_16(packet, 3);
3404 
3405 #ifdef ENABLE_SCO_OVER_HCI
3406             // update SCO
3407             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3408                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3409             }
3410             // trigger can send now
3411             if (hci_have_usb_transport()){
3412                 hci_stack->sco_can_send_now = true;
3413             }
3414 #endif
3415 #ifdef HAVE_SCO_TRANSPORT
3416             // configure sco transport
3417             if (hci_stack->sco_transport != NULL){
3418                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3419                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3420             }
3421 #endif
3422             break;
3423 
3424         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3425             handle = little_endian_read_16(packet, 3);
3426             conn = hci_connection_for_handle(handle);
3427             if (!conn) break;
3428             if (!packet[2]){
3429                 const uint8_t * features = &packet[5];
3430                 hci_handle_remote_features_page_0(conn, features);
3431 
3432                 // read extended features if possible
3433                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
3434                 && ((conn->remote_supported_features[0] & 2) != 0)) {
3435                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
3436                     break;
3437                 }
3438             }
3439             hci_handle_remote_features_received(conn);
3440             break;
3441 
3442         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3443             handle = little_endian_read_16(packet, 3);
3444             conn = hci_connection_for_handle(handle);
3445             if (!conn) break;
3446             // status = ok, page = 1
3447             if (!packet[2]) {
3448                 uint8_t page_number = packet[5];
3449                 uint8_t maximum_page_number = packet[6];
3450                 const uint8_t * features = &packet[7];
3451                 bool done = false;
3452                 switch (page_number){
3453                     case 1:
3454                         hci_handle_remote_features_page_1(conn, features);
3455                         if (maximum_page_number >= 2){
3456                             // get Secure Connections (Controller) from Page 2 if available
3457                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
3458                         } else {
3459                             // otherwise, assume SC (Controller) == SC (Host)
3460                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
3461                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
3462                             }
3463                             done = true;
3464                         }
3465                         break;
3466                     case 2:
3467                         hci_handle_remote_features_page_2(conn, features);
3468                         done = true;
3469                         break;
3470                     default:
3471                         break;
3472                 }
3473                 if (!done) break;
3474             }
3475             hci_handle_remote_features_received(conn);
3476             break;
3477 
3478         case HCI_EVENT_LINK_KEY_REQUEST:
3479 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
3480             hci_event_link_key_request_get_bd_addr(packet, addr);
3481             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3482             if (!conn) break;
3483 
3484             // lookup link key in db if not cached
3485             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
3486                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
3487             }
3488 
3489             // response sent by hci_run()
3490             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
3491 #endif
3492             break;
3493 
3494         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
3495             hci_event_link_key_request_get_bd_addr(packet, addr);
3496             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3497             if (!conn) break;
3498 
3499             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
3500 
3501             // CVE-2020-26555: ignore NULL link key
3502             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
3503             if (btstack_is_null(&packet[8], 16)) break;
3504 
3505             link_key_type_t link_key_type = (link_key_type_t)packet[24];
3506             // Change Connection Encryption keeps link key type
3507             if (link_key_type != CHANGED_COMBINATION_KEY){
3508                 conn->link_key_type = link_key_type;
3509             }
3510 
3511             // cache link key. link keys stored in little-endian format for legacy reasons
3512             memcpy(&conn->link_key, &packet[8], 16);
3513 
3514             // only store link key:
3515             // - if bondable enabled
3516             if (hci_stack->bondable == false) break;
3517             // - if security level sufficient
3518             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
3519             // - for SSP, also check if remote side requested bonding as well
3520             if (conn->link_key_type != COMBINATION_KEY){
3521                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3522                 if (!remote_bonding){
3523                     break;
3524                 }
3525             }
3526             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
3527             break;
3528         }
3529 
3530         case HCI_EVENT_PIN_CODE_REQUEST:
3531             hci_event_pin_code_request_get_bd_addr(packet, addr);
3532             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3533             if (!conn) break;
3534 
3535             hci_pairing_started(conn, false);
3536             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
3537             if (!hci_stack->bondable ){
3538                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3539                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3540                 hci_run();
3541                 return;
3542             }
3543             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3544             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3545                 log_info("Level 4 required, but SC not supported -> abort");
3546                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
3547                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3548                 hci_run();
3549                 return;
3550             }
3551             break;
3552 
3553         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
3554             hci_event_io_capability_response_get_bd_addr(packet, addr);
3555             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3556             if (!conn) break;
3557 
3558             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
3559             hci_pairing_started(conn, true);
3560             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3561             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3562 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3563             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3564 #endif
3565             break;
3566 
3567         case HCI_EVENT_IO_CAPABILITY_REQUEST:
3568             hci_event_io_capability_response_get_bd_addr(packet, addr);
3569             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3570             if (!conn) break;
3571 
3572             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
3573             hci_connection_timestamp(conn);
3574             hci_pairing_started(conn, true);
3575             break;
3576 
3577 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3578         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
3579             hci_event_remote_oob_data_request_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_connection_timestamp(conn);
3584 
3585             hci_pairing_started(conn, true);
3586 
3587             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
3588             break;
3589 #endif
3590 
3591         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
3592             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
3593             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3594             if (!conn) break;
3595             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
3596                 if (hci_stack->ssp_auto_accept){
3597                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
3598                 };
3599             } else {
3600                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3601                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
3602                 // don't forward event to app
3603                 hci_run();
3604                 return;
3605             }
3606             break;
3607 
3608         case HCI_EVENT_USER_PASSKEY_REQUEST:
3609             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
3610             if (hci_stack->ssp_auto_accept){
3611                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
3612             };
3613             break;
3614 
3615         case HCI_EVENT_MODE_CHANGE:
3616             handle = hci_event_mode_change_get_handle(packet);
3617             conn = hci_connection_for_handle(handle);
3618             if (!conn) break;
3619             conn->connection_mode = hci_event_mode_change_get_mode(packet);
3620             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
3621             break;
3622 #endif
3623 
3624         case HCI_EVENT_ENCRYPTION_CHANGE:
3625         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
3626             handle = hci_event_encryption_change_get_connection_handle(packet);
3627             conn = hci_connection_for_handle(handle);
3628             if (!conn) break;
3629             if (hci_event_encryption_change_get_status(packet) == 0u) {
3630                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
3631                 if (encryption_enabled){
3632                     if (hci_is_le_connection(conn)){
3633                         // For LE, we accept connection as encrypted
3634                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
3635                     }
3636 #ifdef ENABLE_CLASSIC
3637                     else {
3638 
3639                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
3640                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
3641                         bool connected_uses_aes_ccm = encryption_enabled == 2;
3642                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
3643                             log_info("SC during pairing, but only E0 now -> abort");
3644                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3645                             break;
3646                         }
3647 
3648                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
3649                         if (connected_uses_aes_ccm){
3650                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3651                         }
3652 
3653 #ifdef ENABLE_TESTING_SUPPORT
3654                         // work around for issue with PTS dongle
3655                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3656 #endif
3657                         // validate encryption key size
3658                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
3659                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
3660                             // already got encryption key size
3661                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
3662                         } else {
3663                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
3664                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
3665                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
3666                             } else {
3667                                 // if not, pretend everything is perfect
3668                                 hci_handle_read_encryption_key_size_complete(conn, 16);
3669                             }
3670                         }
3671                     }
3672 #endif
3673                 } else {
3674                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
3675                 }
3676             } else {
3677                 uint8_t status = hci_event_encryption_change_get_status(packet);
3678                 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
3679                     conn->bonding_flags &= ~BONDING_DEDICATED;
3680                     conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
3681                     conn->bonding_status = status;
3682                 }
3683             }
3684 
3685             break;
3686 
3687 #ifdef ENABLE_CLASSIC
3688         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
3689             handle = hci_event_authentication_complete_get_connection_handle(packet);
3690             conn = hci_connection_for_handle(handle);
3691             if (!conn) break;
3692 
3693             // clear authentication active flag
3694             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
3695             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
3696 
3697             // authenticated only if auth status == 0
3698             if (hci_event_authentication_complete_get_status(packet) == 0){
3699                 // authenticated
3700                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3701 
3702                 // If not already encrypted, start encryption
3703                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
3704                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3705                     break;
3706                 }
3707             }
3708 
3709             // emit updated security level
3710             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
3711             break;
3712 
3713         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3714             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3715             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3716             if (!conn) break;
3717 
3718             // treat successfully paired connection as authenticated
3719             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
3720                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3721             }
3722 
3723             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
3724             break;
3725 #endif
3726 
3727         // HCI_EVENT_DISCONNECTION_COMPLETE
3728         // has been split, to first notify stack before shutting connection down
3729         // see end of function, too.
3730         case HCI_EVENT_DISCONNECTION_COMPLETE:
3731             if (packet[2]) break;   // status != 0
3732             handle = little_endian_read_16(packet, 3);
3733             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
3734             if (hci_stack->acl_fragmentation_total_size > 0u) {
3735                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3736                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
3737                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
3738                     hci_stack->acl_fragmentation_total_size = 0;
3739                     hci_stack->acl_fragmentation_pos = 0;
3740                     if (release_buffer){
3741                         hci_release_packet_buffer();
3742                     }
3743                 }
3744             }
3745 
3746 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3747             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
3748             if (hci_stack->iso_fragmentation_total_size > 0u) {
3749                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3750                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
3751                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
3752                     hci_stack->iso_fragmentation_total_size = 0;
3753                     hci_stack->iso_fragmentation_pos = 0;
3754                     if (release_buffer){
3755                         hci_release_packet_buffer();
3756                     }
3757                 }
3758             }
3759 
3760             // finalize iso stream if handle matches
3761             iso_stream = hci_iso_stream_for_con_handle(handle);
3762             if (iso_stream != NULL){
3763                 hci_iso_stream_finalize(iso_stream);
3764                 break;
3765             }
3766 #endif
3767 
3768             conn = hci_connection_for_handle(handle);
3769             if (!conn) break;
3770 #ifdef ENABLE_CLASSIC
3771             // pairing failed if it was ongoing
3772             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
3773 #endif
3774 
3775             // emit dedicatd bonding event
3776             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3777                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3778             }
3779 
3780             // mark connection for shutdown, stop timers, reset state
3781             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3782             hci_connection_stop_timer(conn);
3783             hci_connection_init(conn);
3784 
3785 #ifdef ENABLE_BLE
3786 #ifdef ENABLE_LE_PERIPHERAL
3787             // re-enable advertisements for le connections if active
3788             if (hci_is_le_connection(conn)){
3789                 hci_update_advertisements_enabled_for_current_roles();
3790             }
3791 #endif
3792 #endif
3793             break;
3794 
3795         case HCI_EVENT_HARDWARE_ERROR:
3796             log_error("Hardware Error: 0x%02x", packet[2]);
3797             if (hci_stack->hardware_error_callback){
3798                 (*hci_stack->hardware_error_callback)(packet[2]);
3799             } else {
3800                 // if no special requests, just reboot stack
3801                 hci_power_control_off();
3802                 hci_power_control_on();
3803             }
3804             break;
3805 
3806 #ifdef ENABLE_CLASSIC
3807         case HCI_EVENT_ROLE_CHANGE:
3808             if (packet[2]) break;   // status != 0
3809             reverse_bd_addr(&packet[3], addr);
3810             addr_type = BD_ADDR_TYPE_ACL;
3811             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3812             if (!conn) break;
3813             conn->role = packet[9];
3814             break;
3815 #endif
3816 
3817         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3818             // release packet buffer only for asynchronous transport and if there are not further fragments
3819             if (hci_transport_synchronous()) {
3820                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
3821                 return; // instead of break: to avoid re-entering hci_run()
3822             }
3823             hci_stack->acl_fragmentation_tx_active = 0;
3824 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3825             hci_stack->iso_fragmentation_tx_active = 0;
3826             if (hci_stack->iso_fragmentation_total_size) break;
3827 #endif
3828             if (hci_stack->acl_fragmentation_total_size) break;
3829             hci_release_packet_buffer();
3830 
3831 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3832             hci_iso_notify_can_send_now();
3833 #endif
3834             // L2CAP receives this event via the hci_emit_event below
3835 
3836 #ifdef ENABLE_CLASSIC
3837             // For SCO, we do the can_send_now_check here
3838             hci_notify_if_sco_can_send_now();
3839 #endif
3840             break;
3841 
3842 #ifdef ENABLE_CLASSIC
3843         case HCI_EVENT_SCO_CAN_SEND_NOW:
3844             // For SCO, we do the can_send_now_check here
3845             hci_stack->sco_can_send_now = true;
3846             hci_notify_if_sco_can_send_now();
3847             return;
3848 
3849         // explode inquriy results for easier consumption
3850         case HCI_EVENT_INQUIRY_RESULT:
3851         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3852         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3853             gap_inquiry_explode(packet, size);
3854             break;
3855 #endif
3856 
3857 #ifdef ENABLE_BLE
3858         case HCI_EVENT_LE_META:
3859             switch (packet[2]){
3860 #ifdef ENABLE_LE_CENTRAL
3861                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
3862                     if (!hci_stack->le_scanning_enabled) break;
3863                     le_handle_advertisement_report(packet, size);
3864                     break;
3865 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3866                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
3867                     if (!hci_stack->le_scanning_enabled) break;
3868                     le_handle_extended_advertisement_report(packet, size);
3869                     break;
3870 #endif
3871 #endif
3872                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3873 					event_handle_le_connection_complete(packet);
3874                     break;
3875 
3876                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3877                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3878                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3879                     conn = hci_connection_for_handle(handle);
3880                     if (!conn) break;
3881                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3882                     break;
3883 
3884                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
3885                     // connection
3886                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
3887                     conn = hci_connection_for_handle(handle);
3888                     if (conn) {
3889                         // read arguments
3890                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
3891                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
3892                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
3893                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
3894 
3895                         // validate against current connection parameter range
3896                         le_connection_parameter_range_t existing_range;
3897                         gap_get_connection_parameter_range(&existing_range);
3898                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3899                         if (update_parameter){
3900                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
3901                             conn->le_conn_interval_min = le_conn_interval_min;
3902                             conn->le_conn_interval_max = le_conn_interval_max;
3903                             conn->le_conn_latency = le_conn_latency;
3904                             conn->le_supervision_timeout = le_supervision_timeout;
3905                         } else {
3906                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
3907                         }
3908                     }
3909                     break;
3910 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3911                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
3912                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
3913                     conn = hci_connection_for_handle(handle);
3914                     if (conn) {
3915                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
3916                     }
3917                     break;
3918 #endif
3919 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3920                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
3921                     handle = hci_subevent_le_cis_established_get_connection_handle(packet);
3922                     iso_stream = hci_iso_stream_for_con_handle(handle);
3923                     if (iso_stream){
3924                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
3925                         if (status == ERROR_CODE_SUCCESS){
3926                             iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
3927                         } else {
3928                             hci_iso_stream_finalize(iso_stream);
3929                         }
3930                     }
3931                     break;
3932                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
3933                     big = hci_big_for_handle(packet[4]);
3934                     if (big != NULL){
3935                         uint8_t status = packet[3];
3936                         if (status == ERROR_CODE_SUCCESS){
3937                             // store bis_con_handles and trigger iso path setup
3938                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[20]);
3939                             uint8_t i;
3940                             for (i=0;i<num_bis;i++){
3941                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
3942                                 big->bis_con_handles[i] = bis_handle;
3943                                 // assign bis handle
3944                                 btstack_linked_list_iterator_t it;
3945                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3946                                 while (btstack_linked_list_iterator_has_next(&it)){
3947                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3948                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
3949                                         (iso_stream->big_handle == big->big_handle)){
3950                                         iso_stream->con_handle = bis_handle;
3951                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
3952                                         break;
3953                                     }
3954                                 }
3955                             }
3956                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
3957                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
3958                                 big->state_vars.next_bis = 0;
3959                             }
3960                         } else {
3961                             // create BIG failed or has been stopped by us
3962                             hci_iso_stream_requested_finalize(big->big_handle);
3963                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
3964                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
3965                                 hci_emit_big_created(big, status);
3966                             } else {
3967                                 hci_emit_big_terminated(big);
3968                             }
3969                         }
3970                     }
3971                     break;
3972                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
3973                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
3974                     if (big != NULL){
3975                         // finalize associated ISO streams
3976                         btstack_linked_list_iterator_t it;
3977                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3978                         while (btstack_linked_list_iterator_has_next(&it)){
3979                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3980                             if (iso_stream->big_handle == big->big_handle){
3981                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->big_handle, iso_stream->con_handle);
3982                                 btstack_linked_list_iterator_remove(&it);
3983                                 btstack_memory_hci_iso_stream_free(iso_stream);
3984                             }
3985                         }
3986                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
3987                         switch (big->state){
3988                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
3989                                 hci_emit_big_created(big, big->state_vars.status);
3990                                 break;
3991                             default:
3992                                 hci_emit_big_terminated(big);
3993                                 break;
3994                         }
3995                     }
3996                     break;
3997                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
3998                     big_sync = hci_big_sync_for_handle(packet[4]);
3999                     if (big_sync != NULL){
4000                         uint8_t status = packet[3];
4001                         if (status == ERROR_CODE_SUCCESS){
4002                             // store bis_con_handles and trigger iso path setup
4003                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[16]);
4004                             uint8_t i;
4005                             for (i=0;i<num_bis;i++){
4006                                 big_sync->bis_con_handles[i] = little_endian_read_16(packet, 17 + (2 * i));
4007                             }
4008                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4009                                 // trigger iso path setup
4010                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
4011                                 big_sync->state_vars.next_bis = 0;
4012                             }
4013                         } else {
4014                             // create BIG Sync failed or has been stopped by us
4015                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4016                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
4017                                 hci_emit_big_sync_created(big_sync, status);
4018                             } else {
4019                                 hci_emit_big_sync_stopped(big_sync);
4020                             }
4021                         }
4022                     }
4023                     break;
4024                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4025                     big_sync = hci_big_sync_for_handle(packet[4]);
4026                     if (big_sync != NULL){
4027                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4028                         hci_emit_big_sync_stopped(big_sync);
4029                     }
4030                     break;
4031 #endif
4032                 default:
4033                     break;
4034             }
4035             break;
4036 #endif
4037         case HCI_EVENT_VENDOR_SPECIFIC:
4038             // Vendor specific commands often create vendor specific event instead of num completed packets
4039             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
4040             switch (hci_stack->manufacturer){
4041                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
4042                     hci_stack->num_cmd_packets = 1;
4043                     break;
4044                 default:
4045                     break;
4046             }
4047             break;
4048         default:
4049             break;
4050     }
4051 
4052     handle_event_for_current_stack_state(packet, size);
4053 
4054     // notify upper stack
4055 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
4056 
4057     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4058     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4059 		handle = little_endian_read_16(packet, 3);
4060 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4061 		// discard connection if app did not trigger a reconnect in the event handler
4062 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
4063 			hci_shutdown_connection(aConn);
4064 		}
4065 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
4066         hci_controller_dump_packets();
4067 #endif
4068     }
4069 
4070 	// execute main loop
4071 	hci_run();
4072 }
4073 
4074 #ifdef ENABLE_CLASSIC
4075 
4076 #ifdef ENABLE_SCO_OVER_HCI
4077 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
4078 static void sco_schedule_tx(hci_connection_t * conn);
4079 
4080 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
4081     log_debug("SCO TX Timeout");
4082     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
4083     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4084     if (!conn) return;
4085 
4086     // trigger send
4087     conn->sco_tx_ready = 1;
4088     // extra packet if CVSD but SCO buffer is too short
4089     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
4090         conn->sco_tx_ready++;
4091     }
4092     hci_notify_if_sco_can_send_now();
4093 }
4094 
4095 
4096 #define SCO_TX_AFTER_RX_MS (6)
4097 
4098 static void sco_schedule_tx(hci_connection_t * conn){
4099 
4100     uint32_t now = btstack_run_loop_get_time_ms();
4101     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
4102     int time_delta_ms = sco_tx_ms - now;
4103 
4104     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
4105 
4106     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
4107     btstack_run_loop_remove_timer(timer);
4108     btstack_run_loop_set_timer(timer, time_delta_ms);
4109     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
4110     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
4111     btstack_run_loop_add_timer(timer);
4112 }
4113 #endif
4114 
4115 static void sco_handler(uint8_t * packet, uint16_t size){
4116     // lookup connection struct
4117     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
4118     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
4119     if (!conn) return;
4120 
4121 #ifdef ENABLE_SCO_OVER_HCI
4122     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4123     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4124         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4125             packet[2] = 0x3c;
4126             memmove(&packet[3], &packet[23], 63);
4127             size = 63;
4128         }
4129     }
4130 
4131     if (hci_have_usb_transport()){
4132         // Nothing to do
4133     } else {
4134         // 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);
4135         if (hci_stack->synchronous_flow_control_enabled == 0){
4136             uint32_t now = btstack_run_loop_get_time_ms();
4137 
4138             if (!conn->sco_rx_valid){
4139                 // ignore first 10 packets
4140                 conn->sco_rx_count++;
4141                 // log_debug("sco rx count %u", conn->sco_rx_count);
4142                 if (conn->sco_rx_count == 10) {
4143                     // use first timestamp as is and pretent it just started
4144                     conn->sco_rx_ms = now;
4145                     conn->sco_rx_valid = 1;
4146                     conn->sco_rx_count = 0;
4147                     sco_schedule_tx(conn);
4148                 }
4149             } else {
4150                 // track expected arrival timme
4151                 conn->sco_rx_count++;
4152                 conn->sco_rx_ms += 7;
4153                 int delta = (int32_t) (now - conn->sco_rx_ms);
4154                 if (delta > 0){
4155                     conn->sco_rx_ms++;
4156                 }
4157                 // log_debug("sco rx %u", conn->sco_rx_ms);
4158                 sco_schedule_tx(conn);
4159             }
4160         }
4161     }
4162 #endif
4163 
4164     // deliver to app
4165     if (hci_stack->sco_packet_handler) {
4166         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
4167     }
4168 
4169 #ifdef HAVE_SCO_TRANSPORT
4170     // We can send one packet for each received packet
4171     conn->sco_tx_ready++;
4172     hci_notify_if_sco_can_send_now();
4173 #endif
4174 
4175 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4176     conn->num_packets_completed++;
4177     hci_stack->host_completed_packets = 1;
4178     hci_run();
4179 #endif
4180 }
4181 #endif
4182 
4183 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
4184     hci_dump_packet(packet_type, 1, packet, size);
4185     switch (packet_type) {
4186         case HCI_EVENT_PACKET:
4187             event_handler(packet, size);
4188             break;
4189         case HCI_ACL_DATA_PACKET:
4190             acl_handler(packet, size);
4191             break;
4192 #ifdef ENABLE_CLASSIC
4193         case HCI_SCO_DATA_PACKET:
4194             sco_handler(packet, size);
4195             break;
4196 #endif
4197 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4198         case HCI_ISO_DATA_PACKET:
4199             hci_iso_packet_handler(packet, size);
4200             break;
4201 #endif
4202         default:
4203             break;
4204     }
4205 }
4206 
4207 /**
4208  * @brief Add event packet handler.
4209  */
4210 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4211     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4212 }
4213 
4214 /**
4215  * @brief Remove event packet handler.
4216  */
4217 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
4218     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4219 }
4220 
4221 /** Register HCI packet handlers */
4222 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4223     hci_stack->acl_packet_handler = handler;
4224 }
4225 
4226 #ifdef ENABLE_CLASSIC
4227 /**
4228  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
4229  */
4230 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
4231     hci_stack->sco_packet_handler = handler;
4232 }
4233 #endif
4234 
4235 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4236 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
4237     hci_stack->iso_packet_handler = handler;
4238 }
4239 #endif
4240 
4241 static void hci_state_reset(void){
4242     // no connections yet
4243     hci_stack->connections = NULL;
4244 
4245     // keep discoverable/connectable as this has been requested by the client(s)
4246     // hci_stack->discoverable = 0;
4247     // hci_stack->connectable = 0;
4248     // hci_stack->bondable = 1;
4249     // hci_stack->own_addr_type = 0;
4250 
4251     // buffer is free
4252     hci_stack->hci_packet_buffer_reserved = false;
4253 
4254     // no pending cmds
4255     hci_stack->decline_reason = 0;
4256 
4257     hci_stack->secure_connections_active = false;
4258 
4259 #ifdef ENABLE_CLASSIC
4260     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
4261     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
4262 
4263     hci_stack->gap_tasks_classic =
4264             GAP_TASK_SET_DEFAULT_LINK_POLICY |
4265             GAP_TASK_SET_CLASS_OF_DEVICE |
4266             GAP_TASK_SET_LOCAL_NAME |
4267             GAP_TASK_SET_EIR_DATA |
4268             GAP_TASK_WRITE_SCAN_ENABLE |
4269             GAP_TASK_WRITE_PAGE_TIMEOUT;
4270 #endif
4271 
4272 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4273     hci_stack->classic_read_local_oob_data = false;
4274     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4275 #endif
4276 
4277     // LE
4278 #ifdef ENABLE_BLE
4279     memset(hci_stack->le_random_address, 0, 6);
4280     hci_stack->le_random_address_set = 0;
4281 #endif
4282 #ifdef ENABLE_LE_CENTRAL
4283     hci_stack->le_scanning_active  = false;
4284     hci_stack->le_scanning_param_update = true;
4285     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4286     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4287     hci_stack->le_whitelist_capacity = 0;
4288 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4289     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
4290 #endif
4291 #endif
4292 #ifdef ENABLE_LE_PERIPHERAL
4293     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4294     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4295         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4296     }
4297     if (hci_stack->le_advertisements_data != NULL){
4298         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4299     }
4300 #endif
4301 }
4302 
4303 #ifdef ENABLE_CLASSIC
4304 /**
4305  * @brief Configure Bluetooth hardware control. Has to be called before power on.
4306  */
4307 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
4308     // store and open remote device db
4309     hci_stack->link_key_db = link_key_db;
4310     if (hci_stack->link_key_db) {
4311         hci_stack->link_key_db->open();
4312     }
4313 }
4314 #endif
4315 
4316 void hci_init(const hci_transport_t *transport, const void *config){
4317 
4318 #ifdef HAVE_MALLOC
4319     if (!hci_stack) {
4320         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
4321     }
4322 #else
4323     hci_stack = &hci_stack_static;
4324 #endif
4325     memset(hci_stack, 0, sizeof(hci_stack_t));
4326 
4327     // reference to use transport layer implementation
4328     hci_stack->hci_transport = transport;
4329 
4330     // reference to used config
4331     hci_stack->config = config;
4332 
4333     // setup pointer for outgoing packet buffer
4334     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
4335 
4336     // max acl payload size defined in config.h
4337     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4338 
4339     // register packet handlers with transport
4340     transport->register_packet_handler(&packet_handler);
4341 
4342     hci_stack->state = HCI_STATE_OFF;
4343 
4344     // class of device
4345     hci_stack->class_of_device = 0x007a020c; // Smartphone
4346 
4347     // bondable by default
4348     hci_stack->bondable = 1;
4349 
4350 #ifdef ENABLE_CLASSIC
4351     // classic name
4352     hci_stack->local_name = default_classic_name;
4353 
4354     // Master slave policy
4355     hci_stack->master_slave_policy = 1;
4356 
4357     // Allow Role Switch
4358     hci_stack->allow_role_switch = 1;
4359 
4360     // Default / minimum security level = 2
4361     hci_stack->gap_security_level = LEVEL_2;
4362 
4363     // Default Security Mode 4
4364     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
4365 
4366     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4367     hci_stack->gap_required_encyrption_key_size = 7;
4368 
4369     // Link Supervision Timeout
4370     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4371 
4372 #endif
4373 
4374     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
4375     hci_stack->ssp_enable = 1;
4376     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
4377     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4378     hci_stack->ssp_auto_accept = 1;
4379 
4380     // Secure Connections: enable (requires support from Controller)
4381     hci_stack->secure_connections_enable = true;
4382 
4383     // voice setting - signed 16 bit pcm data with CVSD over the air
4384     hci_stack->sco_voice_setting = 0x60;
4385 
4386 #ifdef ENABLE_LE_CENTRAL
4387     // connection parameter to use for outgoing connections
4388     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
4389     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
4390     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
4391     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
4392     hci_stack->le_connection_latency      = 4;         // 4
4393     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
4394     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
4395     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
4396 
4397     // default LE Scanning
4398     hci_stack->le_scan_type     =   0x1; // active
4399     hci_stack->le_scan_interval = 0x1e0; // 300 ms
4400     hci_stack->le_scan_window   =  0x30; //  30 ms
4401 #endif
4402 
4403 #ifdef ENABLE_LE_PERIPHERAL
4404     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4405 #endif
4406 
4407     // connection parameter range used to answer connection parameter update requests in l2cap
4408     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4409     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4410     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4411     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4412     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4413     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4414 
4415 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4416     hci_stack->iso_packets_to_queue = 1;
4417 #endif
4418 
4419     hci_state_reset();
4420 }
4421 
4422 void hci_deinit(void){
4423     btstack_run_loop_remove_timer(&hci_stack->timeout);
4424 #ifdef HAVE_MALLOC
4425     if (hci_stack) {
4426         free(hci_stack);
4427     }
4428 #endif
4429     hci_stack = NULL;
4430 
4431 #ifdef ENABLE_CLASSIC
4432     disable_l2cap_timeouts = 0;
4433 #endif
4434 }
4435 
4436 /**
4437  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
4438  */
4439 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
4440     hci_stack->chipset = chipset_driver;
4441 
4442     // reset chipset driver - init is also called on power_up
4443     if (hci_stack->chipset && hci_stack->chipset->init){
4444         hci_stack->chipset->init(hci_stack->config);
4445     }
4446 }
4447 
4448 /**
4449  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
4450  */
4451 void hci_set_control(const btstack_control_t *hardware_control){
4452     // references to used control implementation
4453     hci_stack->control = hardware_control;
4454     // init with transport config
4455     hardware_control->init(hci_stack->config);
4456 }
4457 
4458 static void hci_discard_connections(void){
4459     btstack_linked_list_iterator_t it;
4460     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4461     while (btstack_linked_list_iterator_has_next(&it)){
4462         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
4463         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4464         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
4465         hci_shutdown_connection(connection);
4466     }
4467 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4468     while (hci_stack->iso_streams != NULL){
4469         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
4470     }
4471 #endif
4472 }
4473 
4474 void hci_close(void){
4475 
4476 #ifdef ENABLE_CLASSIC
4477     // close remote device db
4478     if (hci_stack->link_key_db) {
4479         hci_stack->link_key_db->close();
4480     }
4481 #endif
4482 
4483     hci_discard_connections();
4484 
4485     hci_power_control(HCI_POWER_OFF);
4486 
4487 #ifdef HAVE_MALLOC
4488     free(hci_stack);
4489 #endif
4490     hci_stack = NULL;
4491 }
4492 
4493 #ifdef HAVE_SCO_TRANSPORT
4494 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
4495     hci_stack->sco_transport = sco_transport;
4496     sco_transport->register_packet_handler(&packet_handler);
4497 }
4498 #endif
4499 
4500 #ifdef ENABLE_CLASSIC
4501 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
4502     // validate ranage and set
4503     if (encryption_key_size < 7)  return;
4504     if (encryption_key_size > 16) return;
4505     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
4506 }
4507 
4508 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
4509     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
4510         hci_stack->gap_security_mode = security_mode;
4511         return ERROR_CODE_SUCCESS;
4512     } else {
4513         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
4514     }
4515 }
4516 
4517 gap_security_mode_t gap_get_security_mode(void){
4518     return hci_stack->gap_security_mode;
4519 }
4520 
4521 void gap_set_security_level(gap_security_level_t security_level){
4522     hci_stack->gap_security_level = security_level;
4523 }
4524 
4525 gap_security_level_t gap_get_security_level(void){
4526     if (hci_stack->gap_secure_connections_only_mode){
4527         return LEVEL_4;
4528     }
4529     return hci_stack->gap_security_level;
4530 }
4531 
4532 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
4533     hci_stack->gap_minimal_service_security_level = security_level;
4534 }
4535 
4536 void gap_set_secure_connections_only_mode(bool enable){
4537     hci_stack->gap_secure_connections_only_mode = enable;
4538 }
4539 
4540 bool gap_get_secure_connections_only_mode(void){
4541     return hci_stack->gap_secure_connections_only_mode;
4542 }
4543 #endif
4544 
4545 #ifdef ENABLE_CLASSIC
4546 void gap_set_class_of_device(uint32_t class_of_device){
4547     hci_stack->class_of_device = class_of_device;
4548     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
4549     hci_run();
4550 }
4551 
4552 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4553     hci_stack->default_link_policy_settings = default_link_policy_settings;
4554     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
4555     hci_run();
4556 }
4557 
4558 void gap_set_allow_role_switch(bool allow_role_switch){
4559     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4560 }
4561 
4562 uint8_t hci_get_allow_role_switch(void){
4563     return  hci_stack->allow_role_switch;
4564 }
4565 
4566 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
4567     hci_stack->link_supervision_timeout = link_supervision_timeout;
4568 }
4569 
4570 void gap_enable_link_watchdog(uint16_t timeout_ms){
4571     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
4572 }
4573 
4574 uint16_t hci_automatic_flush_timeout(void){
4575     return hci_stack->automatic_flush_timeout;
4576 }
4577 
4578 void hci_disable_l2cap_timeout_check(void){
4579     disable_l2cap_timeouts = 1;
4580 }
4581 #endif
4582 
4583 #ifndef HAVE_HOST_CONTROLLER_API
4584 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4585 void hci_set_bd_addr(bd_addr_t addr){
4586     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4587     hci_stack->custom_bd_addr_set = 1;
4588 }
4589 #endif
4590 
4591 // State-Module-Driver overview
4592 // state                    module  low-level
4593 // HCI_STATE_OFF             off      close
4594 // HCI_STATE_INITIALIZING,   on       open
4595 // HCI_STATE_WORKING,        on       open
4596 // HCI_STATE_HALTING,        on       open
4597 // HCI_STATE_SLEEPING,    off/sleep   close
4598 // HCI_STATE_FALLING_ASLEEP  on       open
4599 
4600 static int hci_power_control_on(void){
4601 
4602     // power on
4603     int err = 0;
4604     if (hci_stack->control && hci_stack->control->on){
4605         err = (*hci_stack->control->on)();
4606     }
4607     if (err){
4608         log_error( "POWER_ON failed");
4609         hci_emit_hci_open_failed();
4610         return err;
4611     }
4612 
4613     // int chipset driver
4614     if (hci_stack->chipset && hci_stack->chipset->init){
4615         hci_stack->chipset->init(hci_stack->config);
4616     }
4617 
4618     // init transport
4619     if (hci_stack->hci_transport->init){
4620         hci_stack->hci_transport->init(hci_stack->config);
4621     }
4622 
4623     // open transport
4624     err = hci_stack->hci_transport->open();
4625     if (err){
4626         log_error( "HCI_INIT failed, turning Bluetooth off again");
4627         if (hci_stack->control && hci_stack->control->off){
4628             (*hci_stack->control->off)();
4629         }
4630         hci_emit_hci_open_failed();
4631         return err;
4632     }
4633     return 0;
4634 }
4635 
4636 static void hci_power_control_off(void){
4637 
4638     log_info("hci_power_control_off");
4639 
4640     // close low-level device
4641     hci_stack->hci_transport->close();
4642 
4643     log_info("hci_power_control_off - hci_transport closed");
4644 
4645     // power off
4646     if (hci_stack->control && hci_stack->control->off){
4647         (*hci_stack->control->off)();
4648     }
4649 
4650     log_info("hci_power_control_off - control closed");
4651 
4652     hci_stack->state = HCI_STATE_OFF;
4653 }
4654 
4655 static void hci_power_control_sleep(void){
4656 
4657     log_info("hci_power_control_sleep");
4658 
4659 #if 0
4660     // don't close serial port during sleep
4661 
4662     // close low-level device
4663     hci_stack->hci_transport->close(hci_stack->config);
4664 #endif
4665 
4666     // sleep mode
4667     if (hci_stack->control && hci_stack->control->sleep){
4668         (*hci_stack->control->sleep)();
4669     }
4670 
4671     hci_stack->state = HCI_STATE_SLEEPING;
4672 }
4673 
4674 static int hci_power_control_wake(void){
4675 
4676     log_info("hci_power_control_wake");
4677 
4678     // wake on
4679     if (hci_stack->control && hci_stack->control->wake){
4680         (*hci_stack->control->wake)();
4681     }
4682 
4683 #if 0
4684     // open low-level device
4685     int err = hci_stack->hci_transport->open(hci_stack->config);
4686     if (err){
4687         log_error( "HCI_INIT failed, turning Bluetooth off again");
4688         if (hci_stack->control && hci_stack->control->off){
4689             (*hci_stack->control->off)();
4690         }
4691         hci_emit_hci_open_failed();
4692         return err;
4693     }
4694 #endif
4695 
4696     return 0;
4697 }
4698 
4699 static void hci_power_enter_initializing_state(void){
4700     // set up state machine
4701     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
4702     hci_stack->hci_packet_buffer_reserved = false;
4703     hci_stack->state = HCI_STATE_INITIALIZING;
4704     hci_stack->substate = HCI_INIT_SEND_RESET;
4705 }
4706 
4707 static void hci_power_enter_halting_state(void){
4708 #ifdef ENABLE_BLE
4709     hci_whitelist_free();
4710 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4711     hci_periodic_advertiser_list_free();
4712 #endif
4713 #endif
4714     // see hci_run
4715     hci_stack->state = HCI_STATE_HALTING;
4716     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
4717     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
4718     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
4719     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4720     btstack_run_loop_add_timer(&hci_stack->timeout);
4721 }
4722 
4723 // returns error
4724 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
4725     int err;
4726     switch (power_mode){
4727         case HCI_POWER_ON:
4728             err = hci_power_control_on();
4729             if (err != 0) {
4730                 log_error("hci_power_control_on() error %d", err);
4731                 return err;
4732             }
4733             hci_power_enter_initializing_state();
4734             break;
4735         case HCI_POWER_OFF:
4736             // do nothing
4737             break;
4738         case HCI_POWER_SLEEP:
4739             // do nothing (with SLEEP == OFF)
4740             break;
4741         default:
4742             btstack_assert(false);
4743             break;
4744     }
4745     return ERROR_CODE_SUCCESS;
4746 }
4747 
4748 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
4749     switch (power_mode){
4750         case HCI_POWER_ON:
4751             // do nothing
4752             break;
4753         case HCI_POWER_OFF:
4754             // no connections yet, just turn it off
4755             hci_power_control_off();
4756             break;
4757         case HCI_POWER_SLEEP:
4758             // no connections yet, just turn it off
4759             hci_power_control_sleep();
4760             break;
4761         default:
4762             btstack_assert(false);
4763             break;
4764     }
4765     return ERROR_CODE_SUCCESS;
4766 }
4767 
4768 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
4769     switch (power_mode){
4770         case HCI_POWER_ON:
4771             // do nothing
4772             break;
4773         case HCI_POWER_OFF:
4774             hci_power_enter_halting_state();
4775             break;
4776         case HCI_POWER_SLEEP:
4777             // see hci_run
4778             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4779             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4780             break;
4781         default:
4782             btstack_assert(false);
4783             break;
4784     }
4785     return ERROR_CODE_SUCCESS;
4786 }
4787 
4788 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
4789     switch (power_mode){
4790         case HCI_POWER_ON:
4791             hci_power_enter_initializing_state();
4792             break;
4793         case HCI_POWER_OFF:
4794             // do nothing
4795             break;
4796         case HCI_POWER_SLEEP:
4797             // see hci_run
4798             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
4799             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
4800             break;
4801         default:
4802             btstack_assert(false);
4803             break;
4804     }
4805     return ERROR_CODE_SUCCESS;
4806 }
4807 
4808 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
4809     switch (power_mode){
4810         case HCI_POWER_ON:
4811             hci_power_enter_initializing_state();
4812             break;
4813         case HCI_POWER_OFF:
4814             hci_power_enter_halting_state();
4815             break;
4816         case HCI_POWER_SLEEP:
4817             // do nothing
4818             break;
4819         default:
4820             btstack_assert(false);
4821             break;
4822     }
4823     return ERROR_CODE_SUCCESS;
4824 }
4825 
4826 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
4827     int err;
4828     switch (power_mode){
4829         case HCI_POWER_ON:
4830             err = hci_power_control_wake();
4831             if (err) return err;
4832             hci_power_enter_initializing_state();
4833             break;
4834         case HCI_POWER_OFF:
4835             hci_power_enter_halting_state();
4836             break;
4837         case HCI_POWER_SLEEP:
4838             // do nothing
4839             break;
4840         default:
4841             btstack_assert(false);
4842             break;
4843     }
4844     return ERROR_CODE_SUCCESS;
4845 }
4846 
4847 int hci_power_control(HCI_POWER_MODE power_mode){
4848     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
4849     int err = 0;
4850     switch (hci_stack->state){
4851         case HCI_STATE_OFF:
4852             err = hci_power_control_state_off(power_mode);
4853             break;
4854         case HCI_STATE_INITIALIZING:
4855             err = hci_power_control_state_initializing(power_mode);
4856             break;
4857         case HCI_STATE_WORKING:
4858             err = hci_power_control_state_working(power_mode);
4859             break;
4860         case HCI_STATE_HALTING:
4861             err = hci_power_control_state_halting(power_mode);
4862             break;
4863         case HCI_STATE_FALLING_ASLEEP:
4864             err = hci_power_control_state_falling_asleep(power_mode);
4865             break;
4866         case HCI_STATE_SLEEPING:
4867             err = hci_power_control_state_sleeping(power_mode);
4868             break;
4869         default:
4870             btstack_assert(false);
4871             break;
4872     }
4873     if (err != 0){
4874         return err;
4875     }
4876 
4877     // create internal event
4878 	hci_emit_state();
4879 
4880 	// trigger next/first action
4881 	hci_run();
4882 
4883     return 0;
4884 }
4885 
4886 
4887 static void hci_halting_run(void) {
4888 
4889     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4890 
4891     hci_connection_t *connection;
4892 #ifdef ENABLE_BLE
4893 #ifdef ENABLE_LE_PERIPHERAL
4894     bool stop_advertismenets;
4895 #endif
4896 #endif
4897 
4898     switch (hci_stack->substate) {
4899         case HCI_HALTING_CLASSIC_STOP:
4900 #ifdef ENABLE_CLASSIC
4901             if (!hci_can_send_command_packet_now()) return;
4902 
4903             if (hci_stack->connectable || hci_stack->discoverable){
4904                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4905                 hci_send_cmd(&hci_write_scan_enable, 0);
4906                 return;
4907             }
4908 #endif
4909             /* fall through */
4910 
4911         case HCI_HALTING_LE_ADV_STOP:
4912             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
4913 
4914 #ifdef ENABLE_BLE
4915 #ifdef ENABLE_LE_PERIPHERAL
4916             if (!hci_can_send_command_packet_now()) return;
4917 
4918             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
4919 
4920 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4921             if (hci_extended_advertising_supported()){
4922 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4923                 btstack_linked_list_iterator_t it;
4924                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4925                 // stop all periodic advertisements and check if an extended set is active
4926                 while (btstack_linked_list_iterator_has_next(&it)){
4927                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4928                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
4929                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
4930                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
4931                         return;
4932                     }
4933                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
4934                         stop_advertismenets = true;
4935                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4936                     }
4937                 }
4938 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
4939                 if (stop_advertismenets){
4940                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4941                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
4942                     return;
4943                 }
4944             }
4945             else
4946 #else /* ENABLE_LE_PERIPHERAL */
4947             {
4948                 if (stop_advertismenets) {
4949                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4950                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
4951                     return;
4952                 }
4953             }
4954 #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
4955 #endif  /* ENABLE_LE_PERIPHERAL */
4956 #endif  /* ENABLE_BLE */
4957 
4958             /* fall through */
4959 
4960         case HCI_HALTING_LE_SCAN_STOP:
4961             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
4962             if (!hci_can_send_command_packet_now()) return;
4963 
4964 #ifdef ENABLE_BLE
4965 #ifdef ENABLE_LE_CENTRAL
4966             if (hci_stack->le_scanning_active){
4967                 hci_le_scan_stop();
4968                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4969                 return;
4970             }
4971 #endif
4972 #endif
4973 
4974             /* fall through */
4975 
4976         case HCI_HALTING_DISCONNECT_ALL:
4977             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4978             if (!hci_can_send_command_packet_now()) return;
4979 
4980             // close all open connections
4981             connection = (hci_connection_t *) hci_stack->connections;
4982             if (connection) {
4983                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4984 
4985                 // check state
4986                 if (connection->state == SENT_DISCONNECT) return;
4987                 connection->state = SENT_DISCONNECT;
4988 
4989                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4990 
4991                 // finally, send the disconnect command
4992                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4993                 return;
4994             }
4995 
4996 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4997             // stop BIGs and BIG Syncs
4998             if (hci_stack->le_audio_bigs != NULL){
4999                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5000                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5001                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5002                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5003                 return;
5004             }
5005             if (hci_stack->le_audio_big_syncs != NULL){
5006                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5007                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5008                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5009                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5010                 return;
5011             }
5012 #endif
5013 
5014             btstack_run_loop_remove_timer(&hci_stack->timeout);
5015 
5016             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5017             log_info("HCI_STATE_HALTING: wait 50 ms");
5018             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5019             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5020             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5021             btstack_run_loop_add_timer(&hci_stack->timeout);
5022             break;
5023 
5024         case HCI_HALTING_CLOSE:
5025             // close left over connections (that had not been properly closed before)
5026             hci_discard_connections();
5027 
5028             log_info("HCI_STATE_HALTING, calling off");
5029 
5030             // switch mode
5031             hci_power_control_off();
5032 
5033             log_info("HCI_STATE_HALTING, emitting state");
5034             hci_emit_state();
5035             log_info("HCI_STATE_HALTING, done");
5036             break;
5037 
5038         case HCI_HALTING_W4_CLOSE_TIMER:
5039             // keep waiting
5040 
5041             break;
5042         default:
5043             break;
5044     }
5045 };
5046 
5047 static void hci_falling_asleep_run(void){
5048     hci_connection_t * connection;
5049     switch(hci_stack->substate) {
5050         case HCI_FALLING_ASLEEP_DISCONNECT:
5051             log_info("HCI_STATE_FALLING_ASLEEP");
5052             // close all open connections
5053             connection =  (hci_connection_t *) hci_stack->connections;
5054             if (connection){
5055 
5056                 // send disconnect
5057                 if (!hci_can_send_command_packet_now()) return;
5058 
5059                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5060                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5061 
5062                 // send disconnected event right away - causes higher layer connections to get closed, too.
5063                 hci_shutdown_connection(connection);
5064                 return;
5065             }
5066 
5067             if (hci_classic_supported()){
5068                 // disable page and inquiry scan
5069                 if (!hci_can_send_command_packet_now()) return;
5070 
5071                 log_info("HCI_STATE_HALTING, disabling inq scans");
5072                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5073 
5074                 // continue in next sub state
5075                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5076                 break;
5077             }
5078 
5079             /* fall through */
5080 
5081             case HCI_FALLING_ASLEEP_COMPLETE:
5082                 log_info("HCI_STATE_HALTING, calling sleep");
5083                 // switch mode
5084                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5085                 hci_emit_state();
5086                 break;
5087 
5088                 default:
5089                     break;
5090     }
5091 }
5092 
5093 #ifdef ENABLE_CLASSIC
5094 
5095 static void hci_update_scan_enable(void){
5096     // 2 = page scan, 1 = inq scan
5097     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5098     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5099     hci_run();
5100 }
5101 
5102 void gap_discoverable_control(uint8_t enable){
5103     if (enable) enable = 1; // normalize argument
5104 
5105     if (hci_stack->discoverable == enable){
5106         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5107         return;
5108     }
5109 
5110     hci_stack->discoverable = enable;
5111     hci_update_scan_enable();
5112 }
5113 
5114 void gap_connectable_control(uint8_t enable){
5115     if (enable) enable = 1; // normalize argument
5116 
5117     // don't emit event
5118     if (hci_stack->connectable == enable) return;
5119 
5120     hci_stack->connectable = enable;
5121     hci_update_scan_enable();
5122 }
5123 #endif
5124 
5125 void gap_local_bd_addr(bd_addr_t address_buffer){
5126     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
5127 }
5128 
5129 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
5130 static void hci_host_num_completed_packets(void){
5131 
5132     // create packet manually as arrays are not supported and num_commands should not get reduced
5133     hci_reserve_packet_buffer();
5134     uint8_t * packet = hci_get_outgoing_packet_buffer();
5135 
5136     uint16_t size = 0;
5137     uint16_t num_handles = 0;
5138     packet[size++] = 0x35;
5139     packet[size++] = 0x0c;
5140     size++;  // skip param len
5141     size++;  // skip num handles
5142 
5143     // add { handle, packets } entries
5144     btstack_linked_item_t * it;
5145     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5146         hci_connection_t * connection = (hci_connection_t *) it;
5147         if (connection->num_packets_completed){
5148             little_endian_store_16(packet, size, connection->con_handle);
5149             size += 2;
5150             little_endian_store_16(packet, size, connection->num_packets_completed);
5151             size += 2;
5152             //
5153             num_handles++;
5154             connection->num_packets_completed = 0;
5155         }
5156     }
5157 
5158     packet[2] = size - 3;
5159     packet[3] = num_handles;
5160 
5161     hci_stack->host_completed_packets = 0;
5162 
5163     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5164     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5165 
5166     // release packet buffer for synchronous transport implementations
5167     if (hci_transport_synchronous()){
5168         hci_release_packet_buffer();
5169         hci_emit_transport_packet_sent();
5170     }
5171 }
5172 #endif
5173 
5174 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
5175     UNUSED(ds);
5176     hci_stack->substate = HCI_HALTING_CLOSE;
5177     // allow packet handlers to defer final shutdown
5178     hci_emit_state();
5179     hci_run();
5180 }
5181 
5182 static bool hci_run_acl_fragments(void){
5183     if (hci_stack->acl_fragmentation_total_size > 0u) {
5184         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5185         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5186         if (connection) {
5187             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5188                 hci_send_acl_packet_fragments(connection);
5189                 return true;
5190             }
5191         } else {
5192             // connection gone -> discard further fragments
5193             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5194             hci_stack->acl_fragmentation_total_size = 0;
5195             hci_stack->acl_fragmentation_pos = 0;
5196         }
5197     }
5198     return false;
5199 }
5200 
5201 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5202 static bool hci_run_iso_fragments(void){
5203     if (hci_stack->iso_fragmentation_total_size > 0u) {
5204         // TODO: flow control
5205         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
5206             hci_send_iso_packet_fragments();
5207             return true;
5208         }
5209     }
5210     return false;
5211 }
5212 #endif
5213 
5214 #ifdef ENABLE_CLASSIC
5215 
5216 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5217 static bool hci_classic_operation_active(void) {
5218     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
5219         return true;
5220     }
5221     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
5222         return true;
5223     }
5224     btstack_linked_item_t * it;
5225     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
5226         hci_connection_t *connection = (hci_connection_t *) it;
5227         switch (connection->state) {
5228             case SENT_CREATE_CONNECTION:
5229             case SENT_CANCEL_CONNECTION:
5230             case SENT_DISCONNECT:
5231                 return true;
5232             default:
5233                 break;
5234         }
5235     }
5236     return false;
5237 }
5238 #endif
5239 
5240 static bool hci_run_general_gap_classic(void){
5241 
5242     // assert stack is working and classic is active
5243     if (hci_classic_supported() == false)      return false;
5244     if (hci_stack->state != HCI_STATE_WORKING) return false;
5245 
5246     // decline incoming connections
5247     if (hci_stack->decline_reason){
5248         uint8_t reason = hci_stack->decline_reason;
5249         hci_stack->decline_reason = 0;
5250         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5251         return true;
5252     }
5253 
5254     if (hci_stack->gap_tasks_classic != 0){
5255         hci_run_gap_tasks_classic();
5256         return true;
5257     }
5258 
5259     // start/stop inquiry
5260     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
5261 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5262         if (hci_classic_operation_active() == false)
5263 #endif
5264         {
5265             uint8_t duration = hci_stack->inquiry_state;
5266             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
5267             if (hci_stack->inquiry_max_period_length != 0){
5268                 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);
5269             } else {
5270                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
5271             }
5272             return true;
5273         }
5274     }
5275     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5276         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5277         hci_send_cmd(&hci_inquiry_cancel);
5278         return true;
5279     }
5280 
5281     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5282         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5283         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
5284         return true;
5285     }
5286 
5287     // remote name request
5288     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
5289 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
5290         if (hci_classic_operation_active() == false)
5291 #endif
5292         {
5293             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5294             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5295                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5296             return true;
5297         }
5298     }
5299 #ifdef ENABLE_CLASSIC_PAIRING_OOB
5300     // Local OOB data
5301     if (hci_stack->classic_read_local_oob_data){
5302         hci_stack->classic_read_local_oob_data = false;
5303         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5304             hci_send_cmd(&hci_read_local_extended_oob_data);
5305         } else {
5306             hci_send_cmd(&hci_read_local_oob_data);
5307         }
5308     }
5309 #endif
5310     // pairing
5311     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
5312         uint8_t state = hci_stack->gap_pairing_state;
5313         uint8_t pin_code[16];
5314         switch (state){
5315             case GAP_PAIRING_STATE_SEND_PIN:
5316                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5317                 memset(pin_code, 0, 16);
5318                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
5319                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
5320                 break;
5321             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5322                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5323                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
5324                 break;
5325             case GAP_PAIRING_STATE_SEND_PASSKEY:
5326                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5327                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
5328                 break;
5329             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5330                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5331                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
5332                 break;
5333             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5334                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5335                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
5336                 break;
5337             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5338                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
5339                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
5340                 break;
5341             default:
5342                 break;
5343         }
5344         return true;
5345     }
5346     return false;
5347 }
5348 #endif
5349 
5350 #ifdef ENABLE_BLE
5351 
5352 #ifdef ENABLE_LE_CENTRAL
5353 static void hci_le_scan_stop(void){
5354 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5355     if (hci_extended_advertising_supported()) {
5356             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5357         } else
5358 #endif
5359     {
5360         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5361     }
5362 }
5363 #endif
5364 
5365 #ifdef ENABLE_LE_PERIPHERAL
5366 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5367 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
5368     uint8_t  operation = 0;
5369     if (pos == 0){
5370         // first fragment or complete data
5371         operation |= 1;
5372     }
5373     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
5374         // last fragment or complete data
5375         operation |= 2;
5376     }
5377     return operation;
5378 }
5379 #endif
5380 #endif
5381 
5382 static bool hci_run_general_gap_le(void){
5383 
5384     btstack_linked_list_iterator_t lit;
5385 
5386     // Phase 1: collect what to stop
5387 
5388 #ifdef ENABLE_LE_CENTRAL
5389     bool scanning_stop = false;
5390     bool connecting_stop = false;
5391 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5392 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5393     bool periodic_sync_stop = false;
5394 #endif
5395 #endif
5396 #endif
5397 
5398 #ifdef ENABLE_LE_PERIPHERAL
5399     bool advertising_stop = false;
5400 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5401     le_advertising_set_t * advertising_stop_set = NULL;
5402 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5403     bool periodic_advertising_stop = false;
5404 #endif
5405 #endif
5406 #endif
5407 
5408     // check if own address changes
5409     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5410 
5411     // check if whitelist needs modification
5412     bool whitelist_modification_pending = false;
5413     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5414     while (btstack_linked_list_iterator_has_next(&lit)){
5415         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5416         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
5417             whitelist_modification_pending = true;
5418             break;
5419         }
5420     }
5421 
5422     // check if resolving list needs modification
5423     bool resolving_list_modification_pending = false;
5424 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5425     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
5426 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
5427         resolving_list_modification_pending = true;
5428     }
5429 #endif
5430 
5431 #ifdef ENABLE_LE_CENTRAL
5432 
5433 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5434     // check if periodic advertiser list needs modification
5435     bool periodic_list_modification_pending = false;
5436     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5437     while (btstack_linked_list_iterator_has_next(&lit)){
5438         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5439         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
5440             periodic_list_modification_pending = true;
5441             break;
5442         }
5443     }
5444 #endif
5445 
5446     // scanning control
5447     if (hci_stack->le_scanning_active) {
5448         // stop if:
5449         // - parameter change required
5450         // - it's disabled
5451         // - whitelist change required but used for scanning
5452         // - resolving list modified
5453         // - own address changes
5454         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
5455         if ((hci_stack->le_scanning_param_update) ||
5456             !hci_stack->le_scanning_enabled ||
5457             (scanning_uses_whitelist && whitelist_modification_pending) ||
5458             resolving_list_modification_pending ||
5459             random_address_change){
5460 
5461             scanning_stop = true;
5462         }
5463     }
5464 
5465     // connecting control
5466     bool connecting_with_whitelist;
5467     switch (hci_stack->le_connecting_state){
5468         case LE_CONNECTING_DIRECT:
5469         case LE_CONNECTING_WHITELIST:
5470             // stop connecting if:
5471             // - connecting uses white and whitelist modification pending
5472             // - if it got disabled
5473             // - resolving list modified
5474             // - own address changes
5475             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
5476             if ((connecting_with_whitelist && whitelist_modification_pending) ||
5477                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
5478                 resolving_list_modification_pending ||
5479                 random_address_change) {
5480 
5481                 connecting_stop = true;
5482             }
5483             break;
5484         default:
5485             break;
5486     }
5487 
5488 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5489 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5490     // periodic sync control
5491     bool sync_with_advertiser_list;
5492     switch(hci_stack->le_periodic_sync_state){
5493         case LE_CONNECTING_DIRECT:
5494         case LE_CONNECTING_WHITELIST:
5495             // stop sync if:
5496             // - sync with advertiser list and advertiser list modification pending
5497             // - if it got disabled
5498             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
5499             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
5500                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
5501                 periodic_sync_stop = true;
5502             }
5503             break;
5504         default:
5505             break;
5506     }
5507 #endif
5508 #endif
5509 
5510 #endif /* ENABLE_LE_CENTRAL */
5511 
5512 #ifdef ENABLE_LE_PERIPHERAL
5513     // le advertisement control
5514     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
5515         // stop if:
5516         // - parameter change required
5517         // - random address used in advertising and changes
5518         // - it's disabled
5519         // - whitelist change required but used for advertisement filter policy
5520         // - resolving list modified
5521         // - own address changes
5522         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
5523         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
5524         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
5525         if (advertising_change ||
5526             (advertising_uses_random_address && random_address_change) ||
5527             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
5528             (advertising_uses_whitelist && whitelist_modification_pending) ||
5529             resolving_list_modification_pending ||
5530             random_address_change) {
5531 
5532             advertising_stop = true;
5533         }
5534     }
5535 
5536 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5537     if (hci_extended_advertising_supported() && (advertising_stop == false)){
5538         btstack_linked_list_iterator_t it;
5539         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5540         while (btstack_linked_list_iterator_has_next(&it)){
5541             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5542             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5543                 // stop if:
5544                 // - parameter change required
5545                 // - random address used in connectable advertising and changes
5546                 // - it's disabled
5547                 // - whitelist change required but used for advertisement filter policy
5548                 // - resolving list modified
5549                 // - own address changes
5550                 // - advertisement set will be removed
5551                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
5552                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
5553                 bool advertising_uses_random_address =
5554                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
5555                         advertising_connectable;
5556                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
5557                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
5558                 bool advertising_set_random_address_change =
5559                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
5560                 bool advertising_set_will_be_removed =
5561                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
5562                 if (advertising_parameter_change ||
5563                     (advertising_uses_random_address && advertising_set_random_address_change) ||
5564                     (advertising_enabled == false) ||
5565                     (advertising_uses_whitelist && whitelist_modification_pending) ||
5566                     resolving_list_modification_pending ||
5567                     advertising_set_will_be_removed) {
5568 
5569                     advertising_stop = true;
5570                     advertising_stop_set = advertising_set;
5571                     break;
5572                 }
5573             }
5574 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5575             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5576                 // stop if:
5577                 // - it's disabled
5578                 // - parameter change required
5579                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
5580                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
5581                 if ((periodic_enabled == false) || periodic_parameter_change){
5582                     periodic_advertising_stop = true;
5583                     advertising_stop_set = advertising_set;
5584                 }
5585             }
5586 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5587         }
5588     }
5589 #endif
5590 
5591 #endif
5592 
5593 
5594     // Phase 2: stop everything that should be off during modifications
5595 
5596 
5597     // 2.1 Outgoing connection
5598 #ifdef ENABLE_LE_CENTRAL
5599     if (connecting_stop){
5600         hci_send_cmd(&hci_le_create_connection_cancel);
5601         return true;
5602     }
5603 #endif
5604 
5605     // 2.2 Scanning
5606 #ifdef ENABLE_LE_CENTRAL
5607     if (scanning_stop){
5608         hci_stack->le_scanning_active = false;
5609         hci_le_scan_stop();
5610         return true;
5611     }
5612 
5613     // 2.3 Periodic Sync
5614 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5615     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
5616         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
5617         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
5618         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
5619         return true;
5620     }
5621 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5622     if (periodic_sync_stop){
5623         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
5624         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
5625         return true;
5626     }
5627 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5628 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5629 #endif /* ENABLE_LE_CENTRAL */
5630 
5631     // 2.4 Advertising: legacy, extended, periodic
5632 #ifdef ENABLE_LE_PERIPHERAL
5633     if (advertising_stop){
5634 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5635         if (hci_extended_advertising_supported()) {
5636             uint8_t advertising_stop_handle;
5637             if (advertising_stop_set != NULL){
5638                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5639                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5640             } else {
5641                 advertising_stop_handle = 0;
5642                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5643             }
5644             const uint8_t advertising_handles[] = { advertising_stop_handle };
5645             const uint16_t durations[] = { 0 };
5646             const uint16_t max_events[] = { 0 };
5647             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5648         } else
5649 #endif
5650         {
5651             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5652             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5653         }
5654         return true;
5655     }
5656 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5657 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5658     if (periodic_advertising_stop){
5659         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5660         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
5661         return true;
5662     }
5663 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5664 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5665 #endif /* ENABLE_LE_PERIPHERAL */
5666 
5667 
5668     // Phase 3: modify
5669 
5670     if (random_address_change){
5671         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5672 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5673         if (hci_extended_advertising_supported()) {
5674             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5675         }
5676 #endif
5677         {
5678             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5679         }
5680         return true;
5681     }
5682 
5683 #ifdef ENABLE_LE_CENTRAL
5684     if (hci_stack->le_scanning_param_update){
5685         hci_stack->le_scanning_param_update = false;
5686 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5687         if (hci_extended_advertising_supported()){
5688             // prepare arrays for all PHYs
5689             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
5690             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
5691             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
5692             uint8_t  scanning_phys     = 1;  // LE 1M PHY
5693             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
5694                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
5695         } else
5696 #endif
5697         {
5698             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5699                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
5700         }
5701         return true;
5702     }
5703 #endif
5704 
5705 #ifdef ENABLE_LE_PERIPHERAL
5706     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
5707         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5708         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5709 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5710         if (hci_extended_advertising_supported()){
5711             // map advertisment type to advertising event properties
5712             uint16_t adv_event_properties = 0;
5713             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5714             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5715                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5716             }
5717             hci_stack->le_advertising_set_in_current_command = 0;
5718             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5719                          0,
5720                          adv_event_properties,
5721                          hci_stack->le_advertisements_interval_min,
5722                          hci_stack->le_advertisements_interval_max,
5723                          hci_stack->le_advertisements_channel_map,
5724                          hci_stack->le_advertisements_own_addr_type,
5725                          hci_stack->le_advertisements_direct_address_type,
5726                          hci_stack->le_advertisements_direct_address,
5727                          hci_stack->le_advertisements_filter_policy,
5728                          0x7f,  // tx power: no preference
5729                          0x01,  // primary adv phy: LE 1M
5730                          0,     // secondary adv max skip
5731                          0,     // secondary adv phy
5732                          0,     // adv sid
5733                          0      // scan request notification
5734                          );
5735         }
5736 #endif
5737         {
5738             hci_send_cmd(&hci_le_set_advertising_parameters,
5739                          hci_stack->le_advertisements_interval_min,
5740                          hci_stack->le_advertisements_interval_max,
5741                          hci_stack->le_advertisements_type,
5742                          hci_stack->le_advertisements_own_addr_type,
5743                          hci_stack->le_advertisements_direct_address_type,
5744                          hci_stack->le_advertisements_direct_address,
5745                          hci_stack->le_advertisements_channel_map,
5746                          hci_stack->le_advertisements_filter_policy);
5747         }
5748         return true;
5749     }
5750 
5751     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
5752         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5753         uint8_t adv_data_clean[31];
5754         memset(adv_data_clean, 0, sizeof(adv_data_clean));
5755         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
5756                      hci_stack->le_advertisements_data_len);
5757         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
5758 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5759         if (hci_extended_advertising_supported()){
5760             hci_stack->le_advertising_set_in_current_command = 0;
5761             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
5762         } else
5763 #endif
5764         {
5765             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
5766         }
5767         return true;
5768     }
5769 
5770     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
5771         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5772         uint8_t scan_data_clean[31];
5773         memset(scan_data_clean, 0, sizeof(scan_data_clean));
5774         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
5775                      hci_stack->le_scan_response_data_len);
5776         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
5777 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5778         if (hci_extended_advertising_supported()){
5779             hci_stack->le_advertising_set_in_current_command = 0;
5780             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
5781         } else
5782 #endif
5783         {
5784             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
5785         }
5786         return true;
5787     }
5788 
5789 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5790     if (hci_extended_advertising_supported()) {
5791         btstack_linked_list_iterator_t it;
5792         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5793         while (btstack_linked_list_iterator_has_next(&it)){
5794             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5795             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
5796                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
5797                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5798                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
5799                 return true;
5800             }
5801             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
5802                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5803                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
5804                 return true;
5805             }
5806             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
5807                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5808                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5809                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5810                              advertising_set->advertising_handle,
5811                              advertising_set->extended_params.advertising_event_properties,
5812                              advertising_set->extended_params.primary_advertising_interval_min,
5813                              advertising_set->extended_params.primary_advertising_interval_max,
5814                              advertising_set->extended_params.primary_advertising_channel_map,
5815                              advertising_set->extended_params.own_address_type,
5816                              advertising_set->extended_params.peer_address_type,
5817                              advertising_set->extended_params.peer_address,
5818                              advertising_set->extended_params.advertising_filter_policy,
5819                              advertising_set->extended_params.advertising_tx_power,
5820                              advertising_set->extended_params.primary_advertising_phy,
5821                              advertising_set->extended_params.secondary_advertising_max_skip,
5822                              advertising_set->extended_params.secondary_advertising_phy,
5823                              advertising_set->extended_params.advertising_sid,
5824                              advertising_set->extended_params.scan_request_notification_enable
5825                 );
5826                 return true;
5827             }
5828             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
5829                 uint16_t pos = advertising_set->adv_data_pos;
5830                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
5831                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5832                 if ((operation & 0x02) != 0){
5833                     // last fragment or complete data
5834                     operation |= 2;
5835                     advertising_set->adv_data_pos = 0;
5836                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5837                 } else {
5838                     advertising_set->adv_data_pos += data_to_upload;
5839                 }
5840                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5841                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
5842                 return true;
5843             }
5844             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
5845                 uint16_t pos = advertising_set->scan_data_pos;
5846                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
5847                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5848                 if ((operation & 0x02) != 0){
5849                     advertising_set->scan_data_pos = 0;
5850                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5851                 } else {
5852                     advertising_set->scan_data_pos += data_to_upload;
5853                 }
5854                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5855                 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
5856                 return true;
5857             }
5858 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5859             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
5860                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
5861                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5862                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
5863                              advertising_set->advertising_handle,
5864                              advertising_set->periodic_params.periodic_advertising_interval_min,
5865                              advertising_set->periodic_params.periodic_advertising_interval_max,
5866                              advertising_set->periodic_params.periodic_advertising_properties);
5867                 return true;
5868             }
5869             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
5870                 uint16_t pos = advertising_set->periodic_data_pos;
5871                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
5872                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5873                 if ((operation & 0x02) != 0){
5874                     // last fragment or complete data
5875                     operation |= 2;
5876                     advertising_set->periodic_data_pos = 0;
5877                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
5878                 } else {
5879                     advertising_set->periodic_data_pos += data_to_upload;
5880                 }
5881                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5882                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
5883                 return true;
5884             }
5885 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5886         }
5887     }
5888 #endif
5889 
5890 #endif
5891 
5892 #ifdef ENABLE_LE_CENTRAL
5893     // if connect with whitelist was active and is not cancelled yet, wait until next time
5894     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
5895 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5896     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
5897     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
5898 #endif
5899 #endif
5900 
5901     // LE Whitelist Management
5902     if (whitelist_modification_pending){
5903         // add/remove entries
5904         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5905         while (btstack_linked_list_iterator_has_next(&lit)){
5906             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5907 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5908 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5909 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
5910 				return true;
5911 			}
5912             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
5913 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
5914                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
5915                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
5916                 return true;
5917             }
5918             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
5919 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5920 				btstack_memory_whitelist_entry_free(entry);
5921             }
5922         }
5923     }
5924 
5925 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5926     // LE Resolving List Management
5927     if (resolving_list_supported) {
5928 		uint16_t i;
5929 		switch (hci_stack->le_resolving_list_state) {
5930 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
5931 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
5932 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
5933 				return true;
5934 			case LE_RESOLVING_LIST_READ_SIZE:
5935 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
5936 				hci_send_cmd(&hci_le_read_resolving_list_size);
5937 				return true;
5938 			case LE_RESOLVING_LIST_SEND_CLEAR:
5939 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
5940 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
5941 							  sizeof(hci_stack->le_resolving_list_add_entries));
5942 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
5943 							  sizeof(hci_stack->le_resolving_list_remove_entries));
5944 				hci_send_cmd(&hci_le_clear_resolving_list);
5945 				return true;
5946 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
5947 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5948 					uint8_t offset = i >> 3;
5949 					uint8_t mask = 1 << (i & 7);
5950 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
5951 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
5952 					bd_addr_t peer_identity_addreses;
5953 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5954 					sm_key_t peer_irk;
5955 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5956 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5957 
5958 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
5959 					// trigger whitelist entry 'update' (work around for controller bug)
5960 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5961 					while (btstack_linked_list_iterator_has_next(&lit)) {
5962 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
5963 						if (entry->address_type != peer_identity_addr_type) continue;
5964 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
5965 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
5966 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
5967 					}
5968 #endif
5969 
5970 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
5971 								 peer_identity_addreses);
5972 					return true;
5973 				}
5974 
5975 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
5976 
5977 				/* fall through */
5978 
5979 			case LE_RESOLVING_LIST_ADD_ENTRIES:
5980 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
5981 					uint8_t offset = i >> 3;
5982 					uint8_t mask = 1 << (i & 7);
5983 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
5984 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
5985 					bd_addr_t peer_identity_addreses;
5986 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
5987 					sm_key_t peer_irk;
5988 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
5989 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5990                     if (btstack_is_null(peer_irk, 16)) continue;
5991 					const uint8_t *local_irk = gap_get_persistent_irk();
5992 					// command uses format specifier 'P' that stores 16-byte value without flip
5993 					uint8_t local_irk_flipped[16];
5994 					uint8_t peer_irk_flipped[16];
5995 					reverse_128(local_irk, local_irk_flipped);
5996 					reverse_128(peer_irk, peer_irk_flipped);
5997 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
5998 								 peer_irk_flipped, local_irk_flipped);
5999 					return true;
6000 				}
6001 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6002 				break;
6003 
6004 			default:
6005 				break;
6006 		}
6007 	}
6008     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
6009 #endif
6010 
6011 #ifdef ENABLE_LE_CENTRAL
6012 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6013     // LE Whitelist Management
6014     if (periodic_list_modification_pending){
6015         // add/remove entries
6016         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6017         while (btstack_linked_list_iterator_has_next(&lit)){
6018             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6019             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6020                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6021                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
6022                 return true;
6023             }
6024             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6025                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6026                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
6027                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6028                 return true;
6029             }
6030             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6031                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6032                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6033             }
6034         }
6035     }
6036 #endif
6037 #endif
6038 
6039     // post-pone all actions until stack is fully working
6040     if (hci_stack->state != HCI_STATE_WORKING) return false;
6041 
6042     // advertisements, active scanning, and creating connections requires random address to be set if using private address
6043     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
6044 
6045     // Phase 4: restore state
6046 
6047 #ifdef ENABLE_LE_CENTRAL
6048     // re-start scanning
6049     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
6050         hci_stack->le_scanning_active = true;
6051 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6052         if (hci_extended_advertising_supported()){
6053             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0);
6054         } else
6055 #endif
6056         {
6057             hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
6058         }
6059         return true;
6060     }
6061 #endif
6062 
6063 #ifdef ENABLE_LE_CENTRAL
6064     // re-start connecting
6065     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
6066         bd_addr_t null_addr;
6067         memset(null_addr, 0, 6);
6068         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6069         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6070         hci_send_cmd(&hci_le_create_connection,
6071                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
6072                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
6073                      1,         // use whitelist
6074                      0,         // peer address type
6075                      null_addr, // peer bd addr
6076                      hci_stack->le_connection_own_addr_type,   // our addr type:
6077                      hci_stack->le_connection_interval_min,    // conn interval min
6078                      hci_stack->le_connection_interval_max,    // conn interval max
6079                      hci_stack->le_connection_latency,         // conn latency
6080                      hci_stack->le_supervision_timeout,        // conn latency
6081                      hci_stack->le_minimum_ce_length,          // min ce length
6082                      hci_stack->le_maximum_ce_length           // max ce length
6083         );
6084         return true;
6085     }
6086 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6087     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
6088         switch(hci_stack->le_periodic_sync_request){
6089             case LE_CONNECTING_DIRECT:
6090             case LE_CONNECTING_WHITELIST:
6091                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
6092                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
6093                              hci_stack->le_periodic_sync_options,
6094                              hci_stack->le_periodic_sync_advertising_sid,
6095                              hci_stack->le_periodic_sync_advertiser_address_type,
6096                              hci_stack->le_periodic_sync_advertiser_address,
6097                              hci_stack->le_periodic_sync_skip,
6098                              hci_stack->le_periodic_sync_timeout,
6099                              hci_stack->le_periodic_sync_cte_type);
6100                 return true;
6101             default:
6102                 break;
6103         }
6104     }
6105 #endif
6106 #endif
6107 
6108 #ifdef ENABLE_LE_PERIPHERAL
6109     // re-start advertising
6110     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6111         // check if advertisements should be enabled given
6112         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6113         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6114 
6115 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6116         if (hci_extended_advertising_supported()){
6117             const uint8_t advertising_handles[] = { 0 };
6118             const uint16_t durations[] = { 0 };
6119             const uint16_t max_events[] = { 0 };
6120             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6121         } else
6122 #endif
6123         {
6124             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6125         }
6126         return true;
6127     }
6128 
6129 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6130     if (hci_extended_advertising_supported()) {
6131         btstack_linked_list_iterator_t it;
6132         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6133         while (btstack_linked_list_iterator_has_next(&it)) {
6134             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6135             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6136                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6137                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6138                 const uint16_t durations[] = { advertising_set->enable_timeout };
6139                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6140                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6141                 return true;
6142             }
6143 #ifdef ENABLE_LE_PERIODIC_ADVERTISING
6144             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
6145                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
6146                 uint8_t enable = 1;
6147                 if (advertising_set->periodic_include_adi){
6148                     enable |= 2;
6149                 }
6150                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
6151                 return true;
6152             }
6153 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6154         }
6155     }
6156 #endif
6157 #endif
6158 
6159     return false;
6160 }
6161 
6162 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6163 static bool hci_run_iso_tasks(void){
6164     btstack_linked_list_iterator_t it;
6165 
6166     // BIG
6167     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
6168     while (btstack_linked_list_iterator_has_next(&it)){
6169         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
6170         switch (big->state){
6171             case LE_AUDIO_BIG_STATE_CREATE:
6172                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6173                 hci_send_cmd(&hci_le_create_big,
6174                              big->params->big_handle,
6175                              big->params->advertising_handle,
6176                              big->params->num_bis,
6177                              big->params->sdu_interval_us,
6178                              big->params->max_sdu,
6179                              big->params->max_transport_latency_ms,
6180                              big->params->rtn,
6181                              big->params->phy,
6182                              big->params->packing,
6183                              big->params->framing,
6184                              big->params->encryption,
6185                              big->params->broadcast_code);
6186                 return true;
6187             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6188                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6189                 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);
6190                 return true;
6191             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6192                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6193                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6194                 return true;
6195             case LE_AUDIO_BIG_STATE_TERMINATE:
6196                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6197                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
6198                 return true;
6199             default:
6200                 break;
6201         }
6202     }
6203 
6204     // BIG Sync
6205     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
6206     while (btstack_linked_list_iterator_has_next(&it)){
6207         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
6208         switch (big_sync->state){
6209             case LE_AUDIO_BIG_STATE_CREATE:
6210                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
6211                 hci_send_cmd(&hci_le_big_create_sync,
6212                              big_sync->params->big_handle,
6213                              big_sync->params->sync_handle,
6214                              big_sync->params->encryption,
6215                              big_sync->params->broadcast_code,
6216                              big_sync->params->mse,
6217                              big_sync->params->big_sync_timeout_10ms,
6218                              big_sync->params->num_bis,
6219                              big_sync->params->bis_indices);
6220                 return true;
6221             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
6222                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
6223                 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);
6224                 return true;
6225             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
6226                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
6227                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6228                 return true;
6229             case LE_AUDIO_BIG_STATE_TERMINATE:
6230                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
6231                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6232                 return true;
6233             default:
6234                 break;
6235         }
6236     }
6237 
6238     return false;
6239 }
6240 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6241 #endif
6242 
6243 static bool hci_run_general_pending_commands(void){
6244     btstack_linked_item_t * it;
6245     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
6246         hci_connection_t * connection = (hci_connection_t *) it;
6247 
6248         switch(connection->state){
6249             case SEND_CREATE_CONNECTION:
6250                 switch(connection->address_type){
6251 #ifdef ENABLE_CLASSIC
6252                     case BD_ADDR_TYPE_ACL:
6253                         log_info("sending hci_create_connection");
6254                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
6255                         break;
6256 #endif
6257                     default:
6258 #ifdef ENABLE_BLE
6259 #ifdef ENABLE_LE_CENTRAL
6260                         log_info("sending hci_le_create_connection");
6261                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
6262                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6263 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6264                         if (hci_extended_advertising_supported()) {
6265                             uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval };
6266                             uint16_t le_connection_scan_window[1]   = { hci_stack->le_connection_scan_window };
6267                             uint16_t le_connection_interval_min[1]  = { hci_stack->le_connection_interval_min };
6268                             uint16_t le_connection_interval_max[1]  = { hci_stack->le_connection_interval_max };
6269                             uint16_t le_connection_latency[1]       = { hci_stack->le_connection_latency };
6270                             uint16_t le_supervision_timeout[1]      = { hci_stack->le_supervision_timeout };
6271                             uint16_t le_minimum_ce_length[1]        = { hci_stack->le_minimum_ce_length };
6272                             uint16_t le_maximum_ce_length[1]        = { hci_stack->le_maximum_ce_length };
6273                             hci_send_cmd(&hci_le_extended_create_connection,
6274                                          0,         // don't use whitelist
6275                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6276                                          connection->address_type,      // peer address type
6277                                          connection->address,           // peer bd addr
6278                                          1,                             // initiating PHY - 1M
6279                                          le_connection_scan_interval,   // conn scan interval
6280                                          le_connection_scan_window,     // conn scan windows
6281                                          le_connection_interval_min,    // conn interval min
6282                                          le_connection_interval_max,    // conn interval max
6283                                          le_connection_latency,         // conn latency
6284                                          le_supervision_timeout,        // conn latency
6285                                          le_minimum_ce_length,          // min ce length
6286                                          le_maximum_ce_length           // max ce length
6287                             );                        }
6288                         else
6289 #endif
6290                         {
6291                             hci_send_cmd(&hci_le_create_connection,
6292                                          hci_stack->le_connection_scan_interval,    // conn scan interval
6293                                          hci_stack->le_connection_scan_window,      // conn scan windows
6294                                          0,         // don't use whitelist
6295                                          connection->address_type, // peer address type
6296                                          connection->address,      // peer bd addr
6297                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6298                                          hci_stack->le_connection_interval_min,    // conn interval min
6299                                          hci_stack->le_connection_interval_max,    // conn interval max
6300                                          hci_stack->le_connection_latency,         // conn latency
6301                                          hci_stack->le_supervision_timeout,        // conn latency
6302                                          hci_stack->le_minimum_ce_length,          // min ce length
6303                                          hci_stack->le_maximum_ce_length          // max ce length
6304                             );
6305                         }
6306                         connection->state = SENT_CREATE_CONNECTION;
6307 #endif
6308 #endif
6309                         break;
6310                 }
6311                 return true;
6312 
6313 #ifdef ENABLE_CLASSIC
6314             case RECEIVED_CONNECTION_REQUEST:
6315                 connection->role  = HCI_ROLE_SLAVE;
6316                 if (connection->address_type == BD_ADDR_TYPE_ACL){
6317                     log_info("sending hci_accept_connection_request");
6318                     connection->state = ACCEPTED_CONNECTION_REQUEST;
6319                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
6320                     return true;
6321                 }
6322                 break;
6323 #endif
6324 
6325 #ifdef ENABLE_BLE
6326 #ifdef ENABLE_LE_CENTRAL
6327             case SEND_CANCEL_CONNECTION:
6328                 connection->state = SENT_CANCEL_CONNECTION;
6329                 hci_send_cmd(&hci_le_create_connection_cancel);
6330                 return true;
6331 #endif
6332 #endif
6333             case SEND_DISCONNECT:
6334                 connection->state = SENT_DISCONNECT;
6335                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6336                 return true;
6337 
6338             default:
6339                 break;
6340         }
6341 
6342         // no further commands if connection is about to get shut down
6343         if (connection->state == SENT_DISCONNECT) continue;
6344 
6345 #ifdef ENABLE_CLASSIC
6346 
6347         // Handling link key request requires remote supported features
6348         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
6349             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
6350             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
6351 
6352             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
6353             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
6354             if (have_link_key && security_level_sufficient){
6355                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
6356             } else {
6357                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
6358             }
6359             return true;
6360         }
6361 
6362         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
6363             log_info("denying to pin request");
6364             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
6365             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
6366             return true;
6367         }
6368 
6369         // security assessment requires remote features
6370         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
6371             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
6372             hci_ssp_assess_security_on_io_cap_request(connection);
6373             // 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
6374         }
6375 
6376         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
6377             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6378             // set authentication requirements:
6379             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
6380             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
6381             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
6382             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
6383                 authreq |= 1;
6384             }
6385             bool bonding = hci_stack->bondable;
6386             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
6387                 // if we have received IO Cap Response, we're in responder role
6388                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6389                 if (bonding && !remote_bonding){
6390                     log_info("Remote not bonding, dropping local flag");
6391                     bonding = false;
6392                 }
6393             }
6394             if (bonding){
6395                 if (connection->bonding_flags & BONDING_DEDICATED){
6396                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6397                 } else {
6398                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
6399                 }
6400             }
6401             uint8_t have_oob_data = 0;
6402 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6403             if (connection->classic_oob_c_192 != NULL){
6404                     have_oob_data |= 1;
6405             }
6406             if (connection->classic_oob_c_256 != NULL){
6407                 have_oob_data |= 2;
6408             }
6409 #endif
6410             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
6411             return true;
6412         }
6413 
6414         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
6415             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6416             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
6417             return true;
6418         }
6419 
6420 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6421         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
6422             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
6423             const uint8_t zero[16] = { 0 };
6424             const uint8_t * r_192 = zero;
6425             const uint8_t * c_192 = zero;
6426             const uint8_t * r_256 = zero;
6427             const uint8_t * c_256 = zero;
6428             // verify P-256 OOB
6429             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
6430                 c_256 = connection->classic_oob_c_256;
6431                 if (connection->classic_oob_r_256 != NULL) {
6432                     r_256 = connection->classic_oob_r_256;
6433                 }
6434             }
6435             // verify P-192 OOB
6436             if ((connection->classic_oob_c_192 != NULL)) {
6437                 c_192 = connection->classic_oob_c_192;
6438                 if (connection->classic_oob_r_192 != NULL) {
6439                     r_192 = connection->classic_oob_r_192;
6440                 }
6441             }
6442 
6443             // assess security
6444             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
6445             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
6446             if (need_level_4 && !can_reach_level_4){
6447                 log_info("Level 4 required, but not possible -> abort");
6448                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
6449                 // send oob negative reply
6450                 c_256 = NULL;
6451                 c_192 = NULL;
6452             }
6453 
6454             // Reply
6455             if (c_256 != zero) {
6456                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
6457             } else if (c_192 != zero){
6458                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
6459             } else {
6460                 hci_stack->classic_oob_con_handle = connection->con_handle;
6461                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
6462             }
6463             return true;
6464         }
6465 #endif
6466 
6467         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
6468             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
6469             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
6470             return true;
6471         }
6472 
6473         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
6474             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
6475             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
6476             return true;
6477         }
6478 
6479         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
6480             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
6481             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
6482             return true;
6483         }
6484 
6485         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
6486             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
6487             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
6488             connection->state = SENT_DISCONNECT;
6489             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6490             return true;
6491         }
6492 
6493         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
6494             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
6495             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
6496             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
6497             return true;
6498         }
6499 
6500         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
6501             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
6502             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
6503             return true;
6504         }
6505 
6506         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
6507             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
6508             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
6509             return true;
6510         }
6511 
6512         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
6513             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6514             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
6515             return true;
6516         }
6517 
6518         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
6519             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
6520             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
6521             return true;
6522         }
6523 
6524         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
6525             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
6526             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
6527             return true;
6528         }
6529 #endif
6530 
6531         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
6532             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
6533 #ifdef ENABLE_CLASSIC
6534             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
6535 #endif
6536             if (connection->state != SENT_DISCONNECT){
6537                 connection->state = SENT_DISCONNECT;
6538                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
6539                 return true;
6540             }
6541         }
6542 
6543 #ifdef ENABLE_CLASSIC
6544         uint16_t sniff_min_interval;
6545         switch (connection->sniff_min_interval){
6546             case 0:
6547                 break;
6548             case 0xffff:
6549                 connection->sniff_min_interval = 0;
6550                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
6551                 return true;
6552             default:
6553                 sniff_min_interval = connection->sniff_min_interval;
6554                 connection->sniff_min_interval = 0;
6555                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
6556                 return true;
6557         }
6558 
6559         if (connection->sniff_subrating_max_latency != 0xffff){
6560             uint16_t max_latency = connection->sniff_subrating_max_latency;
6561             connection->sniff_subrating_max_latency = 0;
6562             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
6563             return true;
6564         }
6565 
6566         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
6567             uint8_t service_type = (uint8_t) connection->qos_service_type;
6568             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
6569             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);
6570             return true;
6571         }
6572 
6573         if (connection->request_role != HCI_ROLE_INVALID){
6574             hci_role_t role = connection->request_role;
6575             connection->request_role = HCI_ROLE_INVALID;
6576             hci_send_cmd(&hci_switch_role_command, connection->address, role);
6577             return true;
6578         }
6579 #endif
6580 
6581         if (connection->gap_connection_tasks != 0){
6582 #ifdef ENABLE_CLASSIC
6583             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
6584                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
6585                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
6586                 return true;
6587             }
6588             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
6589                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
6590                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
6591                 return true;
6592             }
6593 #endif
6594             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
6595                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
6596                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
6597                 return true;
6598             }
6599         }
6600 
6601 #ifdef ENABLE_BLE
6602         switch (connection->le_con_parameter_update_state){
6603             // response to L2CAP CON PARAMETER UPDATE REQUEST
6604             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
6605                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6606                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
6607                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6608                              0x0000, 0xffff);
6609                 return true;
6610             case CON_PARAMETER_UPDATE_REPLY:
6611                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6612                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
6613                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6614                              0x0000, 0xffff);
6615                 return true;
6616             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
6617                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
6618                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
6619                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
6620                 return true;
6621             default:
6622                 break;
6623         }
6624         if (connection->le_phy_update_all_phys != 0xffu){
6625             uint8_t all_phys = connection->le_phy_update_all_phys;
6626             connection->le_phy_update_all_phys = 0xff;
6627             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);
6628             return true;
6629         }
6630 #endif
6631     }
6632     return false;
6633 }
6634 
6635 static void hci_run(void){
6636 
6637     // stack state sub statemachines
6638     switch (hci_stack->state) {
6639         case HCI_STATE_INITIALIZING:
6640             hci_initializing_run();
6641             break;
6642         case HCI_STATE_HALTING:
6643             hci_halting_run();
6644             break;
6645         case HCI_STATE_FALLING_ASLEEP:
6646             hci_falling_asleep_run();
6647             break;
6648         default:
6649             break;
6650     }
6651 
6652     // allow to run after initialization to working transition
6653     if (hci_stack->state != HCI_STATE_WORKING){
6654         return;
6655     }
6656 
6657     bool done;
6658 
6659     // send continuation fragments first, as they block the prepared packet buffer
6660     done = hci_run_acl_fragments();
6661     if (done) return;
6662 
6663 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6664     done = hci_run_iso_fragments();
6665     if (done) return;
6666 #endif
6667 
6668 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
6669     // send host num completed packets next as they don't require num_cmd_packets > 0
6670     if (!hci_can_send_comand_packet_transport()) return;
6671     if (hci_stack->host_completed_packets){
6672         hci_host_num_completed_packets();
6673         return;
6674     }
6675 #endif
6676 
6677     if (!hci_can_send_command_packet_now()) return;
6678 
6679     // global/non-connection oriented commands
6680 
6681 
6682 #ifdef ENABLE_CLASSIC
6683     // general gap classic
6684     done = hci_run_general_gap_classic();
6685     if (done) return;
6686 #endif
6687 
6688 #ifdef ENABLE_BLE
6689     // general gap le
6690     done = hci_run_general_gap_le();
6691     if (done) return;
6692 
6693 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6694     // ISO related tasks, e.g. BIG create/terminate/sync
6695     done = hci_run_iso_tasks();
6696     if (done) return;
6697 #endif
6698 #endif
6699 
6700     // send pending HCI commands
6701     hci_run_general_pending_commands();
6702 }
6703 
6704 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
6705     // house-keeping
6706 
6707 #ifdef ENABLE_CLASSIC
6708     bd_addr_t addr;
6709     hci_connection_t * conn;
6710 #endif
6711 #ifdef ENABLE_LE_CENTRAL
6712     uint8_t initiator_filter_policy;
6713 #endif
6714 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6715     uint8_t i;
6716     uint8_t num_cis;
6717     hci_con_handle_t cis_handle;
6718     uint8_t status;
6719 #endif
6720 
6721     uint16_t opcode = little_endian_read_16(packet, 0);
6722     switch (opcode) {
6723         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
6724             hci_stack->loopback_mode = packet[3];
6725             break;
6726 
6727 #ifdef ENABLE_CLASSIC
6728         case HCI_OPCODE_HCI_CREATE_CONNECTION:
6729             reverse_bd_addr(&packet[3], addr);
6730             log_info("Create_connection to %s", bd_addr_to_str(addr));
6731 
6732             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
6733             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
6734                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
6735                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
6736             }
6737 
6738             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6739             if (!conn) {
6740                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6741                 if (!conn) {
6742                     // notify client that alloc failed
6743                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
6744                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
6745                 }
6746                 conn->state = SEND_CREATE_CONNECTION;
6747                 conn->role  = HCI_ROLE_MASTER;
6748             }
6749 
6750             log_info("conn state %u", conn->state);
6751             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
6752             switch (conn->state) {
6753                 // if connection active exists
6754                 case OPEN:
6755                     // and OPEN, emit connection complete command
6756                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
6757                     // packet not sent to controller
6758                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6759                 case RECEIVED_DISCONNECTION_COMPLETE:
6760                     // create connection triggered in disconnect complete event, let's do it now
6761                     break;
6762                 case SEND_CREATE_CONNECTION:
6763 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
6764                     if (hci_classic_operation_active()){
6765                         return ERROR_CODE_SUCCESS;
6766                     }
6767 #endif
6768                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
6769                     break;
6770                 default:
6771                     // otherwise, just ignore as it is already in the open process
6772                     // packet not sent to controller
6773                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6774             }
6775             conn->state = SENT_CREATE_CONNECTION;
6776 
6777             // track outgoing connection
6778             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
6779             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
6780             break;
6781 
6782 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
6783         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
6784             // setup_synchronous_connection? Voice setting at offset 22
6785             // TODO: compare to current setting if sco connection already active
6786             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
6787             break;
6788         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
6789             // accept_synchronous_connection? Voice setting at offset 18
6790             // TODO: compare to current setting if sco connection already active
6791             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
6792             // track outgoing connection
6793             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
6794             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
6795             break;
6796 #endif
6797 #endif
6798 
6799 #ifdef ENABLE_BLE
6800 #ifdef ENABLE_LE_CENTRAL
6801         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
6802             // white list used?
6803             initiator_filter_policy = packet[7];
6804             switch (initiator_filter_policy) {
6805                 case 0:
6806                     // whitelist not used
6807                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
6808                     break;
6809                 case 1:
6810                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
6811                     break;
6812                 default:
6813                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
6814                     break;
6815             }
6816             // track outgoing connection
6817             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
6818             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
6819             break;
6820         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
6821             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
6822             break;
6823 #endif
6824 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
6825 #ifdef ENABLE_LE_CENTRAL
6826         case HCI_OPCODE_HCI_LE_CREATE_CIS:
6827             status = ERROR_CODE_SUCCESS;
6828             num_cis = packet[3];
6829             // setup hci_iso_streams
6830             for (i=0;i<num_cis;i++){
6831                 cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 4 + (4 * i));
6832                 status = hci_iso_stream_create(cis_handle, 0xff);
6833                 if (status != ERROR_CODE_SUCCESS) {
6834                     break;
6835                 }
6836             }
6837             // free structs on error
6838             if (status != ERROR_CODE_SUCCESS){
6839                 hci_iso_stream_requested_finalize(0xff);
6840                 return status;
6841             }
6842             break;
6843 #endif /* ENABLE_LE_CENTRAL */
6844 #ifdef ENABLE_LE_PERIPHERAL
6845         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
6846             cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 3);
6847             status = hci_iso_stream_create(cis_handle, 0xff);
6848             if (status != ERROR_CODE_SUCCESS){
6849                 return status;
6850             }
6851             break;
6852 #endif /* ENABLE_LE_PERIPHERAL */
6853 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6854 #endif /* ENABLE_BLE */
6855         default:
6856             break;
6857     }
6858 
6859     hci_stack->num_cmd_packets--;
6860 
6861     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
6862     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
6863     if (err != 0){
6864         return ERROR_CODE_HARDWARE_FAILURE;
6865     }
6866     return ERROR_CODE_SUCCESS;
6867 }
6868 
6869 // disconnect because of security block
6870 void hci_disconnect_security_block(hci_con_handle_t con_handle){
6871     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6872     if (!connection) return;
6873     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
6874 }
6875 
6876 
6877 // Configure Secure Simple Pairing
6878 
6879 #ifdef ENABLE_CLASSIC
6880 
6881 // enable will enable SSP during init
6882 void gap_ssp_set_enable(int enable){
6883     hci_stack->ssp_enable = enable;
6884 }
6885 
6886 static int hci_local_ssp_activated(void){
6887     return gap_ssp_supported() && hci_stack->ssp_enable;
6888 }
6889 
6890 // if set, BTstack will respond to io capability request using authentication requirement
6891 void gap_ssp_set_io_capability(int io_capability){
6892     hci_stack->ssp_io_capability = io_capability;
6893 }
6894 void gap_ssp_set_authentication_requirement(int authentication_requirement){
6895     hci_stack->ssp_authentication_requirement = authentication_requirement;
6896 }
6897 
6898 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
6899 void gap_ssp_set_auto_accept(int auto_accept){
6900     hci_stack->ssp_auto_accept = auto_accept;
6901 }
6902 
6903 void gap_secure_connections_enable(bool enable){
6904     hci_stack->secure_connections_enable = enable;
6905 }
6906 bool gap_secure_connections_active(void){
6907     return hci_stack->secure_connections_active;
6908 }
6909 
6910 #endif
6911 
6912 // va_list part of hci_send_cmd
6913 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
6914     if (!hci_can_send_command_packet_now()){
6915         log_error("hci_send_cmd called but cannot send packet now");
6916         return ERROR_CODE_COMMAND_DISALLOWED;
6917     }
6918 
6919     // for HCI INITIALIZATION
6920     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
6921     hci_stack->last_cmd_opcode = cmd->opcode;
6922 
6923     hci_reserve_packet_buffer();
6924     uint8_t * packet = hci_stack->hci_packet_buffer;
6925     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
6926     uint8_t status = hci_send_cmd_packet(packet, size);
6927 
6928     // release packet buffer on error or for synchronous transport implementations
6929     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
6930         hci_release_packet_buffer();
6931         hci_emit_transport_packet_sent();
6932     }
6933 
6934     return status;
6935 }
6936 
6937 /**
6938  * pre: numcmds >= 0 - it's allowed to send a command to the controller
6939  */
6940 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
6941     va_list argptr;
6942     va_start(argptr, cmd);
6943     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
6944     va_end(argptr);
6945     return status;
6946 }
6947 
6948 // Create various non-HCI events.
6949 // TODO: generalize, use table similar to hci_create_command
6950 
6951 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
6952     // dump packet
6953     if (dump) {
6954         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
6955     }
6956 
6957     // dispatch to all event handlers
6958     btstack_linked_list_iterator_t it;
6959     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
6960     while (btstack_linked_list_iterator_has_next(&it)){
6961         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
6962         entry->callback(HCI_EVENT_PACKET, 0, event, size);
6963     }
6964 }
6965 
6966 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
6967     if (!hci_stack->acl_packet_handler) return;
6968     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
6969 }
6970 
6971 #ifdef ENABLE_CLASSIC
6972 static void hci_notify_if_sco_can_send_now(void){
6973     // notify SCO sender if waiting
6974     if (!hci_stack->sco_waiting_for_can_send_now) return;
6975     if (hci_can_send_sco_packet_now()){
6976         hci_stack->sco_waiting_for_can_send_now = 0;
6977         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
6978         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
6979         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
6980     }
6981 }
6982 
6983 // parsing end emitting has been merged to reduce code size
6984 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
6985     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
6986 
6987     uint8_t * eir_data;
6988     ad_context_t context;
6989     const uint8_t * name;
6990     uint8_t         name_len;
6991 
6992     if (size < 3) return;
6993 
6994     int event_type = hci_event_packet_get_type(packet);
6995     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
6996     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
6997 
6998     switch (event_type){
6999         case HCI_EVENT_INQUIRY_RESULT:
7000         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7001             if (size != (3 + (num_responses * 14))) return;
7002             break;
7003         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7004             if (size != 257) return;
7005             if (num_responses != 1) return;
7006             break;
7007         default:
7008             return;
7009     }
7010 
7011     // event[1] is set at the end
7012     int i;
7013     for (i=0; i<num_responses;i++){
7014         memset(event, 0, sizeof(event));
7015         event[0] = GAP_EVENT_INQUIRY_RESULT;
7016         uint8_t event_size = 27;    // if name is not set by EIR
7017 
7018         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
7019         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
7020         (void)memcpy(&event[9],
7021                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
7022                      3); // class of device
7023         (void)memcpy(&event[12],
7024                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
7025                      2); // clock offset
7026 
7027         switch (event_type){
7028             case HCI_EVENT_INQUIRY_RESULT:
7029                 // 14,15,16,17 = 0, size 18
7030                 break;
7031             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
7032                 event[14] = 1;
7033                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7034                 // 16,17 = 0, size 18
7035                 break;
7036             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
7037                 event[14] = 1;
7038                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
7039                 // EIR packets only contain a single inquiry response
7040                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
7041                 name = NULL;
7042                 // Iterate over EIR data
7043                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
7044                     uint8_t data_type    = ad_iterator_get_data_type(&context);
7045                     uint8_t data_size    = ad_iterator_get_data_len(&context);
7046                     const uint8_t * data = ad_iterator_get_data(&context);
7047                     // Prefer Complete Local Name over Shortened Local Name
7048                     switch (data_type){
7049                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
7050                             if (name) continue;
7051                             /* fall through */
7052                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
7053                             name = data;
7054                             name_len = data_size;
7055                             break;
7056                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
7057                             if (data_size != 8) break;
7058                             event[16] = 1;
7059                             memcpy(&event[17], data, 8);
7060                             break;
7061                         default:
7062                             break;
7063                     }
7064                 }
7065                 if (name){
7066                     event[25] = 1;
7067                     // truncate name if needed
7068                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
7069                     event[26] = len;
7070                     (void)memcpy(&event[27], name, len);
7071                     event_size += len;
7072                 }
7073                 break;
7074             default:
7075                 return;
7076         }
7077         event[1] = event_size - 2;
7078         hci_emit_event(event, event_size, 1);
7079     }
7080 }
7081 #endif
7082 
7083 void hci_emit_state(void){
7084     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
7085     uint8_t event[3];
7086     event[0] = BTSTACK_EVENT_STATE;
7087     event[1] = sizeof(event) - 2u;
7088     event[2] = hci_stack->state;
7089     hci_emit_event(event, sizeof(event), 1);
7090 }
7091 
7092 #ifdef ENABLE_CLASSIC
7093 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
7094     uint8_t event[13];
7095     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
7096     event[1] = sizeof(event) - 2;
7097     event[2] = status;
7098     little_endian_store_16(event, 3, con_handle);
7099     reverse_bd_addr(address, &event[5]);
7100     event[11] = 1; // ACL connection
7101     event[12] = 0; // encryption disabled
7102     hci_emit_event(event, sizeof(event), 1);
7103 }
7104 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
7105     if (disable_l2cap_timeouts) return;
7106     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
7107     uint8_t event[4];
7108     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
7109     event[1] = sizeof(event) - 2;
7110     little_endian_store_16(event, 2, conn->con_handle);
7111     hci_emit_event(event, sizeof(event), 1);
7112 }
7113 #endif
7114 
7115 #ifdef ENABLE_BLE
7116 #ifdef ENABLE_LE_CENTRAL
7117 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){
7118     uint8_t event[21];
7119     event[0] = HCI_EVENT_LE_META;
7120     event[1] = sizeof(event) - 2u;
7121     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
7122     event[3] = status;
7123     little_endian_store_16(event, 4, con_handle);
7124     event[6] = 0; // TODO: role
7125     event[7] = address_type;
7126     reverse_bd_addr(address, &event[8]);
7127     little_endian_store_16(event, 14, 0); // interval
7128     little_endian_store_16(event, 16, 0); // latency
7129     little_endian_store_16(event, 18, 0); // supervision timeout
7130     event[20] = 0; // master clock accuracy
7131     hci_emit_event(event, sizeof(event), 1);
7132 }
7133 #endif
7134 #endif
7135 
7136 static void hci_emit_transport_packet_sent(void){
7137     // notify upper stack that it might be possible to send again
7138     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
7139     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
7140 }
7141 
7142 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
7143     uint8_t event[6];
7144     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
7145     event[1] = sizeof(event) - 2u;
7146     event[2] = 0; // status = OK
7147     little_endian_store_16(event, 3, con_handle);
7148     event[5] = reason;
7149     hci_emit_event(event, sizeof(event), 1);
7150 }
7151 
7152 static void hci_emit_nr_connections_changed(void){
7153     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
7154     uint8_t event[3];
7155     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
7156     event[1] = sizeof(event) - 2u;
7157     event[2] = nr_hci_connections();
7158     hci_emit_event(event, sizeof(event), 1);
7159 }
7160 
7161 static void hci_emit_hci_open_failed(void){
7162     log_info("BTSTACK_EVENT_POWERON_FAILED");
7163     uint8_t event[2];
7164     event[0] = BTSTACK_EVENT_POWERON_FAILED;
7165     event[1] = sizeof(event) - 2u;
7166     hci_emit_event(event, sizeof(event), 1);
7167 }
7168 
7169 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
7170     log_info("hci_emit_dedicated_bonding_result %u ", status);
7171     uint8_t event[9];
7172     int pos = 0;
7173     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
7174     event[pos++] = sizeof(event) - 2u;
7175     event[pos++] = status;
7176     reverse_bd_addr(address, &event[pos]);
7177     hci_emit_event(event, sizeof(event), 1);
7178 }
7179 
7180 
7181 #ifdef ENABLE_CLASSIC
7182 
7183 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
7184     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
7185     uint8_t event[5];
7186     int pos = 0;
7187     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
7188     event[pos++] = sizeof(event) - 2;
7189     little_endian_store_16(event, 2, con_handle);
7190     pos += 2;
7191     event[pos++] = level;
7192     hci_emit_event(event, sizeof(event), 1);
7193 }
7194 
7195 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
7196     if (!connection) return LEVEL_0;
7197     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
7198     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
7199     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
7200     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
7201     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
7202     // LEVEL 4 always requires 128 bit encrytion key size
7203     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
7204         security_level = LEVEL_3;
7205     }
7206     return security_level;
7207 }
7208 
7209 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
7210     uint8_t event[4];
7211     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
7212     event[1] = sizeof(event) - 2;
7213     event[2] = discoverable;
7214     event[3] = connectable;
7215     hci_emit_event(event, sizeof(event), 1);
7216 }
7217 
7218 // query if remote side supports eSCO
7219 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
7220     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7221     if (!connection) return false;
7222     return (connection->remote_supported_features[0] & 1) != 0;
7223 }
7224 
7225 static bool hci_ssp_supported(hci_connection_t * connection){
7226     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
7227     return (connection->bonding_flags & mask) == mask;
7228 }
7229 
7230 // query if remote side supports SSP
7231 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
7232     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7233     if (!connection) return false;
7234     return hci_ssp_supported(connection) ? 1 : 0;
7235 }
7236 
7237 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
7238     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
7239 }
7240 
7241 /**
7242  * Check if remote supported features query has completed
7243  */
7244 bool hci_remote_features_available(hci_con_handle_t handle){
7245     hci_connection_t * connection = hci_connection_for_handle(handle);
7246     if (!connection) return false;
7247     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
7248 }
7249 
7250 /**
7251  * Trigger remote supported features query
7252  */
7253 
7254 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
7255     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
7256         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7257     }
7258 }
7259 
7260 void hci_remote_features_query(hci_con_handle_t con_handle){
7261     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7262     if (!connection) return;
7263     hci_trigger_remote_features_for_connection(connection);
7264     hci_run();
7265 }
7266 
7267 // GAP API
7268 /**
7269  * @bbrief enable/disable bonding. default is enabled
7270  * @praram enabled
7271  */
7272 void gap_set_bondable_mode(int enable){
7273     hci_stack->bondable = enable ? 1 : 0;
7274 }
7275 /**
7276  * @brief Get bondable mode.
7277  * @return 1 if bondable
7278  */
7279 int gap_get_bondable_mode(void){
7280     return hci_stack->bondable;
7281 }
7282 
7283 /**
7284  * @brief map link keys to security levels
7285  */
7286 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
7287     switch (link_key_type){
7288         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7289             return LEVEL_4;
7290         case COMBINATION_KEY:
7291         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7292             return LEVEL_3;
7293         default:
7294             return LEVEL_2;
7295     }
7296 }
7297 
7298 /**
7299  * @brief map link keys to secure connection yes/no
7300  */
7301 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
7302     switch (link_key_type){
7303         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7304         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7305             return true;
7306         default:
7307             return false;
7308     }
7309 }
7310 
7311 /**
7312  * @brief map link keys to authenticated
7313  */
7314 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
7315     switch (link_key_type){
7316         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
7317         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
7318             return true;
7319         default:
7320             return false;
7321     }
7322 }
7323 
7324 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
7325     log_info("gap_mitm_protection_required_for_security_level %u", level);
7326     return level > LEVEL_2;
7327 }
7328 
7329 /**
7330  * @brief get current security level
7331  */
7332 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
7333     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7334     if (!connection) return LEVEL_0;
7335     return gap_security_level_for_connection(connection);
7336 }
7337 
7338 /**
7339  * @brief request connection to device to
7340  * @result GAP_AUTHENTICATION_RESULT
7341  */
7342 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
7343     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7344     if (!connection){
7345         hci_emit_security_level(con_handle, LEVEL_0);
7346         return;
7347     }
7348 
7349     btstack_assert(hci_is_le_connection(connection) == false);
7350 
7351     // 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)
7352     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
7353     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
7354         requested_level = LEVEL_4;
7355     }
7356 
7357     gap_security_level_t current_level = gap_security_level(con_handle);
7358     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
7359         requested_level, connection->requested_security_level, current_level);
7360 
7361     // authentication active if authentication request was sent or planned level > 0
7362     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
7363     if (authentication_active){
7364         // authentication already active
7365         if (connection->requested_security_level < requested_level){
7366             // increase requested level as new level is higher
7367             // TODO: handle re-authentication when done
7368             connection->requested_security_level = requested_level;
7369         }
7370     } else {
7371         // no request active, notify if security sufficient
7372         if (requested_level <= current_level){
7373             hci_emit_security_level(con_handle, current_level);
7374             return;
7375         }
7376 
7377         // store request
7378         connection->requested_security_level = requested_level;
7379 
7380         // start to authenticate connection
7381         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
7382 
7383         // request remote features if not already active, also trigger hci_run
7384         hci_remote_features_query(con_handle);
7385     }
7386 }
7387 
7388 /**
7389  * @brief start dedicated bonding with device. disconnect after bonding
7390  * @param device
7391  * @param request MITM protection
7392  * @result GAP_DEDICATED_BONDING_COMPLETE
7393  */
7394 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
7395 
7396     // create connection state machine
7397     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
7398 
7399     if (!connection){
7400         return BTSTACK_MEMORY_ALLOC_FAILED;
7401     }
7402 
7403     // delete linkn key
7404     gap_drop_link_key_for_bd_addr(device);
7405 
7406     // configure LEVEL_2/3, dedicated bonding
7407     connection->state = SEND_CREATE_CONNECTION;
7408     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
7409     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
7410     connection->bonding_flags = BONDING_DEDICATED;
7411 
7412     // wait for GAP Security Result and send GAP Dedicated Bonding complete
7413 
7414     // handle: connnection failure (connection complete != ok)
7415     // handle: authentication failure
7416     // handle: disconnect on done
7417 
7418     hci_run();
7419 
7420     return 0;
7421 }
7422 
7423 void gap_set_local_name(const char * local_name){
7424     hci_stack->local_name = local_name;
7425     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
7426     // also update EIR if not set by user
7427     if (hci_stack->eir_data == NULL){
7428         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
7429     }
7430     hci_run();
7431 }
7432 #endif
7433 
7434 
7435 #ifdef ENABLE_BLE
7436 
7437 #ifdef ENABLE_LE_CENTRAL
7438 void gap_start_scan(void){
7439     hci_stack->le_scanning_enabled = true;
7440     hci_run();
7441 }
7442 
7443 void gap_stop_scan(void){
7444     hci_stack->le_scanning_enabled = false;
7445     hci_run();
7446 }
7447 
7448 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
7449     hci_stack->le_scan_type          = scan_type;
7450     hci_stack->le_scan_filter_policy = scanning_filter_policy;
7451     hci_stack->le_scan_interval      = scan_interval;
7452     hci_stack->le_scan_window        = scan_window;
7453     hci_stack->le_scanning_param_update = true;
7454     hci_run();
7455 }
7456 
7457 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
7458     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
7459 }
7460 
7461 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
7462     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
7463     if (!conn){
7464         // disallow if le connection is already outgoing
7465         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7466             log_error("le connection already active");
7467             return ERROR_CODE_COMMAND_DISALLOWED;
7468         }
7469 
7470         log_info("gap_connect: no connection exists yet, creating context");
7471         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
7472         if (!conn){
7473             // notify client that alloc failed
7474             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7475             log_info("gap_connect: failed to alloc hci_connection_t");
7476             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
7477         }
7478 
7479         // set le connecting state
7480         if (hci_is_le_connection_type(addr_type)){
7481             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
7482         }
7483 
7484         conn->state = SEND_CREATE_CONNECTION;
7485         log_info("gap_connect: send create connection next");
7486         hci_run();
7487         return ERROR_CODE_SUCCESS;
7488     }
7489 
7490     if (!hci_is_le_connection(conn) ||
7491         (conn->state == SEND_CREATE_CONNECTION) ||
7492         (conn->state == SENT_CREATE_CONNECTION)) {
7493         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
7494         log_error("gap_connect: classic connection or connect is already being created");
7495         return GATT_CLIENT_IN_WRONG_STATE;
7496     }
7497 
7498     // check if connection was just disconnected
7499     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7500         log_info("gap_connect: send create connection (again)");
7501         conn->state = SEND_CREATE_CONNECTION;
7502         hci_run();
7503         return ERROR_CODE_SUCCESS;
7504     }
7505 
7506     log_info("gap_connect: context exists with state %u", conn->state);
7507     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
7508     hci_run();
7509     return ERROR_CODE_SUCCESS;
7510 }
7511 
7512 // @assumption: only a single outgoing LE Connection exists
7513 static hci_connection_t * gap_get_outgoing_connection(void){
7514     btstack_linked_item_t *it;
7515     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
7516         hci_connection_t * conn = (hci_connection_t *) it;
7517         if (!hci_is_le_connection(conn)) continue;
7518         switch (conn->state){
7519             case SEND_CREATE_CONNECTION:
7520             case SENT_CREATE_CONNECTION:
7521             case SENT_CANCEL_CONNECTION:
7522                 return conn;
7523             default:
7524                 break;
7525         };
7526     }
7527     return NULL;
7528 }
7529 
7530 uint8_t gap_connect_cancel(void){
7531     hci_connection_t * conn;
7532     switch (hci_stack->le_connecting_request){
7533         case LE_CONNECTING_IDLE:
7534             break;
7535         case LE_CONNECTING_WHITELIST:
7536             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7537             hci_run();
7538             break;
7539         case LE_CONNECTING_DIRECT:
7540             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
7541             conn = gap_get_outgoing_connection();
7542             if (conn == NULL){
7543                 hci_run();
7544             } else {
7545                 switch (conn->state){
7546                     case SEND_CREATE_CONNECTION:
7547                         // skip sending create connection and emit event instead
7548                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
7549                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
7550                         btstack_memory_hci_connection_free( conn );
7551                         break;
7552                     case SENT_CREATE_CONNECTION:
7553                         // request to send cancel connection
7554                         conn->state = SEND_CANCEL_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         if (big->can_send_now_requested){
9142             // check if no outgoing iso packets pending and no can send now have to be emitted
9143             uint8_t i;
9144             bool can_send = true;
9145             for (i=0;i<big->num_bis;i++){
9146                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9147                 if ((iso_stream == NULL) || (iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
9148                     can_send = false;
9149                     break;
9150                 }
9151             }
9152             if (can_send){
9153                 // propagate can send now to individual streams
9154                 big->can_send_now_requested = false;
9155                 for (i=0;i<big->num_bis;i++){
9156                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9157                     iso_stream->emit_ready_to_send = true;
9158                 }
9159             }
9160         }
9161     }
9162 
9163     if (hci_stack->hci_packet_buffer_reserved) return;
9164 
9165     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
9166     while (btstack_linked_list_iterator_has_next(&it)){
9167         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
9168         // report bis ready
9169         uint8_t i;
9170         for (i=0;i<big->num_bis;i++){
9171             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
9172             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
9173                 iso_stream->emit_ready_to_send = false;
9174                 hci_emit_bis_can_send_now(big, i);
9175                 break;
9176             }
9177         }
9178     }
9179 }
9180 
9181 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
9182     if (hci_big_for_handle(big_params->big_handle) != NULL){
9183         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9184     }
9185     if (big_params->num_bis == 0){
9186         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9187     }
9188     if (big_params->num_bis > MAX_NR_BIS){
9189         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9190     }
9191 
9192     // reserve ISO Streams
9193     uint8_t i;
9194     uint8_t status = ERROR_CODE_SUCCESS;
9195     for (i=0;i<big_params->num_bis;i++){
9196         status = hci_iso_stream_create(HCI_CON_HANDLE_INVALID, big_params->big_handle);
9197         if (status != ERROR_CODE_SUCCESS) {
9198             break;
9199         }
9200     }
9201 
9202     // free structs on error
9203     if (status != ERROR_CODE_SUCCESS){
9204         hci_iso_stream_requested_finalize(big_params->big_handle);
9205         return status;
9206     }
9207 
9208     le_audio_big_t * big = storage;
9209     big->big_handle = big_params->big_handle;
9210     big->params = big_params;
9211     big->state = LE_AUDIO_BIG_STATE_CREATE;
9212     big->num_bis = big_params->num_bis;
9213     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9214 
9215     hci_run();
9216 
9217     return ERROR_CODE_SUCCESS;
9218 }
9219 
9220 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
9221     if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){
9222         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
9223     }
9224     if (big_sync_params->num_bis == 0){
9225         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9226     }
9227     if (big_sync_params->num_bis > MAX_NR_BIS){
9228         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9229     }
9230 
9231     le_audio_big_sync_t * big_sync = storage;
9232     big_sync->big_handle = big_sync_params->big_handle;
9233     big_sync->params = big_sync_params;
9234     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
9235     big_sync->num_bis = big_sync_params->num_bis;
9236     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9237 
9238     hci_run();
9239 
9240     return ERROR_CODE_SUCCESS;
9241 }
9242 
9243 uint8_t gap_big_terminate(uint8_t big_handle){
9244     le_audio_big_t * big = hci_big_for_handle(big_handle);
9245     if (big == NULL){
9246         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9247     }
9248     switch (big->state){
9249         case LE_AUDIO_BIG_STATE_CREATE:
9250             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
9251             hci_emit_big_terminated(big);
9252             break;
9253         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9254             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9255             break;
9256         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9257         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9258         case LE_AUDIO_BIG_STATE_ACTIVE:
9259             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
9260             hci_run();
9261             break;
9262         default:
9263             return ERROR_CODE_COMMAND_DISALLOWED;
9264     }
9265     return ERROR_CODE_SUCCESS;
9266 }
9267 
9268 uint8_t gap_big_sync_terminate(uint8_t big_handle){
9269     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
9270     if (big_sync == NULL){
9271         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9272     }
9273     switch (big_sync->state){
9274         case LE_AUDIO_BIG_STATE_CREATE:
9275             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
9276             hci_emit_big_sync_stopped(big_sync);
9277             break;
9278         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
9279             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
9280             break;
9281         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
9282         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
9283         case LE_AUDIO_BIG_STATE_ACTIVE:
9284             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
9285             hci_run();
9286             break;
9287         default:
9288             return ERROR_CODE_COMMAND_DISALLOWED;
9289     }
9290     return ERROR_CODE_SUCCESS;
9291 }
9292 
9293 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
9294     le_audio_big_t * big = hci_big_for_handle(big_handle);
9295     if (big == NULL){
9296         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9297     }
9298     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
9299         return ERROR_CODE_COMMAND_DISALLOWED;
9300     }
9301     big->can_send_now_requested = true;
9302     hci_iso_notify_can_send_now();
9303     return ERROR_CODE_SUCCESS;
9304 }
9305 #endif
9306 #endif /* ENABLE_BLE */
9307 
9308 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
9309 void hci_setup_test_connections_fuzz(void){
9310     hci_connection_t * conn;
9311 
9312     // default address: 66:55:44:33:00:01
9313     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
9314 
9315     // setup Controller info
9316     hci_stack->num_cmd_packets = 255;
9317     hci_stack->acl_packets_total_num = 255;
9318 
9319     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
9320     addr[5] = 0x01;
9321     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9322     conn->con_handle = addr[5];
9323     conn->role  = HCI_ROLE_SLAVE;
9324     conn->state = RECEIVED_CONNECTION_REQUEST;
9325     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9326 
9327     // setup incoming Classic SCO connection with con handle 0x0002
9328     addr[5] = 0x02;
9329     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9330     conn->con_handle = addr[5];
9331     conn->role  = HCI_ROLE_SLAVE;
9332     conn->state = RECEIVED_CONNECTION_REQUEST;
9333     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9334 
9335     // setup ready Classic ACL connection with con handle 0x0003
9336     addr[5] = 0x03;
9337     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9338     conn->con_handle = addr[5];
9339     conn->role  = HCI_ROLE_SLAVE;
9340     conn->state = OPEN;
9341     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9342 
9343     // setup ready Classic SCO connection with con handle 0x0004
9344     addr[5] = 0x04;
9345     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
9346     conn->con_handle = addr[5];
9347     conn->role  = HCI_ROLE_SLAVE;
9348     conn->state = OPEN;
9349     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9350 
9351     // setup ready LE ACL connection with con handle 0x005 and public address
9352     addr[5] = 0x05;
9353     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
9354     conn->con_handle = addr[5];
9355     conn->role  = HCI_ROLE_SLAVE;
9356     conn->state = OPEN;
9357     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
9358     conn->sm_connection.sm_connection_encrypted = 1;
9359 }
9360 
9361 void hci_free_connections_fuzz(void){
9362     btstack_linked_list_iterator_t it;
9363     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9364     while (btstack_linked_list_iterator_has_next(&it)){
9365         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9366         btstack_linked_list_iterator_remove(&it);
9367         btstack_memory_hci_connection_free(con);
9368     }
9369 }
9370 void hci_simulate_working_fuzz(void){
9371     hci_stack->le_scanning_param_update = false;
9372     hci_init_done();
9373     hci_stack->num_cmd_packets = 255;
9374 }
9375 #endif
9376