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