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