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