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