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