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