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