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