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