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