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