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