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