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