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