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