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