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