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