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