xref: /btstack/src/hci.c (revision aee5d5c18b988b2ede1a8016b67098c530f58fc6)
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             // mark connection for shutdown, stop timers
3074             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3075             hci_connection_stop_timer(conn);
3076 
3077             // emit dedicatd bonding event
3078             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3079                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3080             }
3081 
3082 #ifdef ENABLE_BLE
3083 #ifdef ENABLE_LE_PERIPHERAL
3084             // re-enable advertisements for le connections if active
3085             if (hci_is_le_connection(conn)){
3086                 hci_update_advertisements_enabled_for_current_roles();
3087             }
3088 #endif
3089 #endif
3090             break;
3091 
3092         case HCI_EVENT_HARDWARE_ERROR:
3093             log_error("Hardware Error: 0x%02x", packet[2]);
3094             if (hci_stack->hardware_error_callback){
3095                 (*hci_stack->hardware_error_callback)(packet[2]);
3096             } else {
3097                 // if no special requests, just reboot stack
3098                 hci_power_control_off();
3099                 hci_power_control_on();
3100             }
3101             break;
3102 
3103 #ifdef ENABLE_CLASSIC
3104         case HCI_EVENT_ROLE_CHANGE:
3105             if (packet[2]) break;   // status != 0
3106             reverse_bd_addr(&packet[3], addr);
3107             addr_type = BD_ADDR_TYPE_ACL;
3108             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3109             if (!conn) break;
3110             conn->role = packet[9];
3111             break;
3112 #endif
3113 
3114         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3115             // release packet buffer only for asynchronous transport and if there are not further fragements
3116             if (hci_transport_synchronous()) {
3117                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
3118                 return; // instead of break: to avoid re-entering hci_run()
3119             }
3120             hci_stack->acl_fragmentation_tx_active = 0;
3121             if (hci_stack->acl_fragmentation_total_size) break;
3122             hci_release_packet_buffer();
3123 
3124             // L2CAP receives this event via the hci_emit_event below
3125 
3126 #ifdef ENABLE_CLASSIC
3127             // For SCO, we do the can_send_now_check here
3128             hci_notify_if_sco_can_send_now();
3129 #endif
3130             break;
3131 
3132 #ifdef ENABLE_CLASSIC
3133         case HCI_EVENT_SCO_CAN_SEND_NOW:
3134             // For SCO, we do the can_send_now_check here
3135             hci_stack->sco_can_send_now = true;
3136             hci_notify_if_sco_can_send_now();
3137             return;
3138 
3139         // explode inquriy results for easier consumption
3140         case HCI_EVENT_INQUIRY_RESULT:
3141         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3142         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3143             gap_inquiry_explode(packet, size);
3144             break;
3145 #endif
3146 
3147 #ifdef ENABLE_BLE
3148         case HCI_EVENT_LE_META:
3149             switch (packet[2]){
3150 #ifdef ENABLE_LE_CENTRAL
3151                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
3152                     // log_info("advertising report received");
3153                     if (!hci_stack->le_scanning_enabled) break;
3154                     le_handle_advertisement_report(packet, size);
3155                     break;
3156 #endif
3157                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3158 					event_handle_le_connection_complete(packet);
3159                     break;
3160 
3161                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3162                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3163                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3164                     conn = hci_connection_for_handle(handle);
3165                     if (!conn) break;
3166                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3167                     break;
3168 
3169                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
3170                     // connection
3171                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
3172                     conn = hci_connection_for_handle(handle);
3173                     if (conn) {
3174                         // read arguments
3175                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
3176                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
3177                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
3178                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
3179 
3180                         // validate against current connection parameter range
3181                         le_connection_parameter_range_t existing_range;
3182                         gap_get_connection_parameter_range(&existing_range);
3183                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3184                         if (update_parameter){
3185                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
3186                             conn->le_conn_interval_min = le_conn_interval_min;
3187                             conn->le_conn_interval_max = le_conn_interval_max;
3188                             conn->le_conn_latency = le_conn_latency;
3189                             conn->le_supervision_timeout = le_supervision_timeout;
3190                         } else {
3191                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
3192                         }
3193                     }
3194                     break;
3195 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3196                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
3197                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
3198                     conn = hci_connection_for_handle(handle);
3199                     if (conn) {
3200                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
3201                     }
3202                     break;
3203 #endif
3204                 default:
3205                     break;
3206             }
3207             break;
3208 #endif
3209         case HCI_EVENT_VENDOR_SPECIFIC:
3210             // Vendor specific commands often create vendor specific event instead of num completed packets
3211             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
3212             switch (hci_stack->manufacturer){
3213                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
3214                     hci_stack->num_cmd_packets = 1;
3215                     break;
3216                 default:
3217                     break;
3218             }
3219             break;
3220         default:
3221             break;
3222     }
3223 
3224     handle_event_for_current_stack_state(packet, size);
3225 
3226     // notify upper stack
3227 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
3228 
3229     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
3230     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
3231 		handle = little_endian_read_16(packet, 3);
3232 		hci_connection_t * aConn = hci_connection_for_handle(handle);
3233 		// discard connection if app did not trigger a reconnect in the event handler
3234 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
3235 			hci_shutdown_connection(aConn);
3236 		}
3237     }
3238 
3239 	// execute main loop
3240 	hci_run();
3241 }
3242 
3243 #ifdef ENABLE_CLASSIC
3244 
3245 #ifdef ENABLE_SCO_OVER_HCI
3246 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
3247 static void sco_schedule_tx(hci_connection_t * conn);
3248 
3249 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
3250     log_debug("SCO TX Timeout");
3251     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
3252     hci_connection_t * conn = hci_connection_for_handle(con_handle);
3253     if (!conn) return;
3254 
3255     // trigger send
3256     conn->sco_tx_ready = 1;
3257     // extra packet if CVSD but SCO buffer is too short
3258     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
3259         conn->sco_tx_ready++;
3260     }
3261     hci_notify_if_sco_can_send_now();
3262 }
3263 
3264 
3265 #define SCO_TX_AFTER_RX_MS (6)
3266 
3267 static void sco_schedule_tx(hci_connection_t * conn){
3268 
3269     uint32_t now = btstack_run_loop_get_time_ms();
3270     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
3271     int time_delta_ms = sco_tx_ms - now;
3272 
3273     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
3274 
3275     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
3276     btstack_run_loop_remove_timer(timer);
3277     btstack_run_loop_set_timer(timer, time_delta_ms);
3278     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
3279     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
3280     btstack_run_loop_add_timer(timer);
3281 }
3282 #endif
3283 
3284 static void sco_handler(uint8_t * packet, uint16_t size){
3285     // lookup connection struct
3286     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
3287     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
3288     if (!conn) return;
3289 
3290 #ifdef ENABLE_SCO_OVER_HCI
3291     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
3292     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
3293         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
3294             packet[2] = 0x3c;
3295             memmove(&packet[3], &packet[23], 63);
3296             size = 63;
3297         }
3298     }
3299 
3300     if (hci_have_usb_transport()){
3301         // Nothing to do
3302     } else {
3303         // 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);
3304         if (hci_stack->synchronous_flow_control_enabled == 0){
3305             uint32_t now = btstack_run_loop_get_time_ms();
3306 
3307             if (!conn->sco_rx_valid){
3308                 // ignore first 10 packets
3309                 conn->sco_rx_count++;
3310                 // log_debug("sco rx count %u", conn->sco_rx_count);
3311                 if (conn->sco_rx_count == 10) {
3312                     // use first timestamp as is and pretent it just started
3313                     conn->sco_rx_ms = now;
3314                     conn->sco_rx_valid = 1;
3315                     conn->sco_rx_count = 0;
3316                     sco_schedule_tx(conn);
3317                 }
3318             } else {
3319                 // track expected arrival timme
3320                 conn->sco_rx_count++;
3321                 conn->sco_rx_ms += 7;
3322                 int delta = (int32_t) (now - conn->sco_rx_ms);
3323                 if (delta > 0){
3324                     conn->sco_rx_ms++;
3325                 }
3326                 // log_debug("sco rx %u", conn->sco_rx_ms);
3327                 sco_schedule_tx(conn);
3328             }
3329         }
3330     }
3331 #endif
3332 
3333     // deliver to app
3334     if (hci_stack->sco_packet_handler) {
3335         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
3336     }
3337 
3338 #ifdef HAVE_SCO_TRANSPORT
3339     // We can send one packet for each received packet
3340     conn->sco_tx_ready++;
3341     hci_notify_if_sco_can_send_now();
3342 #endif
3343 
3344 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3345     conn->num_packets_completed++;
3346     hci_stack->host_completed_packets = 1;
3347     hci_run();
3348 #endif
3349 }
3350 #endif
3351 
3352 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
3353     hci_dump_packet(packet_type, 1, packet, size);
3354     switch (packet_type) {
3355         case HCI_EVENT_PACKET:
3356             event_handler(packet, size);
3357             break;
3358         case HCI_ACL_DATA_PACKET:
3359             acl_handler(packet, size);
3360             break;
3361 #ifdef ENABLE_CLASSIC
3362         case HCI_SCO_DATA_PACKET:
3363             sco_handler(packet, size);
3364             break;
3365 #endif
3366         default:
3367             break;
3368     }
3369 }
3370 
3371 /**
3372  * @brief Add event packet handler.
3373  */
3374 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3375     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3376 }
3377 
3378 
3379 /** Register HCI packet handlers */
3380 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3381     hci_stack->acl_packet_handler = handler;
3382 }
3383 
3384 #ifdef ENABLE_CLASSIC
3385 /**
3386  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
3387  */
3388 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
3389     hci_stack->sco_packet_handler = handler;
3390 }
3391 #endif
3392 
3393 static void hci_state_reset(void){
3394     // no connections yet
3395     hci_stack->connections = NULL;
3396 
3397     // keep discoverable/connectable as this has been requested by the client(s)
3398     // hci_stack->discoverable = 0;
3399     // hci_stack->connectable = 0;
3400     // hci_stack->bondable = 1;
3401     // hci_stack->own_addr_type = 0;
3402 
3403     // buffer is free
3404     hci_stack->hci_packet_buffer_reserved = false;
3405 
3406     // no pending cmds
3407     hci_stack->decline_reason = 0;
3408     hci_stack->new_scan_enable_value = 0xff;
3409 
3410     hci_stack->secure_connections_active = false;
3411 
3412 #ifdef ENABLE_CLASSIC
3413     hci_stack->new_page_scan_interval = 0xffff;
3414     hci_stack->new_page_scan_window = 0xffff;
3415     hci_stack->new_page_scan_type = 0xff;
3416     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
3417     hci_stack->gap_tasks =
3418             GAP_TASK_SET_DEFAULT_LINK_POLICY |
3419             GAP_TASK_SET_CLASS_OF_DEVICE |
3420             GAP_TASK_SET_LOCAL_NAME |
3421             GAP_TASK_SET_EIR_DATA;
3422 #endif
3423 
3424 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3425     hci_stack->classic_read_local_oob_data = true;
3426     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
3427 #endif
3428 
3429     // LE
3430 #ifdef ENABLE_BLE
3431     memset(hci_stack->le_random_address, 0, 6);
3432     hci_stack->le_random_address_set = 0;
3433 #endif
3434 #ifdef ENABLE_LE_CENTRAL
3435     hci_stack->le_scanning_active  = false;
3436     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3437     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3438     hci_stack->le_whitelist_capacity = 0;
3439 #endif
3440 #ifdef ENABLE_LE_PERIPHERAL
3441     hci_stack->le_advertisements_active = false;
3442     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PARAMS_SET) != 0){
3443         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3444     }
3445     if (hci_stack->le_advertisements_data != NULL){
3446         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3447     }
3448 #endif
3449 }
3450 
3451 #ifdef ENABLE_CLASSIC
3452 /**
3453  * @brief Configure Bluetooth hardware control. Has to be called before power on.
3454  */
3455 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
3456     // store and open remote device db
3457     hci_stack->link_key_db = link_key_db;
3458     if (hci_stack->link_key_db) {
3459         hci_stack->link_key_db->open();
3460     }
3461 }
3462 #endif
3463 
3464 void hci_init(const hci_transport_t *transport, const void *config){
3465 
3466 #ifdef HAVE_MALLOC
3467     if (!hci_stack) {
3468         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
3469     }
3470 #else
3471     hci_stack = &hci_stack_static;
3472 #endif
3473     memset(hci_stack, 0, sizeof(hci_stack_t));
3474 
3475     // reference to use transport layer implementation
3476     hci_stack->hci_transport = transport;
3477 
3478     // reference to used config
3479     hci_stack->config = config;
3480 
3481     // setup pointer for outgoing packet buffer
3482     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
3483 
3484     // max acl payload size defined in config.h
3485     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
3486 
3487     // register packet handlers with transport
3488     transport->register_packet_handler(&packet_handler);
3489 
3490     hci_stack->state = HCI_STATE_OFF;
3491 
3492     // class of device
3493     hci_stack->class_of_device = 0x007a020c; // Smartphone
3494 
3495     // bondable by default
3496     hci_stack->bondable = 1;
3497 
3498 #ifdef ENABLE_CLASSIC
3499     // classic name
3500     hci_stack->local_name = default_classic_name;
3501 
3502     // Master slave policy
3503     hci_stack->master_slave_policy = 1;
3504 
3505     // Allow Role Switch
3506     hci_stack->allow_role_switch = 1;
3507 
3508     // Default / minimum security level = 2
3509     hci_stack->gap_security_level = LEVEL_2;
3510 
3511     // Default Security Mode 4
3512     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
3513 
3514     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3515     hci_stack->gap_required_encyrption_key_size = 7;
3516 
3517     // Link Supervision Timeout
3518     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
3519 
3520 #endif
3521 
3522     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
3523     hci_stack->ssp_enable = 1;
3524     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
3525     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
3526     hci_stack->ssp_auto_accept = 1;
3527 
3528     // Secure Connections: enable (requires support from Controller)
3529     hci_stack->secure_connections_enable = true;
3530 
3531     // voice setting - signed 16 bit pcm data with CVSD over the air
3532     hci_stack->sco_voice_setting = 0x60;
3533 
3534 #ifdef ENABLE_LE_CENTRAL
3535     // connection parameter to use for outgoing connections
3536     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3537     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3538     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3539     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3540     hci_stack->le_connection_latency      = 4;         // 4
3541     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3542     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3543     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
3544 
3545     // default LE Scanning
3546     hci_stack->le_scan_type     =   0x1; // active
3547     hci_stack->le_scan_interval = 0x1e0; // 300 ms
3548     hci_stack->le_scan_window   =  0x30; //  30 ms
3549 #endif
3550 
3551 #ifdef ENABLE_LE_PERIPHERAL
3552     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
3553 #endif
3554 
3555     // connection parameter range used to answer connection parameter update requests in l2cap
3556     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3557     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3558     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3559     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3560     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3561     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3562 
3563     hci_state_reset();
3564 }
3565 
3566 void hci_deinit(void){
3567 #ifdef HAVE_MALLOC
3568     if (hci_stack) {
3569         free(hci_stack);
3570     }
3571 #endif
3572     hci_stack = NULL;
3573 
3574 #ifdef ENABLE_CLASSIC
3575     disable_l2cap_timeouts = 0;
3576 #endif
3577 }
3578 
3579 /**
3580  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
3581  */
3582 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
3583     hci_stack->chipset = chipset_driver;
3584 
3585     // reset chipset driver - init is also called on power_up
3586     if (hci_stack->chipset && hci_stack->chipset->init){
3587         hci_stack->chipset->init(hci_stack->config);
3588     }
3589 }
3590 
3591 /**
3592  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3593  */
3594 void hci_set_control(const btstack_control_t *hardware_control){
3595     // references to used control implementation
3596     hci_stack->control = hardware_control;
3597     // init with transport config
3598     hardware_control->init(hci_stack->config);
3599 }
3600 
3601 void hci_close(void){
3602 
3603 #ifdef ENABLE_CLASSIC
3604     // close remote device db
3605     if (hci_stack->link_key_db) {
3606         hci_stack->link_key_db->close();
3607     }
3608 #endif
3609 
3610     btstack_linked_list_iterator_t lit;
3611     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
3612     while (btstack_linked_list_iterator_has_next(&lit)){
3613         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
3614         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
3615         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
3616         hci_shutdown_connection(connection);
3617     }
3618 
3619     hci_power_control(HCI_POWER_OFF);
3620 
3621 #ifdef HAVE_MALLOC
3622     free(hci_stack);
3623 #endif
3624     hci_stack = NULL;
3625 }
3626 
3627 #ifdef HAVE_SCO_TRANSPORT
3628 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3629     hci_stack->sco_transport = sco_transport;
3630     sco_transport->register_packet_handler(&packet_handler);
3631 }
3632 #endif
3633 
3634 #ifdef ENABLE_CLASSIC
3635 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3636     // validate ranage and set
3637     if (encryption_key_size < 7)  return;
3638     if (encryption_key_size > 16) return;
3639     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3640 }
3641 
3642 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
3643     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
3644         hci_stack->gap_security_mode = security_mode;
3645         return ERROR_CODE_SUCCESS;
3646     } else {
3647         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3648     }
3649 }
3650 
3651 gap_security_mode_t gap_get_security_mode(void){
3652     return hci_stack->gap_security_mode;
3653 }
3654 
3655 void gap_set_security_level(gap_security_level_t security_level){
3656     hci_stack->gap_security_level = security_level;
3657 }
3658 
3659 gap_security_level_t gap_get_security_level(void){
3660     if (hci_stack->gap_secure_connections_only_mode){
3661         return LEVEL_4;
3662     }
3663     return hci_stack->gap_security_level;
3664 }
3665 
3666 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
3667     hci_stack->gap_minimal_service_security_level = security_level;
3668 }
3669 
3670 void gap_set_secure_connections_only_mode(bool enable){
3671     hci_stack->gap_secure_connections_only_mode = enable;
3672 }
3673 
3674 bool gap_get_secure_connections_only_mode(void){
3675     return hci_stack->gap_secure_connections_only_mode;
3676 }
3677 #endif
3678 
3679 #ifdef ENABLE_CLASSIC
3680 void gap_set_class_of_device(uint32_t class_of_device){
3681     hci_stack->class_of_device = class_of_device;
3682     hci_stack->gap_tasks |= GAP_TASK_SET_CLASS_OF_DEVICE;
3683     hci_run();
3684 }
3685 
3686 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3687     hci_stack->default_link_policy_settings = default_link_policy_settings;
3688     hci_stack->gap_tasks |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
3689     hci_run();
3690 }
3691 
3692 void gap_set_allow_role_switch(bool allow_role_switch){
3693     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3694 }
3695 
3696 uint8_t hci_get_allow_role_switch(void){
3697     return  hci_stack->allow_role_switch;
3698 }
3699 
3700 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
3701     hci_stack->link_supervision_timeout = link_supervision_timeout;
3702 }
3703 
3704 void hci_disable_l2cap_timeout_check(void){
3705     disable_l2cap_timeouts = 1;
3706 }
3707 #endif
3708 
3709 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
3710 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3711 void hci_set_bd_addr(bd_addr_t addr){
3712     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3713     hci_stack->custom_bd_addr_set = 1;
3714 }
3715 #endif
3716 
3717 // State-Module-Driver overview
3718 // state                    module  low-level
3719 // HCI_STATE_OFF             off      close
3720 // HCI_STATE_INITIALIZING,   on       open
3721 // HCI_STATE_WORKING,        on       open
3722 // HCI_STATE_HALTING,        on       open
3723 // HCI_STATE_SLEEPING,    off/sleep   close
3724 // HCI_STATE_FALLING_ASLEEP  on       open
3725 
3726 static int hci_power_control_on(void){
3727 
3728     // power on
3729     int err = 0;
3730     if (hci_stack->control && hci_stack->control->on){
3731         err = (*hci_stack->control->on)();
3732     }
3733     if (err){
3734         log_error( "POWER_ON failed");
3735         hci_emit_hci_open_failed();
3736         return err;
3737     }
3738 
3739     // int chipset driver
3740     if (hci_stack->chipset && hci_stack->chipset->init){
3741         hci_stack->chipset->init(hci_stack->config);
3742     }
3743 
3744     // init transport
3745     if (hci_stack->hci_transport->init){
3746         hci_stack->hci_transport->init(hci_stack->config);
3747     }
3748 
3749     // open transport
3750     err = hci_stack->hci_transport->open();
3751     if (err){
3752         log_error( "HCI_INIT failed, turning Bluetooth off again");
3753         if (hci_stack->control && hci_stack->control->off){
3754             (*hci_stack->control->off)();
3755         }
3756         hci_emit_hci_open_failed();
3757         return err;
3758     }
3759     return 0;
3760 }
3761 
3762 static void hci_power_control_off(void){
3763 
3764     log_info("hci_power_control_off");
3765 
3766     // close low-level device
3767     hci_stack->hci_transport->close();
3768 
3769     log_info("hci_power_control_off - hci_transport closed");
3770 
3771     // power off
3772     if (hci_stack->control && hci_stack->control->off){
3773         (*hci_stack->control->off)();
3774     }
3775 
3776     log_info("hci_power_control_off - control closed");
3777 
3778     hci_stack->state = HCI_STATE_OFF;
3779 }
3780 
3781 static void hci_power_control_sleep(void){
3782 
3783     log_info("hci_power_control_sleep");
3784 
3785 #if 0
3786     // don't close serial port during sleep
3787 
3788     // close low-level device
3789     hci_stack->hci_transport->close(hci_stack->config);
3790 #endif
3791 
3792     // sleep mode
3793     if (hci_stack->control && hci_stack->control->sleep){
3794         (*hci_stack->control->sleep)();
3795     }
3796 
3797     hci_stack->state = HCI_STATE_SLEEPING;
3798 }
3799 
3800 static int hci_power_control_wake(void){
3801 
3802     log_info("hci_power_control_wake");
3803 
3804     // wake on
3805     if (hci_stack->control && hci_stack->control->wake){
3806         (*hci_stack->control->wake)();
3807     }
3808 
3809 #if 0
3810     // open low-level device
3811     int err = hci_stack->hci_transport->open(hci_stack->config);
3812     if (err){
3813         log_error( "HCI_INIT failed, turning Bluetooth off again");
3814         if (hci_stack->control && hci_stack->control->off){
3815             (*hci_stack->control->off)();
3816         }
3817         hci_emit_hci_open_failed();
3818         return err;
3819     }
3820 #endif
3821 
3822     return 0;
3823 }
3824 
3825 static void hci_power_transition_to_initializing(void){
3826     // set up state machine
3827     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
3828     hci_stack->hci_packet_buffer_reserved = false;
3829     hci_stack->state = HCI_STATE_INITIALIZING;
3830     hci_stack->substate = HCI_INIT_SEND_RESET;
3831 }
3832 
3833 // returns error
3834 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
3835     int err;
3836     switch (power_mode){
3837         case HCI_POWER_ON:
3838             err = hci_power_control_on();
3839             if (err != 0) {
3840                 log_error("hci_power_control_on() error %d", err);
3841                 return err;
3842             }
3843             hci_power_transition_to_initializing();
3844             break;
3845         case HCI_POWER_OFF:
3846             // do nothing
3847             break;
3848         case HCI_POWER_SLEEP:
3849             // do nothing (with SLEEP == OFF)
3850             break;
3851         default:
3852             btstack_assert(false);
3853             break;
3854     }
3855     return ERROR_CODE_SUCCESS;
3856 }
3857 
3858 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
3859     switch (power_mode){
3860         case HCI_POWER_ON:
3861             // do nothing
3862             break;
3863         case HCI_POWER_OFF:
3864             // no connections yet, just turn it off
3865             hci_power_control_off();
3866             break;
3867         case HCI_POWER_SLEEP:
3868             // no connections yet, just turn it off
3869             hci_power_control_sleep();
3870             break;
3871         default:
3872             btstack_assert(false);
3873             break;
3874     }
3875     return ERROR_CODE_SUCCESS;
3876 }
3877 
3878 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
3879     switch (power_mode){
3880         case HCI_POWER_ON:
3881             // do nothing
3882             break;
3883         case HCI_POWER_OFF:
3884             // see hci_run
3885             hci_stack->state = HCI_STATE_HALTING;
3886             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3887             break;
3888         case HCI_POWER_SLEEP:
3889             // see hci_run
3890             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3891             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3892             break;
3893         default:
3894             btstack_assert(false);
3895             break;
3896     }
3897     return ERROR_CODE_SUCCESS;
3898 }
3899 
3900 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
3901     switch (power_mode){
3902         case HCI_POWER_ON:
3903             hci_power_transition_to_initializing();
3904             break;
3905         case HCI_POWER_OFF:
3906             // do nothing
3907             break;
3908         case HCI_POWER_SLEEP:
3909             // see hci_run
3910             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3911             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3912             break;
3913         default:
3914             btstack_assert(false);
3915             break;
3916     }
3917     return ERROR_CODE_SUCCESS;
3918 }
3919 
3920 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
3921     switch (power_mode){
3922         case HCI_POWER_ON:
3923 
3924 #ifdef HAVE_PLATFORM_IPHONE_OS
3925             // nothing to do, if H4 supports power management
3926                     if (btstack_control_iphone_power_management_enabled()){
3927                         hci_stack->state = HCI_STATE_INITIALIZING;
3928                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
3929                         break;
3930                     }
3931 #endif
3932             hci_power_transition_to_initializing();
3933             break;
3934         case HCI_POWER_OFF:
3935             // see hci_run
3936             hci_stack->state = HCI_STATE_HALTING;
3937             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3938             break;
3939         case HCI_POWER_SLEEP:
3940             // do nothing
3941             break;
3942         default:
3943             btstack_assert(false);
3944             break;
3945     }
3946     return ERROR_CODE_SUCCESS;
3947 }
3948 
3949 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
3950     int err;
3951     switch (power_mode){
3952         case HCI_POWER_ON:
3953 #ifdef HAVE_PLATFORM_IPHONE_OS
3954             // nothing to do, if H4 supports power management
3955                     if (btstack_control_iphone_power_management_enabled()){
3956                         hci_stack->state = HCI_STATE_INITIALIZING;
3957                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3958                         hci_update_scan_enable();
3959                         break;
3960                     }
3961 #endif
3962             err = hci_power_control_wake();
3963             if (err) return err;
3964             hci_power_transition_to_initializing();
3965             break;
3966         case HCI_POWER_OFF:
3967             hci_stack->state = HCI_STATE_HALTING;
3968             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3969             break;
3970         case HCI_POWER_SLEEP:
3971             // do nothing
3972             break;
3973         default:
3974             btstack_assert(false);
3975             break;
3976     }
3977     return ERROR_CODE_SUCCESS;
3978 }
3979 
3980 int hci_power_control(HCI_POWER_MODE power_mode){
3981     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
3982     int err = 0;
3983     switch (hci_stack->state){
3984         case HCI_STATE_OFF:
3985             err = hci_power_control_state_off(power_mode);
3986             break;
3987         case HCI_STATE_INITIALIZING:
3988             err = hci_power_control_state_initializing(power_mode);
3989             break;
3990         case HCI_STATE_WORKING:
3991             err = hci_power_control_state_working(power_mode);
3992             break;
3993         case HCI_STATE_HALTING:
3994             err = hci_power_control_state_halting(power_mode);
3995             break;
3996         case HCI_STATE_FALLING_ASLEEP:
3997             err = hci_power_control_state_falling_asleep(power_mode);
3998             break;
3999         case HCI_STATE_SLEEPING:
4000             err = hci_power_control_state_sleeping(power_mode);
4001             break;
4002         default:
4003             btstack_assert(false);
4004             break;
4005     }
4006     if (err != 0){
4007         return err;
4008     }
4009 
4010     // create internal event
4011 	hci_emit_state();
4012 
4013 	// trigger next/first action
4014 	hci_run();
4015 
4016     return 0;
4017 }
4018 
4019 
4020 #ifdef ENABLE_CLASSIC
4021 
4022 static void hci_update_scan_enable(void){
4023     // 2 = page scan, 1 = inq scan
4024     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
4025     hci_run();
4026 }
4027 
4028 void gap_discoverable_control(uint8_t enable){
4029     if (enable) enable = 1; // normalize argument
4030 
4031     if (hci_stack->discoverable == enable){
4032         hci_emit_discoverable_enabled(hci_stack->discoverable);
4033         return;
4034     }
4035 
4036     hci_stack->discoverable = enable;
4037     hci_update_scan_enable();
4038 }
4039 
4040 void gap_connectable_control(uint8_t enable){
4041     if (enable) enable = 1; // normalize argument
4042 
4043     // don't emit event
4044     if (hci_stack->connectable == enable) return;
4045 
4046     hci_stack->connectable = enable;
4047     hci_update_scan_enable();
4048 }
4049 #endif
4050 
4051 void gap_local_bd_addr(bd_addr_t address_buffer){
4052     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
4053 }
4054 
4055 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4056 static void hci_host_num_completed_packets(void){
4057 
4058     // create packet manually as arrays are not supported and num_commands should not get reduced
4059     hci_reserve_packet_buffer();
4060     uint8_t * packet = hci_get_outgoing_packet_buffer();
4061 
4062     uint16_t size = 0;
4063     uint16_t num_handles = 0;
4064     packet[size++] = 0x35;
4065     packet[size++] = 0x0c;
4066     size++;  // skip param len
4067     size++;  // skip num handles
4068 
4069     // add { handle, packets } entries
4070     btstack_linked_item_t * it;
4071     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4072         hci_connection_t * connection = (hci_connection_t *) it;
4073         if (connection->num_packets_completed){
4074             little_endian_store_16(packet, size, connection->con_handle);
4075             size += 2;
4076             little_endian_store_16(packet, size, connection->num_packets_completed);
4077             size += 2;
4078             //
4079             num_handles++;
4080             connection->num_packets_completed = 0;
4081         }
4082     }
4083 
4084     packet[2] = size - 3;
4085     packet[3] = num_handles;
4086 
4087     hci_stack->host_completed_packets = 0;
4088 
4089     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4090     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
4091 
4092     // release packet buffer for synchronous transport implementations
4093     if (hci_transport_synchronous()){
4094         hci_release_packet_buffer();
4095         hci_emit_transport_packet_sent();
4096     }
4097 }
4098 #endif
4099 
4100 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
4101     UNUSED(ds);
4102     hci_stack->substate = HCI_HALTING_CLOSE;
4103     // allow packet handlers to defer final shutdown
4104     hci_emit_state();
4105     hci_run();
4106 }
4107 
4108 static bool hci_run_acl_fragments(void){
4109     if (hci_stack->acl_fragmentation_total_size > 0u) {
4110         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
4111         hci_connection_t *connection = hci_connection_for_handle(con_handle);
4112         if (connection) {
4113             if (hci_can_send_prepared_acl_packet_now(con_handle)){
4114                 hci_send_acl_packet_fragments(connection);
4115                 return true;
4116             }
4117         } else {
4118             // connection gone -> discard further fragments
4119             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
4120             hci_stack->acl_fragmentation_total_size = 0;
4121             hci_stack->acl_fragmentation_pos = 0;
4122         }
4123     }
4124     return false;
4125 }
4126 
4127 #ifdef ENABLE_CLASSIC
4128 static bool hci_run_general_gap_classic(void){
4129 
4130     // assert stack is working and classic is active
4131     if (hci_classic_supported() == false)      return false;
4132     if (hci_stack->state != HCI_STATE_WORKING) return false;
4133 
4134     // decline incoming connections
4135     if (hci_stack->decline_reason){
4136         uint8_t reason = hci_stack->decline_reason;
4137         hci_stack->decline_reason = 0;
4138         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
4139         return true;
4140     }
4141 
4142     if ((hci_stack->gap_tasks & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
4143         hci_stack->gap_tasks &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
4144         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
4145         return true;
4146     }
4147     if ((hci_stack->gap_tasks & GAP_TASK_SET_LOCAL_NAME) != 0) {
4148         hci_stack->gap_tasks &= ~GAP_TASK_SET_LOCAL_NAME;
4149         gap_run_set_local_name();
4150         return true;
4151     }
4152     if ((hci_stack->gap_tasks & GAP_TASK_SET_EIR_DATA) != 0) {
4153         hci_stack->gap_tasks &= ~GAP_TASK_SET_EIR_DATA;
4154         gap_run_set_eir_data();
4155         return true;
4156     }
4157     if ((hci_stack->gap_tasks & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
4158         hci_stack->gap_tasks &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
4159         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
4160         return true;
4161     }
4162     // write page scan activity
4163     if (hci_stack->new_page_scan_interval != 0xffff) {
4164         uint16_t new_page_scan_interval = hci_stack->new_page_scan_interval;
4165         uint16_t new_page_scan_window = hci_stack->new_page_scan_window;
4166         hci_stack->new_page_scan_interval = 0xffff;
4167         hci_stack->new_page_scan_window = 0xffff;
4168         hci_send_cmd(&hci_write_page_scan_activity, new_page_scan_interval, new_page_scan_window);
4169         return true;
4170     }
4171     // write page scan type
4172     if (hci_stack->new_page_scan_type != 0xff) {
4173         uint8_t new_page_scan_type = hci_stack->new_page_scan_type;
4174         hci_stack->new_page_scan_type = 0xff;
4175         hci_send_cmd(&hci_write_page_scan_type, new_page_scan_type);
4176         return true;
4177     }
4178     // send scan enable
4179     if (hci_stack->new_scan_enable_value != 0xff) {
4180         uint8_t new_scan_enable_value = hci_stack->new_scan_enable_value;
4181         hci_stack->new_scan_enable_value = 0xff;
4182         hci_send_cmd(&hci_write_scan_enable, new_scan_enable_value);
4183         return true;
4184     }
4185 
4186     // start/stop inquiry
4187     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
4188         uint8_t duration = hci_stack->inquiry_state;
4189         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
4190         hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
4191         return true;
4192     }
4193     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
4194         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
4195         hci_send_cmd(&hci_inquiry_cancel);
4196         return true;
4197     }
4198     // remote name request
4199     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
4200         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
4201         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
4202                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
4203         return true;
4204     }
4205 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4206     // Local OOB data
4207     if (hci_stack->classic_read_local_oob_data){
4208         hci_stack->classic_read_local_oob_data = false;
4209         if (hci_stack->local_supported_commands[1] & 0x10u){
4210             hci_send_cmd(&hci_read_local_extended_oob_data);
4211         } else {
4212             hci_send_cmd(&hci_read_local_oob_data);
4213         }
4214     }
4215 #endif
4216     // pairing
4217     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
4218         uint8_t state = hci_stack->gap_pairing_state;
4219         uint8_t pin_code[16];
4220         switch (state){
4221             case GAP_PAIRING_STATE_SEND_PIN:
4222                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4223                 memset(pin_code, 0, 16);
4224                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
4225                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
4226                 break;
4227             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
4228                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4229                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
4230                 break;
4231             case GAP_PAIRING_STATE_SEND_PASSKEY:
4232                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4233                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
4234                 break;
4235             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
4236                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4237                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
4238                 break;
4239             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
4240                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4241                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
4242                 break;
4243             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
4244                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4245                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
4246                 break;
4247             default:
4248                 break;
4249         }
4250         return true;
4251     }
4252     return false;
4253 }
4254 #endif
4255 
4256 #ifdef ENABLE_BLE
4257 static bool hci_run_general_gap_le(void){
4258 
4259     // advertisements, active scanning, and creating connections requires random address to be set if using private address
4260 
4261     if (hci_stack->state != HCI_STATE_WORKING) return false;
4262     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
4263 
4264 
4265     // Phase 1: collect what to stop
4266 
4267     bool scanning_stop = false;
4268     bool connecting_stop = false;
4269     bool advertising_stop = false;
4270 
4271 #ifndef ENABLE_LE_CENTRAL
4272     UNUSED(scanning_stop);
4273     UNUSED(connecting_stop);
4274 #endif
4275 #ifndef ENABLE_LE_PERIPHERAL
4276     UNUSED(advertising_stop);
4277 #endif
4278 
4279     // check if whitelist needs modification
4280     bool whitelist_modification_pending = false;
4281     btstack_linked_list_iterator_t lit;
4282     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4283     while (btstack_linked_list_iterator_has_next(&lit)){
4284         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4285         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
4286             whitelist_modification_pending = true;
4287             break;
4288         }
4289     }
4290     // check if resolving list needs modification
4291     bool resolving_list_modification_pending = false;
4292 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4293     bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0;
4294 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
4295         resolving_list_modification_pending = true;
4296     }
4297 #endif
4298 
4299 #ifdef ENABLE_LE_CENTRAL
4300     // scanning control
4301     if (hci_stack->le_scanning_active) {
4302         // stop if:
4303         // - parameter change required
4304         // - it's disabled
4305         // - whitelist change required but used for scanning
4306         // - resolving list modified
4307         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
4308         if ((hci_stack->le_scanning_param_update) ||
4309             !hci_stack->le_scanning_enabled ||
4310             scanning_uses_whitelist ||
4311             resolving_list_modification_pending){
4312 
4313             scanning_stop = true;
4314         }
4315     }
4316 #endif
4317 
4318 #ifdef ENABLE_LE_CENTRAL
4319     // connecting control
4320     bool connecting_with_whitelist;
4321     switch (hci_stack->le_connecting_state){
4322         case LE_CONNECTING_DIRECT:
4323         case LE_CONNECTING_WHITELIST:
4324             // stop connecting if:
4325             // - connecting uses white and whitelist modification pending
4326             // - if it got disabled
4327             // - resolving list modified
4328             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
4329             if ((connecting_with_whitelist && whitelist_modification_pending) ||
4330                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
4331                 resolving_list_modification_pending) {
4332 
4333                 connecting_stop = true;
4334             }
4335             break;
4336         default:
4337             break;
4338     }
4339 #endif
4340 
4341 #ifdef ENABLE_LE_PERIPHERAL
4342     // le advertisement control
4343     if (hci_stack->le_advertisements_active){
4344         // stop if:
4345         // - parameter change required
4346         // - it's disabled
4347         // - whitelist change required but used for advertisement filter policy
4348         // - resolving list modified
4349         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
4350         bool advertising_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
4351         if (advertising_change ||
4352             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
4353             (advertising_uses_whitelist & whitelist_modification_pending) ||
4354             resolving_list_modification_pending) {
4355 
4356             advertising_stop = true;
4357         }
4358     }
4359 #endif
4360 
4361 
4362     // Phase 2: stop everything that should be off during modifications
4363 
4364 #ifdef ENABLE_LE_CENTRAL
4365     if (scanning_stop){
4366         hci_stack->le_scanning_active = false;
4367         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
4368         return true;
4369     }
4370 #endif
4371 
4372 #ifdef ENABLE_LE_CENTRAL
4373     if (connecting_stop){
4374         hci_send_cmd(&hci_le_create_connection_cancel);
4375         return true;
4376     }
4377 #endif
4378 
4379 #ifdef ENABLE_LE_PERIPHERAL
4380     if (advertising_stop){
4381         hci_stack->le_advertisements_active = false;
4382         hci_send_cmd(&hci_le_set_advertise_enable, 0);
4383         return true;
4384     }
4385 #endif
4386 
4387     // Phase 3: modify
4388 
4389 #ifdef ENABLE_LE_CENTRAL
4390     if (hci_stack->le_scanning_param_update){
4391         hci_stack->le_scanning_param_update = false;
4392         hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
4393                      hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
4394         return true;
4395     }
4396 #endif
4397 
4398 #ifdef ENABLE_LE_PERIPHERAL
4399     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
4400         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4401         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
4402         hci_send_cmd(&hci_le_set_advertising_parameters,
4403                      hci_stack->le_advertisements_interval_min,
4404                      hci_stack->le_advertisements_interval_max,
4405                      hci_stack->le_advertisements_type,
4406                      hci_stack->le_advertisements_own_addr_type,
4407                      hci_stack->le_advertisements_direct_address_type,
4408                      hci_stack->le_advertisements_direct_address,
4409                      hci_stack->le_advertisements_channel_map,
4410                      hci_stack->le_advertisements_filter_policy);
4411         return true;
4412     }
4413     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
4414         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4415         uint8_t adv_data_clean[31];
4416         memset(adv_data_clean, 0, sizeof(adv_data_clean));
4417         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
4418                      hci_stack->le_advertisements_data_len);
4419         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
4420         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
4421         return true;
4422     }
4423     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
4424         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4425         uint8_t scan_data_clean[31];
4426         memset(scan_data_clean, 0, sizeof(scan_data_clean));
4427         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
4428                      hci_stack->le_scan_response_data_len);
4429         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
4430         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
4431         return true;
4432     }
4433 #endif
4434 
4435 
4436 #ifdef ENABLE_LE_CENTRAL
4437     // if connect with whitelist was active and is not cancelled yet, wait until next time
4438     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
4439 #endif
4440 
4441     // LE Whitelist Management
4442     if (whitelist_modification_pending){
4443         // add/remove entries
4444         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4445         while (btstack_linked_list_iterator_has_next(&lit)){
4446             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4447 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
4448 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4449 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
4450 				return true;
4451 			}
4452             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
4453 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
4454                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
4455                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
4456                 return true;
4457             }
4458             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
4459 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
4460 				btstack_memory_whitelist_entry_free(entry);
4461             }
4462         }
4463     }
4464 
4465 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4466     // LE Resolving List Management
4467     if (resolving_list_supported) {
4468 		uint16_t i;
4469 		switch (hci_stack->le_resolving_list_state) {
4470 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
4471 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
4472 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
4473 				return true;
4474 			case LE_RESOLVING_LIST_READ_SIZE:
4475 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
4476 				hci_send_cmd(&hci_le_read_resolving_list_size);
4477 				return true;
4478 			case LE_RESOLVING_LIST_SEND_CLEAR:
4479 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
4480 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
4481 							  sizeof(hci_stack->le_resolving_list_add_entries));
4482 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
4483 							  sizeof(hci_stack->le_resolving_list_remove_entries));
4484 				hci_send_cmd(&hci_le_clear_resolving_list);
4485 				return true;
4486 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
4487 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4488 					uint8_t offset = i >> 3;
4489 					uint8_t mask = 1 << (i & 7);
4490 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
4491 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
4492 					bd_addr_t peer_identity_addreses;
4493 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4494 					sm_key_t peer_irk;
4495 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4496 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4497 
4498 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
4499 					// trigger whitelist entry 'update' (work around for controller bug)
4500 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4501 					while (btstack_linked_list_iterator_has_next(&lit)) {
4502 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
4503 						if (entry->address_type != peer_identity_addr_type) continue;
4504 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
4505 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
4506 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
4507 					}
4508 #endif
4509 
4510 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
4511 								 peer_identity_addreses);
4512 					return true;
4513 				}
4514 
4515 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
4516 
4517 				/* fall through */
4518 
4519 			case LE_RESOLVING_LIST_ADD_ENTRIES:
4520 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4521 					uint8_t offset = i >> 3;
4522 					uint8_t mask = 1 << (i & 7);
4523 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
4524 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
4525 					bd_addr_t peer_identity_addreses;
4526 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4527 					sm_key_t peer_irk;
4528 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4529 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4530 					const uint8_t *local_irk = gap_get_persistent_irk();
4531 					// command uses format specifier 'P' that stores 16-byte value without flip
4532 					uint8_t local_irk_flipped[16];
4533 					uint8_t peer_irk_flipped[16];
4534 					reverse_128(local_irk, local_irk_flipped);
4535 					reverse_128(peer_irk, peer_irk_flipped);
4536 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
4537 								 peer_irk_flipped, local_irk_flipped);
4538 					return true;
4539 				}
4540 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4541 				break;
4542 
4543 			default:
4544 				break;
4545 		}
4546 	}
4547     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4548 #endif
4549 
4550     // Phase 4: restore state
4551 
4552 #ifdef ENABLE_LE_CENTRAL
4553     // re-start scanning
4554     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
4555         hci_stack->le_scanning_active = true;
4556         hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
4557         return true;
4558     }
4559 #endif
4560 
4561 #ifdef ENABLE_LE_CENTRAL
4562     // re-start connecting
4563     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
4564         bd_addr_t null_addr;
4565         memset(null_addr, 0, 6);
4566         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
4567         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
4568         hci_send_cmd(&hci_le_create_connection,
4569                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
4570                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
4571                      1,         // use whitelist
4572                      0,         // peer address type
4573                      null_addr, // peer bd addr
4574                      hci_stack->le_connection_own_addr_type,   // our addr type:
4575                      hci_stack->le_connection_interval_min,    // conn interval min
4576                      hci_stack->le_connection_interval_max,    // conn interval max
4577                      hci_stack->le_connection_latency,         // conn latency
4578                      hci_stack->le_supervision_timeout,        // conn latency
4579                      hci_stack->le_minimum_ce_length,          // min ce length
4580                      hci_stack->le_maximum_ce_length           // max ce length
4581         );
4582         return true;
4583     }
4584 #endif
4585 
4586 #ifdef ENABLE_LE_PERIPHERAL
4587     // re-start advertising
4588     if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){
4589         // check if advertisements should be enabled given
4590         hci_stack->le_advertisements_active = true;
4591         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_advertisements_own_address);
4592         hci_send_cmd(&hci_le_set_advertise_enable, 1);
4593         return true;
4594     }
4595 #endif
4596 
4597     return false;
4598 }
4599 #endif
4600 
4601 static bool hci_run_general_pending_commands(void){
4602     btstack_linked_item_t * it;
4603     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
4604         hci_connection_t * connection = (hci_connection_t *) it;
4605 
4606         switch(connection->state){
4607             case SEND_CREATE_CONNECTION:
4608                 switch(connection->address_type){
4609 #ifdef ENABLE_CLASSIC
4610                     case BD_ADDR_TYPE_ACL:
4611                         log_info("sending hci_create_connection");
4612                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
4613                         break;
4614 #endif
4615                     default:
4616 #ifdef ENABLE_BLE
4617 #ifdef ENABLE_LE_CENTRAL
4618                         log_info("sending hci_le_create_connection");
4619                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
4620                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
4621                         hci_send_cmd(&hci_le_create_connection,
4622                                      hci_stack->le_connection_scan_interval,    // conn scan interval
4623                                      hci_stack->le_connection_scan_window,      // conn scan windows
4624                                      0,         // don't use whitelist
4625                                      connection->address_type, // peer address type
4626                                      connection->address,      // peer bd addr
4627                                      hci_stack->le_connection_own_addr_type,   // our addr type:
4628                                      hci_stack->le_connection_interval_min,    // conn interval min
4629                                      hci_stack->le_connection_interval_max,    // conn interval max
4630                                      hci_stack->le_connection_latency,         // conn latency
4631                                      hci_stack->le_supervision_timeout,        // conn latency
4632                                      hci_stack->le_minimum_ce_length,          // min ce length
4633                                      hci_stack->le_maximum_ce_length          // max ce length
4634                         );
4635                         connection->state = SENT_CREATE_CONNECTION;
4636 #endif
4637 #endif
4638                         break;
4639                 }
4640                 return true;
4641 
4642 #ifdef ENABLE_CLASSIC
4643             case RECEIVED_CONNECTION_REQUEST:
4644                 connection->role  = HCI_ROLE_SLAVE;
4645                 if (connection->address_type == BD_ADDR_TYPE_ACL){
4646                     log_info("sending hci_accept_connection_request");
4647                     connection->state = ACCEPTED_CONNECTION_REQUEST;
4648                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
4649                 }
4650                 return true;
4651 #endif
4652 
4653 #ifdef ENABLE_BLE
4654 #ifdef ENABLE_LE_CENTRAL
4655             case SEND_CANCEL_CONNECTION:
4656                 connection->state = SENT_CANCEL_CONNECTION;
4657                 hci_send_cmd(&hci_le_create_connection_cancel);
4658                 return true;
4659 #endif
4660 #endif
4661             case SEND_DISCONNECT:
4662                 connection->state = SENT_DISCONNECT;
4663                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4664                 return true;
4665 
4666             default:
4667                 break;
4668         }
4669 
4670         // no further commands if connection is about to get shut down
4671         if (connection->state == SENT_DISCONNECT) continue;
4672 
4673         if (connection->authentication_flags & AUTH_FLAG_READ_RSSI){
4674             connectionClearAuthenticationFlags(connection, AUTH_FLAG_READ_RSSI);
4675             hci_send_cmd(&hci_read_rssi, connection->con_handle);
4676             return true;
4677         }
4678 
4679 #ifdef ENABLE_CLASSIC
4680 
4681         if (connection->authentication_flags & AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT){
4682             connectionClearAuthenticationFlags(connection, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
4683             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
4684             return true;
4685         }
4686 
4687         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
4688             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
4689             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
4690             return true;
4691         }
4692 
4693         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
4694             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
4695             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
4696             return true;
4697         }
4698 
4699         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
4700             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
4701             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
4702             return true;
4703         }
4704 
4705         // Handling link key request requires remote supported features
4706         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
4707             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
4708             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
4709 
4710             // lookup link key using cached key first
4711             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
4712             if (!have_link_key && (hci_stack->link_key_db != NULL)){
4713                 have_link_key = hci_stack->link_key_db->get_link_key(connection->address, connection->link_key, &connection->link_key_type);
4714             }
4715 
4716             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
4717             if (have_link_key && security_level_sufficient){
4718                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
4719             } else {
4720                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
4721             }
4722             return true;
4723         }
4724 
4725         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
4726             log_info("denying to pin request");
4727             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
4728             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
4729             return true;
4730         }
4731 
4732         // security assessment requires remote features
4733         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
4734             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
4735             hci_ssp_assess_security_on_io_cap_request(connection);
4736             // 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
4737         }
4738 
4739         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
4740             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
4741             // set authentication requirements:
4742             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
4743             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
4744             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
4745             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
4746                 authreq |= 1;
4747             }
4748             bool bonding = hci_stack->bondable;
4749             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
4750                 // if we have received IO Cap Response, we're in responder role
4751                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4752                 if (bonding && !remote_bonding){
4753                     log_info("Remote not bonding, dropping local flag");
4754                     bonding = false;
4755                 }
4756             }
4757             if (bonding){
4758                 if (connection->bonding_flags & BONDING_DEDICATED){
4759                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4760                 } else {
4761                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4762                 }
4763             }
4764             uint8_t have_oob_data = 0;
4765 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4766             if (connection->classic_oob_c_192 != NULL){
4767                     have_oob_data |= 1;
4768             }
4769             if (connection->classic_oob_c_256 != NULL){
4770                 have_oob_data |= 2;
4771             }
4772 #endif
4773             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
4774             return true;
4775         }
4776 
4777         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
4778             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
4779             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
4780             return true;
4781         }
4782 
4783 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4784         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
4785             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
4786             const uint8_t zero[16] = { 0 };
4787             const uint8_t * r_192 = zero;
4788             const uint8_t * c_192 = zero;
4789             const uint8_t * r_256 = zero;
4790             const uint8_t * c_256 = zero;
4791             // verify P-256 OOB
4792             if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) {
4793                 c_256 = connection->classic_oob_c_256;
4794                 if (connection->classic_oob_r_256 != NULL) {
4795                     r_256 = connection->classic_oob_r_256;
4796                 }
4797             }
4798             // verify P-192 OOB
4799             if ((connection->classic_oob_c_192 != NULL)) {
4800                 c_192 = connection->classic_oob_c_192;
4801                 if (connection->classic_oob_r_192 != NULL) {
4802                     r_192 = connection->classic_oob_r_192;
4803                 }
4804             }
4805 
4806             // assess security
4807             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
4808             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
4809             if (need_level_4 && !can_reach_level_4){
4810                 log_info("Level 4 required, but not possible -> abort");
4811                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
4812                 // send oob negative reply
4813                 c_256 = NULL;
4814                 c_192 = NULL;
4815             }
4816 
4817             // Reply
4818             if (c_256 != zero) {
4819                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
4820             } else if (c_192 != zero){
4821                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
4822             } else {
4823                 hci_stack->classic_oob_con_handle = connection->con_handle;
4824                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
4825             }
4826             return true;
4827         }
4828 #endif
4829 
4830         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
4831             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4832             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
4833             return true;
4834         }
4835 
4836         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
4837             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4838             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
4839             return true;
4840         }
4841 
4842         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
4843             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4844             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
4845             return true;
4846         }
4847 
4848         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
4849             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
4850             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
4851             connection->state = SENT_DISCONNECT;
4852             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4853             return true;
4854         }
4855 
4856         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
4857             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
4858             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
4859             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
4860             return true;
4861         }
4862 
4863         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
4864             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
4865             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
4866             return true;
4867         }
4868         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
4869             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4870             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
4871             return true;
4872         }
4873 #endif
4874 
4875         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
4876             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
4877 #ifdef ENABLE_CLASSIC
4878             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
4879 #endif
4880             if (connection->state != SENT_DISCONNECT){
4881                 connection->state = SENT_DISCONNECT;
4882                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4883                 return true;
4884             }
4885         }
4886 
4887 #ifdef ENABLE_CLASSIC
4888         uint16_t sniff_min_interval;
4889         switch (connection->sniff_min_interval){
4890             case 0:
4891                 break;
4892             case 0xffff:
4893                 connection->sniff_min_interval = 0;
4894                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
4895                 return true;
4896             default:
4897                 sniff_min_interval = connection->sniff_min_interval;
4898                 connection->sniff_min_interval = 0;
4899                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
4900                 return true;
4901         }
4902 
4903         if (connection->sniff_subrating_max_latency != 0xffff){
4904             uint16_t max_latency = connection->sniff_subrating_max_latency;
4905             connection->sniff_subrating_max_latency = 0;
4906             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
4907             return true;
4908         }
4909 
4910         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
4911             uint8_t service_type = (uint8_t) connection->qos_service_type;
4912             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
4913             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);
4914             return true;
4915         }
4916 
4917         if (connection->request_role != HCI_ROLE_INVALID){
4918             hci_role_t role = connection->request_role;
4919             connection->request_role = HCI_ROLE_INVALID;
4920             hci_send_cmd(&hci_switch_role_command, connection->address, role);
4921             return true;
4922         }
4923 #endif
4924 
4925 #ifdef ENABLE_BLE
4926         switch (connection->le_con_parameter_update_state){
4927             // response to L2CAP CON PARAMETER UPDATE REQUEST
4928             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
4929                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4930                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
4931                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4932                              0x0000, 0xffff);
4933                 return true;
4934             case CON_PARAMETER_UPDATE_REPLY:
4935                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4936                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
4937                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4938                              0x0000, 0xffff);
4939                 return true;
4940             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
4941                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4942                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
4943                 return true;
4944             default:
4945                 break;
4946         }
4947         if (connection->le_phy_update_all_phys != 0xffu){
4948             uint8_t all_phys = connection->le_phy_update_all_phys;
4949             connection->le_phy_update_all_phys = 0xff;
4950             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);
4951             return true;
4952         }
4953 #endif
4954     }
4955     return false;
4956 }
4957 
4958 static void hci_run(void){
4959 
4960     bool done;
4961 
4962     // send continuation fragments first, as they block the prepared packet buffer
4963     done = hci_run_acl_fragments();
4964     if (done) return;
4965 
4966 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4967     // send host num completed packets next as they don't require num_cmd_packets > 0
4968     if (!hci_can_send_comand_packet_transport()) return;
4969     if (hci_stack->host_completed_packets){
4970         hci_host_num_completed_packets();
4971         return;
4972     }
4973 #endif
4974 
4975     if (!hci_can_send_command_packet_now()) return;
4976 
4977     // global/non-connection oriented commands
4978 
4979 
4980 #ifdef ENABLE_CLASSIC
4981     // general gap classic
4982     done = hci_run_general_gap_classic();
4983     if (done) return;
4984 #endif
4985 
4986 #ifdef ENABLE_BLE
4987     // general gap le
4988     done = hci_run_general_gap_le();
4989     if (done) return;
4990 #endif
4991 
4992     // send pending HCI commands
4993     done = hci_run_general_pending_commands();
4994     if (done) return;
4995 
4996     // stack state sub statemachines
4997     hci_connection_t * connection;
4998     switch (hci_stack->state){
4999         case HCI_STATE_INITIALIZING:
5000             hci_initializing_run();
5001             break;
5002 
5003         case HCI_STATE_HALTING:
5004 
5005             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5006             switch (hci_stack->substate){
5007                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
5008                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
5009 
5010 #ifdef ENABLE_BLE
5011 #ifdef ENABLE_LE_CENTRAL
5012                     // free whitelist entries
5013                     {
5014                         btstack_linked_list_iterator_t lit;
5015                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5016                         while (btstack_linked_list_iterator_has_next(&lit)){
5017                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5018                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5019                             btstack_memory_whitelist_entry_free(entry);
5020                         }
5021                     }
5022 #endif
5023 #endif
5024                     // close all open connections
5025                     connection =  (hci_connection_t *) hci_stack->connections;
5026                     if (connection){
5027                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5028                         if (!hci_can_send_command_packet_now()) return;
5029 
5030                         // check state
5031                         if (connection->state == SENT_DISCONNECT) return;
5032                         connection->state = SENT_DISCONNECT;
5033 
5034                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
5035 
5036                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
5037                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
5038 
5039                         // ... which would be ignored anyway as we shutdown (free) the connection now
5040                         hci_shutdown_connection(connection);
5041 
5042                         // finally, send the disconnect command
5043                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5044                         return;
5045                     }
5046 
5047                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
5048                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5049                         log_info("HCI_STATE_HALTING: wait 50 ms");
5050                         hci_stack->substate = HCI_HALTING_W4_TIMER;
5051                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5052                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5053                         btstack_run_loop_add_timer(&hci_stack->timeout);
5054                         break;
5055                     }
5056 
5057                     /* fall through */
5058 
5059                 case HCI_HALTING_CLOSE:
5060                     log_info("HCI_STATE_HALTING, calling off");
5061 
5062                     // switch mode
5063                     hci_power_control_off();
5064 
5065                     log_info("HCI_STATE_HALTING, emitting state");
5066                     hci_emit_state();
5067                     log_info("HCI_STATE_HALTING, done");
5068                     break;
5069 
5070                 case HCI_HALTING_W4_TIMER:
5071                     // keep waiting
5072 
5073                     break;
5074                 default:
5075                     break;
5076             }
5077 
5078             break;
5079 
5080         case HCI_STATE_FALLING_ASLEEP:
5081             switch(hci_stack->substate) {
5082                 case HCI_FALLING_ASLEEP_DISCONNECT:
5083                     log_info("HCI_STATE_FALLING_ASLEEP");
5084                     // close all open connections
5085                     connection =  (hci_connection_t *) hci_stack->connections;
5086 
5087 #ifdef HAVE_PLATFORM_IPHONE_OS
5088                     // don't close connections, if H4 supports power management
5089                     if (btstack_control_iphone_power_management_enabled()){
5090                         connection = NULL;
5091                     }
5092 #endif
5093                     if (connection){
5094 
5095                         // send disconnect
5096                         if (!hci_can_send_command_packet_now()) return;
5097 
5098                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5099                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5100 
5101                         // send disconnected event right away - causes higher layer connections to get closed, too.
5102                         hci_shutdown_connection(connection);
5103                         return;
5104                     }
5105 
5106                     if (hci_classic_supported()){
5107                         // disable page and inquiry scan
5108                         if (!hci_can_send_command_packet_now()) return;
5109 
5110                         log_info("HCI_STATE_HALTING, disabling inq scans");
5111                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5112 
5113                         // continue in next sub state
5114                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5115                         break;
5116                     }
5117 
5118                     /* fall through */
5119 
5120                 case HCI_FALLING_ASLEEP_COMPLETE:
5121                     log_info("HCI_STATE_HALTING, calling sleep");
5122 #ifdef HAVE_PLATFORM_IPHONE_OS
5123                     // don't actually go to sleep, if H4 supports power management
5124                     if (btstack_control_iphone_power_management_enabled()){
5125                         // SLEEP MODE reached
5126                         hci_stack->state = HCI_STATE_SLEEPING;
5127                         hci_emit_state();
5128                         break;
5129                     }
5130 #endif
5131                     // switch mode
5132                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5133                     hci_emit_state();
5134                     break;
5135 
5136                 default:
5137                     break;
5138             }
5139             break;
5140 
5141         default:
5142             break;
5143     }
5144 }
5145 
5146 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
5147     // house-keeping
5148 
5149 #ifdef ENABLE_CLASSIC
5150     bd_addr_t addr;
5151     hci_connection_t * conn;
5152 #endif
5153 #ifdef ENABLE_LE_CENTRAL
5154     uint8_t initiator_filter_policy;
5155 #endif
5156 
5157     uint16_t opcode = little_endian_read_16(packet, 0);
5158     switch (opcode) {
5159         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
5160             hci_stack->loopback_mode = packet[3];
5161             break;
5162 
5163 #ifdef ENABLE_CLASSIC
5164         case HCI_OPCODE_HCI_CREATE_CONNECTION:
5165             reverse_bd_addr(&packet[3], addr);
5166             log_info("Create_connection to %s", bd_addr_to_str(addr));
5167 
5168             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
5169             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
5170                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
5171                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
5172             }
5173 
5174             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5175             if (!conn) {
5176                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5177                 if (!conn) {
5178                     // notify client that alloc failed
5179                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5180                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
5181                 }
5182                 conn->state = SEND_CREATE_CONNECTION;
5183                 conn->role  = HCI_ROLE_MASTER;
5184             }
5185 
5186             conn->con_handle = HCI_CON_HANDLE_INVALID;
5187             conn->role = HCI_ROLE_INVALID;
5188 
5189             log_info("conn state %u", conn->state);
5190             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
5191             switch (conn->state) {
5192                 // if connection active exists
5193                 case OPEN:
5194                     // and OPEN, emit connection complete command
5195                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
5196                     // packet not sent to controller
5197                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5198                 case RECEIVED_DISCONNECTION_COMPLETE:
5199                     // create connection triggered in disconnect complete event, let's do it now
5200                     break;
5201                 case SEND_CREATE_CONNECTION:
5202                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
5203                     break;
5204                 default:
5205                     // otherwise, just ignore as it is already in the open process
5206                     // packet not sent to controller
5207                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5208             }
5209             conn->state = SENT_CREATE_CONNECTION;
5210 
5211             // track outgoing connection
5212             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
5213             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
5214             break;
5215         case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY:
5216             if (hci_stack->link_key_db) {
5217                 reverse_bd_addr(&packet[3], addr);
5218                 hci_stack->link_key_db->delete_link_key(addr);
5219             }
5220             break;
5221 
5222 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
5223         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
5224             // setup_synchronous_connection? Voice setting at offset 22
5225             // TODO: compare to current setting if sco connection already active
5226             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
5227             break;
5228         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
5229             // accept_synchronus_connection? Voice setting at offset 18
5230             // TODO: compare to current setting if sco connection already active
5231             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
5232             break;
5233 #endif
5234 #endif
5235 
5236 #ifdef ENABLE_BLE
5237         case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS:
5238             hci_stack->le_random_address_set = 1;
5239             reverse_bd_addr(&packet[3], hci_stack->le_random_address);
5240             break;
5241 #ifdef ENABLE_LE_PERIPHERAL
5242         case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE:
5243             hci_stack->le_advertisements_active = packet[3] != 0;
5244             break;
5245 #endif
5246 #ifdef ENABLE_LE_CENTRAL
5247         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
5248             // white list used?
5249             initiator_filter_policy = packet[7];
5250             switch (initiator_filter_policy) {
5251                 case 0:
5252                     // whitelist not used
5253                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
5254                     break;
5255                 case 1:
5256                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
5257                     break;
5258                 default:
5259                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
5260                     break;
5261             }
5262             // track outgoing connection
5263             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
5264             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
5265             break;
5266         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
5267             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
5268             break;
5269 #endif
5270 #endif
5271         default:
5272             break;
5273     }
5274 
5275     hci_stack->num_cmd_packets--;
5276 
5277     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5278     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5279     if (err != 0){
5280         return ERROR_CODE_HARDWARE_FAILURE;
5281     }
5282     return ERROR_CODE_SUCCESS;
5283 }
5284 
5285 // disconnect because of security block
5286 void hci_disconnect_security_block(hci_con_handle_t con_handle){
5287     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5288     if (!connection) return;
5289     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
5290 }
5291 
5292 
5293 // Configure Secure Simple Pairing
5294 
5295 #ifdef ENABLE_CLASSIC
5296 
5297 // enable will enable SSP during init
5298 void gap_ssp_set_enable(int enable){
5299     hci_stack->ssp_enable = enable;
5300 }
5301 
5302 static int hci_local_ssp_activated(void){
5303     return gap_ssp_supported() && hci_stack->ssp_enable;
5304 }
5305 
5306 // if set, BTstack will respond to io capability request using authentication requirement
5307 void gap_ssp_set_io_capability(int io_capability){
5308     hci_stack->ssp_io_capability = io_capability;
5309 }
5310 void gap_ssp_set_authentication_requirement(int authentication_requirement){
5311     hci_stack->ssp_authentication_requirement = authentication_requirement;
5312 }
5313 
5314 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
5315 void gap_ssp_set_auto_accept(int auto_accept){
5316     hci_stack->ssp_auto_accept = auto_accept;
5317 }
5318 
5319 void gap_secure_connections_enable(bool enable){
5320     hci_stack->secure_connections_enable = enable;
5321 }
5322 
5323 #endif
5324 
5325 // va_list part of hci_send_cmd
5326 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
5327     if (!hci_can_send_command_packet_now()){
5328         log_error("hci_send_cmd called but cannot send packet now");
5329         return ERROR_CODE_COMMAND_DISALLOWED;
5330     }
5331 
5332     // for HCI INITIALIZATION
5333     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
5334     hci_stack->last_cmd_opcode = cmd->opcode;
5335 
5336     hci_reserve_packet_buffer();
5337     uint8_t * packet = hci_stack->hci_packet_buffer;
5338     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
5339     uint8_t status = hci_send_cmd_packet(packet, size);
5340 
5341     // release packet buffer on error or for synchronous transport implementations
5342     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
5343         hci_release_packet_buffer();
5344         hci_emit_transport_packet_sent();
5345     }
5346 
5347     return status;
5348 }
5349 
5350 /**
5351  * pre: numcmds >= 0 - it's allowed to send a command to the controller
5352  */
5353 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
5354     va_list argptr;
5355     va_start(argptr, cmd);
5356     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
5357     va_end(argptr);
5358     return status;
5359 }
5360 
5361 // Create various non-HCI events.
5362 // TODO: generalize, use table similar to hci_create_command
5363 
5364 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
5365     // dump packet
5366     if (dump) {
5367         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
5368     }
5369 
5370     // dispatch to all event handlers
5371     btstack_linked_list_iterator_t it;
5372     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
5373     while (btstack_linked_list_iterator_has_next(&it)){
5374         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
5375         entry->callback(HCI_EVENT_PACKET, 0, event, size);
5376     }
5377 }
5378 
5379 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
5380     if (!hci_stack->acl_packet_handler) return;
5381     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
5382 }
5383 
5384 #ifdef ENABLE_CLASSIC
5385 static void hci_notify_if_sco_can_send_now(void){
5386     // notify SCO sender if waiting
5387     if (!hci_stack->sco_waiting_for_can_send_now) return;
5388     if (hci_can_send_sco_packet_now()){
5389         hci_stack->sco_waiting_for_can_send_now = 0;
5390         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
5391         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
5392         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
5393     }
5394 }
5395 
5396 // parsing end emitting has been merged to reduce code size
5397 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
5398     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
5399 
5400     uint8_t * eir_data;
5401     ad_context_t context;
5402     const uint8_t * name;
5403     uint8_t         name_len;
5404 
5405     if (size < 3) return;
5406 
5407     int event_type = hci_event_packet_get_type(packet);
5408     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
5409     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
5410 
5411     switch (event_type){
5412         case HCI_EVENT_INQUIRY_RESULT:
5413         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5414             if (size != (3 + (num_responses * 14))) return;
5415             break;
5416         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5417             if (size != 257) return;
5418             if (num_responses != 1) return;
5419             break;
5420         default:
5421             return;
5422     }
5423 
5424     // event[1] is set at the end
5425     int i;
5426     for (i=0; i<num_responses;i++){
5427         memset(event, 0, sizeof(event));
5428         event[0] = GAP_EVENT_INQUIRY_RESULT;
5429         uint8_t event_size = 27;    // if name is not set by EIR
5430 
5431         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
5432         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
5433         (void)memcpy(&event[9],
5434                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
5435                      3); // class of device
5436         (void)memcpy(&event[12],
5437                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
5438                      2); // clock offset
5439 
5440         switch (event_type){
5441             case HCI_EVENT_INQUIRY_RESULT:
5442                 // 14,15,16,17 = 0, size 18
5443                 break;
5444             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5445                 event[14] = 1;
5446                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5447                 // 16,17 = 0, size 18
5448                 break;
5449             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5450                 event[14] = 1;
5451                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5452                 // EIR packets only contain a single inquiry response
5453                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
5454                 name = NULL;
5455                 // Iterate over EIR data
5456                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
5457                     uint8_t data_type    = ad_iterator_get_data_type(&context);
5458                     uint8_t data_size    = ad_iterator_get_data_len(&context);
5459                     const uint8_t * data = ad_iterator_get_data(&context);
5460                     // Prefer Complete Local Name over Shortened Local Name
5461                     switch (data_type){
5462                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
5463                             if (name) continue;
5464                             /* fall through */
5465                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
5466                             name = data;
5467                             name_len = data_size;
5468                             break;
5469                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
5470                             if (data_size != 8) break;
5471                             event[16] = 1;
5472                             memcpy(&event[17], data, 8);
5473                             break;
5474                         default:
5475                             break;
5476                     }
5477                 }
5478                 if (name){
5479                     event[25] = 1;
5480                     // truncate name if needed
5481                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
5482                     event[26] = len;
5483                     (void)memcpy(&event[27], name, len);
5484                     event_size += len;
5485                 }
5486                 break;
5487             default:
5488                 return;
5489         }
5490         event[1] = event_size - 2;
5491         hci_emit_event(event, event_size, 1);
5492     }
5493 }
5494 #endif
5495 
5496 void hci_emit_state(void){
5497     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
5498     uint8_t event[3];
5499     event[0] = BTSTACK_EVENT_STATE;
5500     event[1] = sizeof(event) - 2u;
5501     event[2] = hci_stack->state;
5502     hci_emit_event(event, sizeof(event), 1);
5503 }
5504 
5505 #ifdef ENABLE_CLASSIC
5506 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5507     uint8_t event[13];
5508     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
5509     event[1] = sizeof(event) - 2;
5510     event[2] = status;
5511     little_endian_store_16(event, 3, con_handle);
5512     reverse_bd_addr(address, &event[5]);
5513     event[11] = 1; // ACL connection
5514     event[12] = 0; // encryption disabled
5515     hci_emit_event(event, sizeof(event), 1);
5516 }
5517 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
5518     if (disable_l2cap_timeouts) return;
5519     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
5520     uint8_t event[4];
5521     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
5522     event[1] = sizeof(event) - 2;
5523     little_endian_store_16(event, 2, conn->con_handle);
5524     hci_emit_event(event, sizeof(event), 1);
5525 }
5526 #endif
5527 
5528 #ifdef ENABLE_BLE
5529 #ifdef ENABLE_LE_CENTRAL
5530 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){
5531     uint8_t event[21];
5532     event[0] = HCI_EVENT_LE_META;
5533     event[1] = sizeof(event) - 2u;
5534     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
5535     event[3] = status;
5536     little_endian_store_16(event, 4, con_handle);
5537     event[6] = 0; // TODO: role
5538     event[7] = address_type;
5539     reverse_bd_addr(address, &event[8]);
5540     little_endian_store_16(event, 14, 0); // interval
5541     little_endian_store_16(event, 16, 0); // latency
5542     little_endian_store_16(event, 18, 0); // supervision timeout
5543     event[20] = 0; // master clock accuracy
5544     hci_emit_event(event, sizeof(event), 1);
5545 }
5546 #endif
5547 #endif
5548 
5549 static void hci_emit_transport_packet_sent(void){
5550     // notify upper stack that it might be possible to send again
5551     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
5552     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
5553 }
5554 
5555 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
5556     uint8_t event[6];
5557     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
5558     event[1] = sizeof(event) - 2u;
5559     event[2] = 0; // status = OK
5560     little_endian_store_16(event, 3, con_handle);
5561     event[5] = reason;
5562     hci_emit_event(event, sizeof(event), 1);
5563 }
5564 
5565 static void hci_emit_nr_connections_changed(void){
5566     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
5567     uint8_t event[3];
5568     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
5569     event[1] = sizeof(event) - 2u;
5570     event[2] = nr_hci_connections();
5571     hci_emit_event(event, sizeof(event), 1);
5572 }
5573 
5574 static void hci_emit_hci_open_failed(void){
5575     log_info("BTSTACK_EVENT_POWERON_FAILED");
5576     uint8_t event[2];
5577     event[0] = BTSTACK_EVENT_POWERON_FAILED;
5578     event[1] = sizeof(event) - 2u;
5579     hci_emit_event(event, sizeof(event), 1);
5580 }
5581 
5582 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
5583     log_info("hci_emit_dedicated_bonding_result %u ", status);
5584     uint8_t event[9];
5585     int pos = 0;
5586     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
5587     event[pos++] = sizeof(event) - 2u;
5588     event[pos++] = status;
5589     reverse_bd_addr(address, &event[pos]);
5590     hci_emit_event(event, sizeof(event), 1);
5591 }
5592 
5593 
5594 #ifdef ENABLE_CLASSIC
5595 
5596 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
5597     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
5598     uint8_t event[5];
5599     int pos = 0;
5600     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
5601     event[pos++] = sizeof(event) - 2;
5602     little_endian_store_16(event, 2, con_handle);
5603     pos += 2;
5604     event[pos++] = level;
5605     hci_emit_event(event, sizeof(event), 1);
5606 }
5607 
5608 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
5609     if (!connection) return LEVEL_0;
5610     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
5611     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
5612     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
5613     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
5614     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
5615     // LEVEL 4 always requires 128 bit encrytion key size
5616     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
5617         security_level = LEVEL_3;
5618     }
5619     return security_level;
5620 }
5621 
5622 static void hci_emit_discoverable_enabled(uint8_t enabled){
5623     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
5624     uint8_t event[3];
5625     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
5626     event[1] = sizeof(event) - 2;
5627     event[2] = enabled;
5628     hci_emit_event(event, sizeof(event), 1);
5629 }
5630 
5631 // query if remote side supports eSCO
5632 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
5633     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5634     if (!connection) return false;
5635     return (connection->remote_supported_features[0] & 1) != 0;
5636 }
5637 
5638 static bool hci_ssp_supported(hci_connection_t * connection){
5639     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
5640     return (connection->bonding_flags & mask) == mask;
5641 }
5642 
5643 // query if remote side supports SSP
5644 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
5645     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5646     if (!connection) return false;
5647     return hci_ssp_supported(connection) ? 1 : 0;
5648 }
5649 
5650 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
5651     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
5652 }
5653 
5654 // GAP API
5655 /**
5656  * @bbrief enable/disable bonding. default is enabled
5657  * @praram enabled
5658  */
5659 void gap_set_bondable_mode(int enable){
5660     hci_stack->bondable = enable ? 1 : 0;
5661 }
5662 /**
5663  * @brief Get bondable mode.
5664  * @return 1 if bondable
5665  */
5666 int gap_get_bondable_mode(void){
5667     return hci_stack->bondable;
5668 }
5669 
5670 /**
5671  * @brief map link keys to security levels
5672  */
5673 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
5674     switch (link_key_type){
5675         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5676             return LEVEL_4;
5677         case COMBINATION_KEY:
5678         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5679             return LEVEL_3;
5680         default:
5681             return LEVEL_2;
5682     }
5683 }
5684 
5685 /**
5686  * @brief map link keys to secure connection yes/no
5687  */
5688 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
5689     switch (link_key_type){
5690         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5691         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5692             return 1;
5693         default:
5694             return 0;
5695     }
5696 }
5697 
5698 /**
5699  * @brief map link keys to authenticated
5700  */
5701 int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
5702     switch (link_key_type){
5703         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5704         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5705             return 1;
5706         default:
5707             return 0;
5708     }
5709 }
5710 
5711 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
5712     log_info("gap_mitm_protection_required_for_security_level %u", level);
5713     return level > LEVEL_2;
5714 }
5715 
5716 /**
5717  * @brief get current security level
5718  */
5719 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
5720     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5721     if (!connection) return LEVEL_0;
5722     return gap_security_level_for_connection(connection);
5723 }
5724 
5725 /**
5726  * @brief request connection to device to
5727  * @result GAP_AUTHENTICATION_RESULT
5728  */
5729 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
5730     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5731     if (!connection){
5732         hci_emit_security_level(con_handle, LEVEL_0);
5733         return;
5734     }
5735 
5736     btstack_assert(hci_is_le_connection(connection) == false);
5737 
5738     // 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)
5739     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
5740     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
5741         requested_level = LEVEL_4;
5742     }
5743 
5744     gap_security_level_t current_level = gap_security_level(con_handle);
5745     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
5746         requested_level, connection->requested_security_level, current_level);
5747 
5748     // authentication active if authentication request was sent or planned level > 0
5749     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
5750     if (authentication_active){
5751         // authentication already active
5752         if (connection->requested_security_level < requested_level){
5753             // increase requested level as new level is higher
5754             // TODO: handle re-authentication when done
5755             connection->requested_security_level = requested_level;
5756         }
5757     } else {
5758         // no request active, notify if security sufficient
5759         if (requested_level <= current_level){
5760             hci_emit_security_level(con_handle, current_level);
5761             return;
5762         }
5763 
5764         // store request
5765         connection->requested_security_level = requested_level;
5766 
5767         // start to authenticate connection
5768         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
5769         hci_run();
5770     }
5771 }
5772 
5773 /**
5774  * @brief start dedicated bonding with device. disconnect after bonding
5775  * @param device
5776  * @param request MITM protection
5777  * @result GAP_DEDICATED_BONDING_COMPLETE
5778  */
5779 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
5780 
5781     // create connection state machine
5782     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
5783 
5784     if (!connection){
5785         return BTSTACK_MEMORY_ALLOC_FAILED;
5786     }
5787 
5788     // delete linkn key
5789     gap_drop_link_key_for_bd_addr(device);
5790 
5791     // configure LEVEL_2/3, dedicated bonding
5792     connection->state = SEND_CREATE_CONNECTION;
5793     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
5794     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
5795     connection->bonding_flags = BONDING_DEDICATED;
5796 
5797     // wait for GAP Security Result and send GAP Dedicated Bonding complete
5798 
5799     // handle: connnection failure (connection complete != ok)
5800     // handle: authentication failure
5801     // handle: disconnect on done
5802 
5803     hci_run();
5804 
5805     return 0;
5806 }
5807 
5808 void gap_set_local_name(const char * local_name){
5809     hci_stack->local_name = local_name;
5810     hci_stack->gap_tasks |= GAP_TASK_SET_LOCAL_NAME;
5811     // also update EIR if not set by user
5812     if (hci_stack->eir_data == NULL){
5813         hci_stack->gap_tasks |= GAP_TASK_SET_EIR_DATA;
5814     }
5815     hci_run();
5816 }
5817 #endif
5818 
5819 
5820 #ifdef ENABLE_BLE
5821 
5822 #ifdef ENABLE_LE_CENTRAL
5823 void gap_start_scan(void){
5824     hci_stack->le_scanning_enabled = true;
5825     hci_run();
5826 }
5827 
5828 void gap_stop_scan(void){
5829     hci_stack->le_scanning_enabled = false;
5830     hci_run();
5831 }
5832 
5833 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
5834     hci_stack->le_scan_type          = scan_type;
5835     hci_stack->le_scan_filter_policy = scanning_filter_policy;
5836     hci_stack->le_scan_interval      = scan_interval;
5837     hci_stack->le_scan_window        = scan_window;
5838     hci_stack->le_scanning_param_update = true;
5839     hci_run();
5840 }
5841 
5842 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
5843     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
5844 }
5845 
5846 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
5847     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
5848     if (!conn){
5849         // disallow if le connection is already outgoing
5850         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5851             log_error("le connection already active");
5852             return ERROR_CODE_COMMAND_DISALLOWED;
5853         }
5854 
5855         log_info("gap_connect: no connection exists yet, creating context");
5856         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
5857         if (!conn){
5858             // notify client that alloc failed
5859             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5860             log_info("gap_connect: failed to alloc hci_connection_t");
5861             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
5862         }
5863 
5864         // set le connecting state
5865         if (hci_is_le_connection_type(addr_type)){
5866             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
5867         }
5868 
5869         conn->state = SEND_CREATE_CONNECTION;
5870         log_info("gap_connect: send create connection next");
5871         hci_run();
5872         return ERROR_CODE_SUCCESS;
5873     }
5874 
5875     if (!hci_is_le_connection(conn) ||
5876         (conn->state == SEND_CREATE_CONNECTION) ||
5877         (conn->state == SENT_CREATE_CONNECTION)) {
5878         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
5879         log_error("gap_connect: classic connection or connect is already being created");
5880         return GATT_CLIENT_IN_WRONG_STATE;
5881     }
5882 
5883     // check if connection was just disconnected
5884     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5885         log_info("gap_connect: send create connection (again)");
5886         conn->state = SEND_CREATE_CONNECTION;
5887         hci_run();
5888         return ERROR_CODE_SUCCESS;
5889     }
5890 
5891     log_info("gap_connect: context exists with state %u", conn->state);
5892     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
5893     hci_run();
5894     return ERROR_CODE_SUCCESS;
5895 }
5896 
5897 // @assumption: only a single outgoing LE Connection exists
5898 static hci_connection_t * gap_get_outgoing_connection(void){
5899     btstack_linked_item_t *it;
5900     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5901         hci_connection_t * conn = (hci_connection_t *) it;
5902         if (!hci_is_le_connection(conn)) continue;
5903         switch (conn->state){
5904             case SEND_CREATE_CONNECTION:
5905             case SENT_CREATE_CONNECTION:
5906             case SENT_CANCEL_CONNECTION:
5907                 return conn;
5908             default:
5909                 break;
5910         };
5911     }
5912     return NULL;
5913 }
5914 
5915 uint8_t gap_connect_cancel(void){
5916     hci_connection_t * conn = gap_get_outgoing_connection();
5917     if (!conn) return 0;
5918     switch (conn->state){
5919         case SEND_CREATE_CONNECTION:
5920             // skip sending create connection and emit event instead
5921             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
5922             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
5923             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
5924             btstack_memory_hci_connection_free( conn );
5925             break;
5926         case SENT_CREATE_CONNECTION:
5927             // request to send cancel connection
5928             conn->state = SEND_CANCEL_CONNECTION;
5929             hci_run();
5930             break;
5931         default:
5932             break;
5933     }
5934     return 0;
5935 }
5936 #endif
5937 
5938 #ifdef ENABLE_LE_CENTRAL
5939 /**
5940  * @brief Set connection parameters for outgoing connections
5941  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
5942  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
5943  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
5944  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
5945  * @param conn_latency, default: 4
5946  * @param supervision_timeout (unit: 10ms), default: 720 ms
5947  * @param min_ce_length (unit: 0.625ms), default: 10 ms
5948  * @param max_ce_length (unit: 0.625ms), default: 30 ms
5949  */
5950 
5951 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
5952     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
5953     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
5954     hci_stack->le_connection_scan_interval = conn_scan_interval;
5955     hci_stack->le_connection_scan_window = conn_scan_window;
5956     hci_stack->le_connection_interval_min = conn_interval_min;
5957     hci_stack->le_connection_interval_max = conn_interval_max;
5958     hci_stack->le_connection_latency = conn_latency;
5959     hci_stack->le_supervision_timeout = supervision_timeout;
5960     hci_stack->le_minimum_ce_length = min_ce_length;
5961     hci_stack->le_maximum_ce_length = max_ce_length;
5962 }
5963 #endif
5964 
5965 /**
5966  * @brief Updates the connection parameters for a given LE connection
5967  * @param handle
5968  * @param conn_interval_min (unit: 1.25ms)
5969  * @param conn_interval_max (unit: 1.25ms)
5970  * @param conn_latency
5971  * @param supervision_timeout (unit: 10ms)
5972  * @returns 0 if ok
5973  */
5974 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5975     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5976     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5977     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5978     connection->le_conn_interval_min = conn_interval_min;
5979     connection->le_conn_interval_max = conn_interval_max;
5980     connection->le_conn_latency = conn_latency;
5981     connection->le_supervision_timeout = supervision_timeout;
5982     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
5983     hci_run();
5984     return 0;
5985 }
5986 
5987 /**
5988  * @brief Request an update of the connection parameter for a given LE connection
5989  * @param handle
5990  * @param conn_interval_min (unit: 1.25ms)
5991  * @param conn_interval_max (unit: 1.25ms)
5992  * @param conn_latency
5993  * @param supervision_timeout (unit: 10ms)
5994  * @returns 0 if ok
5995  */
5996 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5997     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5998     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5999     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6000     connection->le_conn_interval_min = conn_interval_min;
6001     connection->le_conn_interval_max = conn_interval_max;
6002     connection->le_conn_latency = conn_latency;
6003     connection->le_supervision_timeout = supervision_timeout;
6004     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
6005     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
6006     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
6007     return 0;
6008 }
6009 
6010 #ifdef ENABLE_LE_PERIPHERAL
6011 
6012 /**
6013  * @brief Set Advertisement Data
6014  * @param advertising_data_length
6015  * @param advertising_data (max 31 octets)
6016  * @note data is not copied, pointer has to stay valid
6017  */
6018 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
6019     hci_stack->le_advertisements_data_len = advertising_data_length;
6020     hci_stack->le_advertisements_data = advertising_data;
6021     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6022     hci_run();
6023 }
6024 
6025 /**
6026  * @brief Set Scan Response Data
6027  * @param advertising_data_length
6028  * @param advertising_data (max 31 octets)
6029  * @note data is not copied, pointer has to stay valid
6030  */
6031 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
6032     hci_stack->le_scan_response_data_len = scan_response_data_length;
6033     hci_stack->le_scan_response_data = scan_response_data;
6034     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6035     hci_run();
6036 }
6037 
6038 /**
6039  * @brief Set Advertisement Parameters
6040  * @param adv_int_min
6041  * @param adv_int_max
6042  * @param adv_type
6043  * @param direct_address_type
6044  * @param direct_address
6045  * @param channel_map
6046  * @param filter_policy
6047  *
6048  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
6049  */
6050  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
6051     uint8_t direct_address_typ, bd_addr_t direct_address,
6052     uint8_t channel_map, uint8_t filter_policy) {
6053 
6054     hci_stack->le_advertisements_interval_min = adv_int_min;
6055     hci_stack->le_advertisements_interval_max = adv_int_max;
6056     hci_stack->le_advertisements_type = adv_type;
6057     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
6058     hci_stack->le_advertisements_channel_map = channel_map;
6059     hci_stack->le_advertisements_filter_policy = filter_policy;
6060     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
6061                  6);
6062 
6063     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS | LE_ADVERTISEMENT_TASKS_PARAMS_SET;
6064     hci_run();
6065  }
6066 
6067 /**
6068  * @brief Enable/Disable Advertisements
6069  * @param enabled
6070  */
6071 void gap_advertisements_enable(int enabled){
6072     hci_stack->le_advertisements_enabled = enabled != 0;
6073     hci_update_advertisements_enabled_for_current_roles();
6074     hci_run();
6075 }
6076 
6077 #endif
6078 
6079 void hci_le_set_own_address_type(uint8_t own_address_type){
6080     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
6081     if (own_address_type == hci_stack->le_own_addr_type) return;
6082     hci_stack->le_own_addr_type = own_address_type;
6083 
6084 #ifdef ENABLE_LE_PERIPHERAL
6085     // update advertisement parameters, too
6086     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6087     hci_run();
6088 #endif
6089 #ifdef ENABLE_LE_CENTRAL
6090     // note: we don't update scan parameters or modify ongoing connection attempts
6091 #endif
6092 }
6093 
6094 #endif
6095 
6096 uint8_t gap_disconnect(hci_con_handle_t handle){
6097     hci_connection_t * conn = hci_connection_for_handle(handle);
6098     if (!conn){
6099         hci_emit_disconnection_complete(handle, 0);
6100         return 0;
6101     }
6102     // ignore if already disconnected
6103     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
6104         return 0;
6105     }
6106     conn->state = SEND_DISCONNECT;
6107     hci_run();
6108     return 0;
6109 }
6110 
6111 int gap_read_rssi(hci_con_handle_t con_handle){
6112     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6113     if (hci_connection == NULL) return 0;
6114     connectionSetAuthenticationFlags(hci_connection, AUTH_FLAG_READ_RSSI);
6115     hci_run();
6116     return 1;
6117 }
6118 
6119 /**
6120  * @brief Get connection type
6121  * @param con_handle
6122  * @result connection_type
6123  */
6124 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
6125     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6126     if (!conn) return GAP_CONNECTION_INVALID;
6127     switch (conn->address_type){
6128         case BD_ADDR_TYPE_LE_PUBLIC:
6129         case BD_ADDR_TYPE_LE_RANDOM:
6130             return GAP_CONNECTION_LE;
6131         case BD_ADDR_TYPE_SCO:
6132             return GAP_CONNECTION_SCO;
6133         case BD_ADDR_TYPE_ACL:
6134             return GAP_CONNECTION_ACL;
6135         default:
6136             return GAP_CONNECTION_INVALID;
6137     }
6138 }
6139 
6140 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
6141     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6142     if (!conn) return HCI_ROLE_INVALID;
6143     return (hci_role_t) conn->role;
6144 }
6145 
6146 
6147 #ifdef ENABLE_CLASSIC
6148 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
6149     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6150     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6151     conn->request_role = role;
6152     hci_run();
6153     return ERROR_CODE_SUCCESS;
6154 }
6155 #endif
6156 
6157 #ifdef ENABLE_BLE
6158 
6159 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){
6160     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6161     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6162 
6163     conn->le_phy_update_all_phys    = all_phys;
6164     conn->le_phy_update_tx_phys     = tx_phys;
6165     conn->le_phy_update_rx_phys     = rx_phys;
6166     conn->le_phy_update_phy_options = phy_options;
6167 
6168     hci_run();
6169 
6170     return 0;
6171 }
6172 
6173 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6174     // check if already in list
6175     btstack_linked_list_iterator_t it;
6176     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6177     while (btstack_linked_list_iterator_has_next(&it)) {
6178         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
6179         if (entry->address_type != address_type) {
6180             continue;
6181         }
6182         if (memcmp(entry->address, address, 6) != 0) {
6183             continue;
6184         }
6185 		// disallow if already scheduled to add
6186 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
6187 			return ERROR_CODE_COMMAND_DISALLOWED;
6188 		}
6189 		// still on controller, but scheduled to remove -> re-add
6190 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
6191 		return ERROR_CODE_SUCCESS;
6192     }
6193     // alloc and add to list
6194     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
6195     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
6196     entry->address_type = address_type;
6197     (void)memcpy(entry->address, address, 6);
6198     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
6199     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
6200     return ERROR_CODE_SUCCESS;
6201 }
6202 
6203 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6204     btstack_linked_list_iterator_t it;
6205     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6206     while (btstack_linked_list_iterator_has_next(&it)){
6207         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6208         if (entry->address_type != address_type) {
6209             continue;
6210         }
6211         if (memcmp(entry->address, address, 6) != 0) {
6212             continue;
6213         }
6214         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6215             // remove from controller if already present
6216             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6217         }  else {
6218             // directly remove entry from whitelist
6219             btstack_linked_list_iterator_remove(&it);
6220             btstack_memory_whitelist_entry_free(entry);
6221         }
6222         return ERROR_CODE_SUCCESS;
6223     }
6224     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6225 }
6226 
6227 static void hci_whitelist_clear(void){
6228     btstack_linked_list_iterator_t it;
6229     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6230     while (btstack_linked_list_iterator_has_next(&it)){
6231         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6232         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6233             // remove from controller if already present
6234             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6235             continue;
6236         }
6237         // directly remove entry from whitelist
6238         btstack_linked_list_iterator_remove(&it);
6239         btstack_memory_whitelist_entry_free(entry);
6240     }
6241 }
6242 
6243 /**
6244  * @brief Clear Whitelist
6245  * @returns 0 if ok
6246  */
6247 uint8_t gap_whitelist_clear(void){
6248     hci_whitelist_clear();
6249     hci_run();
6250     return ERROR_CODE_SUCCESS;
6251 }
6252 
6253 /**
6254  * @brief Add Device to Whitelist
6255  * @param address_typ
6256  * @param address
6257  * @returns 0 if ok
6258  */
6259 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6260     uint8_t status = hci_whitelist_add(address_type, address);
6261     if (status){
6262         return status;
6263     }
6264     hci_run();
6265     return ERROR_CODE_SUCCESS;
6266 }
6267 
6268 /**
6269  * @brief Remove Device from Whitelist
6270  * @param address_typ
6271  * @param address
6272  * @returns 0 if ok
6273  */
6274 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6275     uint8_t status = hci_whitelist_remove(address_type, address);
6276     if (status){
6277         return status;
6278     }
6279     hci_run();
6280     return ERROR_CODE_SUCCESS;
6281 }
6282 
6283 #ifdef ENABLE_LE_CENTRAL
6284 /**
6285  *  @brief Connect with Whitelist
6286  *  @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
6287  *  @returns - if ok
6288  */
6289 uint8_t gap_connect_with_whitelist(void){
6290     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6291         return ERROR_CODE_COMMAND_DISALLOWED;
6292     }
6293     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6294     hci_run();
6295     return ERROR_CODE_SUCCESS;
6296 }
6297 
6298 /**
6299  * @brief Auto Connection Establishment - Start Connecting to device
6300  * @param address_typ
6301  * @param address
6302  * @returns 0 if ok
6303  */
6304 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
6305     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6306         return ERROR_CODE_COMMAND_DISALLOWED;
6307     }
6308 
6309     uint8_t status = hci_whitelist_add(address_type, address);
6310     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
6311         return status;
6312     }
6313 
6314     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6315 
6316     hci_run();
6317     return ERROR_CODE_SUCCESS;
6318 }
6319 
6320 /**
6321  * @brief Auto Connection Establishment - Stop Connecting to device
6322  * @param address_typ
6323  * @param address
6324  * @returns 0 if ok
6325  */
6326 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
6327     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6328         return ERROR_CODE_COMMAND_DISALLOWED;
6329     }
6330 
6331     hci_whitelist_remove(address_type, address);
6332     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
6333         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6334     }
6335     hci_run();
6336     return 0;
6337 }
6338 
6339 /**
6340  * @brief Auto Connection Establishment - Stop everything
6341  * @note  Convenience function to stop all active auto connection attempts
6342  */
6343 uint8_t gap_auto_connection_stop_all(void){
6344     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
6345         return ERROR_CODE_COMMAND_DISALLOWED;
6346     }
6347     hci_whitelist_clear();
6348     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6349     hci_run();
6350     return ERROR_CODE_SUCCESS;
6351 }
6352 
6353 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
6354     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6355     if (!conn) return 0;
6356     return conn->le_connection_interval;
6357 }
6358 #endif
6359 #endif
6360 
6361 #ifdef ENABLE_CLASSIC
6362 /**
6363  * @brief Set Extended Inquiry Response data
6364  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
6365  * @note has to be done before stack starts up
6366  */
6367 void gap_set_extended_inquiry_response(const uint8_t * data){
6368     hci_stack->eir_data = data;
6369     hci_stack->gap_tasks |= GAP_TASK_SET_EIR_DATA;
6370     hci_run();
6371 }
6372 
6373 /**
6374  * @brief Start GAP Classic Inquiry
6375  * @param duration in 1.28s units
6376  * @return 0 if ok
6377  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
6378  */
6379 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
6380     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
6381     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6382     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
6383         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
6384     }
6385     hci_stack->inquiry_state = duration_in_1280ms_units;
6386     hci_run();
6387     return 0;
6388 }
6389 
6390 /**
6391  * @brief Stop GAP Classic Inquiry
6392  * @returns 0 if ok
6393  */
6394 int gap_inquiry_stop(void){
6395     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
6396         // emit inquiry complete event, before it even started
6397         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
6398         hci_emit_event(event, sizeof(event), 1);
6399         return 0;
6400     }
6401     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
6402     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
6403     hci_run();
6404     return 0;
6405 }
6406 
6407 void gap_inquiry_set_lap(uint32_t lap){
6408     hci_stack->inquiry_lap = lap;
6409 }
6410 
6411 
6412 /**
6413  * @brief Remote Name Request
6414  * @param addr
6415  * @param page_scan_repetition_mode
6416  * @param clock_offset only used when bit 15 is set
6417  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
6418  */
6419 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
6420     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6421     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
6422     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
6423     hci_stack->remote_name_clock_offset = clock_offset;
6424     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
6425     hci_run();
6426     return 0;
6427 }
6428 
6429 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
6430     hci_stack->gap_pairing_state = state;
6431     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
6432     hci_run();
6433     return 0;
6434 }
6435 
6436 /**
6437  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
6438  * @param addr
6439  * @param pin_data
6440  * @param pin_len
6441  * @return 0 if ok
6442  */
6443 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
6444     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6445     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
6446     hci_stack->gap_pairing_pin_len = pin_len;
6447     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
6448 }
6449 
6450 /**
6451  * @brief Legacy Pairing Pin Code Response
6452  * @param addr
6453  * @param pin
6454  * @return 0 if ok
6455  */
6456 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
6457     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
6458 }
6459 
6460 /**
6461  * @brief Abort Legacy Pairing
6462  * @param addr
6463  * @param pin
6464  * @return 0 if ok
6465  */
6466 int gap_pin_code_negative(bd_addr_t addr){
6467     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6468     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
6469 }
6470 
6471 /**
6472  * @brief SSP Passkey Response
6473  * @param addr
6474  * @param passkey
6475  * @return 0 if ok
6476  */
6477 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
6478     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6479     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
6480     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
6481 }
6482 
6483 /**
6484  * @brief Abort SSP Passkey Entry/Pairing
6485  * @param addr
6486  * @param pin
6487  * @return 0 if ok
6488  */
6489 int gap_ssp_passkey_negative(const bd_addr_t addr){
6490     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6491     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
6492 }
6493 
6494 /**
6495  * @brief Accept SSP Numeric Comparison
6496  * @param addr
6497  * @param passkey
6498  * @return 0 if ok
6499  */
6500 int gap_ssp_confirmation_response(const bd_addr_t addr){
6501     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6502     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
6503 }
6504 
6505 /**
6506  * @brief Abort SSP Numeric Comparison/Pairing
6507  * @param addr
6508  * @param pin
6509  * @return 0 if ok
6510  */
6511 int gap_ssp_confirmation_negative(const bd_addr_t addr){
6512     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6513     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
6514 }
6515 
6516 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
6517 
6518 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
6519     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6520     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6521     connectionSetAuthenticationFlags(conn, flag);
6522     hci_run();
6523     return ERROR_CODE_SUCCESS;
6524 }
6525 
6526 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
6527     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6528 }
6529 
6530 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
6531     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6532 }
6533 #endif
6534 
6535 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6536 /**
6537  * @brief Report Remote OOB Data
6538  * @param bd_addr
6539  * @param c_192 Simple Pairing Hash C derived from P-192 public key
6540  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
6541  * @param c_256 Simple Pairing Hash C derived from P-256 public key
6542  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
6543  */
6544 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){
6545     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6546     if (connection == NULL) {
6547         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6548     }
6549     connection->classic_oob_c_192 = c_192;
6550     connection->classic_oob_r_192 = r_192;
6551 
6552     // ignore P-256 if not supported by us
6553     if (hci_stack->secure_connections_active){
6554         connection->classic_oob_c_256 = c_256;
6555         connection->classic_oob_r_256 = r_256;
6556     }
6557 
6558     return ERROR_CODE_SUCCESS;
6559 }
6560 /**
6561  * @brief Generate new OOB data
6562  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
6563  */
6564 void gap_ssp_generate_oob_data(void){
6565     hci_stack->classic_read_local_oob_data = true;
6566     hci_run();
6567 }
6568 
6569 #endif
6570 
6571 /**
6572  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
6573  * @param inquiry_mode see bluetooth_defines.h
6574  */
6575 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
6576     hci_stack->inquiry_mode = inquiry_mode;
6577 }
6578 
6579 /**
6580  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
6581  */
6582 void hci_set_sco_voice_setting(uint16_t voice_setting){
6583     hci_stack->sco_voice_setting = voice_setting;
6584 }
6585 
6586 /**
6587  * @brief Get SCO Voice Setting
6588  * @return current voice setting
6589  */
6590 uint16_t hci_get_sco_voice_setting(void){
6591     return hci_stack->sco_voice_setting;
6592 }
6593 
6594 static int hci_have_usb_transport(void){
6595     if (!hci_stack->hci_transport) return 0;
6596     const char * transport_name = hci_stack->hci_transport->name;
6597     if (!transport_name) return 0;
6598     return (transport_name[0] == 'H') && (transport_name[1] == '2');
6599 }
6600 
6601 /** @brief Get SCO packet length for current SCO Voice setting
6602  *  @note  Using SCO packets of the exact length is required for USB transfer
6603  *  @return Length of SCO packets in bytes (not audio frames)
6604  */
6605 uint16_t hci_get_sco_packet_length(void){
6606     uint16_t sco_packet_length = 0;
6607 
6608 #ifdef ENABLE_SCO_OVER_HCI
6609     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6610     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6611 
6612     if (hci_have_usb_transport()){
6613         // see Core Spec for H2 USB Transfer.
6614         // 3 byte SCO header + 24 bytes per connection
6615         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
6616         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
6617     } else {
6618         // 3 byte SCO header + SCO packet size over the air (60 bytes)
6619         sco_packet_length = 3 + 60 * multiplier;
6620         // assert that it still fits inside an SCO buffer
6621         if (sco_packet_length > hci_stack->sco_data_packet_length){
6622             sco_packet_length = 3 + 60;
6623         }
6624     }
6625 #endif
6626 
6627 #ifdef HAVE_SCO_TRANSPORT
6628     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6629     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6630     sco_packet_length = 3 + 60 * multiplier;
6631 #endif
6632     return sco_packet_length;
6633 }
6634 
6635 /**
6636 * @brief Sets the master/slave policy
6637 * @param policy (0: attempt to become master, 1: let connecting device decide)
6638 */
6639 void hci_set_master_slave_policy(uint8_t policy){
6640     hci_stack->master_slave_policy = policy;
6641 }
6642 
6643 #endif
6644 
6645 HCI_STATE hci_get_state(void){
6646     return hci_stack->state;
6647 }
6648 
6649 #ifdef ENABLE_CLASSIC
6650 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
6651     hci_stack->gap_classic_accept_callback = accept_callback;
6652 }
6653 #endif
6654 
6655 /**
6656  * @brief Set callback for Bluetooth Hardware Error
6657  */
6658 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
6659     hci_stack->hardware_error_callback = fn;
6660 }
6661 
6662 void hci_disconnect_all(void){
6663     btstack_linked_list_iterator_t it;
6664     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6665     while (btstack_linked_list_iterator_has_next(&it)){
6666         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6667         if (con->state == SENT_DISCONNECT) continue;
6668         con->state = SEND_DISCONNECT;
6669     }
6670     hci_run();
6671 }
6672 
6673 uint16_t hci_get_manufacturer(void){
6674     return hci_stack->manufacturer;
6675 }
6676 
6677 #ifdef ENABLE_BLE
6678 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
6679     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
6680     if (!hci_con) return NULL;
6681     return &hci_con->sm_connection;
6682 }
6683 
6684 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
6685 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
6686 #endif
6687 
6688 int gap_encryption_key_size(hci_con_handle_t con_handle){
6689     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6690     if (hci_connection == NULL) return 0;
6691     if (hci_is_le_connection(hci_connection)){
6692 #ifdef ENABLE_BLE
6693         sm_connection_t * sm_conn = &hci_connection->sm_connection;
6694         if (sm_conn->sm_connection_encrypted) {
6695             return sm_conn->sm_actual_encryption_key_size;
6696         }
6697 #endif
6698     } else {
6699 #ifdef ENABLE_CLASSIC
6700         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
6701             return hci_connection->encryption_key_size;
6702         }
6703 #endif
6704     }
6705     return 0;
6706 }
6707 
6708 int gap_authenticated(hci_con_handle_t con_handle){
6709     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6710     if (hci_connection == NULL) return 0;
6711 
6712     switch (hci_connection->address_type){
6713 #ifdef ENABLE_BLE
6714         case BD_ADDR_TYPE_LE_PUBLIC:
6715         case BD_ADDR_TYPE_LE_RANDOM:
6716             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6717             return hci_connection->sm_connection.sm_connection_authenticated;
6718 #endif
6719 #ifdef ENABLE_CLASSIC
6720         case BD_ADDR_TYPE_SCO:
6721         case BD_ADDR_TYPE_ACL:
6722             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
6723 #endif
6724         default:
6725             return 0;
6726     }
6727 }
6728 
6729 int gap_secure_connection(hci_con_handle_t con_handle){
6730     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6731     if (hci_connection == NULL) return 0;
6732 
6733     switch (hci_connection->address_type){
6734 #ifdef ENABLE_BLE
6735         case BD_ADDR_TYPE_LE_PUBLIC:
6736         case BD_ADDR_TYPE_LE_RANDOM:
6737             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6738             return hci_connection->sm_connection.sm_connection_sc;
6739 #endif
6740 #ifdef ENABLE_CLASSIC
6741         case BD_ADDR_TYPE_SCO:
6742         case BD_ADDR_TYPE_ACL:
6743             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
6744 #endif
6745         default:
6746             return 0;
6747     }
6748 }
6749 
6750 bool gap_bonded(hci_con_handle_t con_handle){
6751 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6752 	if (hci_connection == NULL) return 0;
6753 
6754 #ifdef ENABLE_CLASSIC
6755 	link_key_t link_key;
6756 	link_key_type_t link_key_type;
6757 #endif
6758 	switch (hci_connection->address_type){
6759 #ifdef ENABLE_BLE
6760 		case BD_ADDR_TYPE_LE_PUBLIC:
6761 		case BD_ADDR_TYPE_LE_RANDOM:
6762 			return hci_connection->sm_connection.sm_le_db_index >= 0;
6763 #endif
6764 #ifdef ENABLE_CLASSIC
6765 		case BD_ADDR_TYPE_SCO:
6766 		case BD_ADDR_TYPE_ACL:
6767 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
6768 #endif
6769 		default:
6770 			return false;
6771 	}
6772 }
6773 
6774 #ifdef ENABLE_BLE
6775 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
6776     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
6777     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
6778     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
6779     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
6780     return sm_conn->sm_connection_authorization_state;
6781 }
6782 #endif
6783 
6784 #ifdef ENABLE_CLASSIC
6785 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){
6786     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6787     if (!conn) return GAP_CONNECTION_INVALID;
6788     conn->sniff_min_interval = sniff_min_interval;
6789     conn->sniff_max_interval = sniff_max_interval;
6790     conn->sniff_attempt = sniff_attempt;
6791     conn->sniff_timeout = sniff_timeout;
6792     hci_run();
6793     return 0;
6794 }
6795 
6796 /**
6797  * @brief Exit Sniff mode
6798  * @param con_handle
6799  @ @return 0 if ok
6800  */
6801 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
6802     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6803     if (!conn) return GAP_CONNECTION_INVALID;
6804     conn->sniff_min_interval = 0xffff;
6805     hci_run();
6806     return 0;
6807 }
6808 
6809 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){
6810     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6811     if (!conn) return GAP_CONNECTION_INVALID;
6812     conn->sniff_subrating_max_latency = max_latency;
6813     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
6814     conn->sniff_subrating_min_local_timeout = min_local_timeout;
6815     hci_run();
6816     return ERROR_CODE_SUCCESS;
6817 }
6818 
6819 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){
6820     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6821     if (!conn) return GAP_CONNECTION_INVALID;
6822     conn->qos_service_type = service_type;
6823     conn->qos_token_rate = token_rate;
6824     conn->qos_peak_bandwidth = peak_bandwidth;
6825     conn->qos_latency = latency;
6826     conn->qos_delay_variation = delay_variation;
6827     hci_run();
6828     return ERROR_CODE_SUCCESS;
6829 }
6830 
6831 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
6832     hci_stack->new_page_scan_interval = page_scan_interval;
6833     hci_stack->new_page_scan_window = page_scan_window;
6834     hci_run();
6835 }
6836 
6837 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
6838     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
6839     hci_run();
6840 }
6841 
6842 #endif
6843 
6844 void hci_halting_defer(void){
6845     if (hci_stack->state != HCI_STATE_HALTING) return;
6846     switch (hci_stack->substate){
6847         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
6848         case HCI_HALTING_CLOSE:
6849             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
6850             break;
6851         default:
6852             break;
6853     }
6854 }
6855 
6856 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6857 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
6858     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6859     if (le_device_db_index >= le_device_db_max_count()) return;
6860     uint8_t offset = le_device_db_index >> 3;
6861     uint8_t mask = 1 << (le_device_db_index & 7);
6862     hci_stack->le_resolving_list_add_entries[offset] |= mask;
6863     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6864     	// note: go back to remove entries, otherwise, a remove + add will skip the add
6865         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6866     }
6867 }
6868 
6869 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
6870 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6871 	if (le_device_db_index >= le_device_db_max_count()) return;
6872 	uint8_t offset = le_device_db_index >> 3;
6873 	uint8_t mask = 1 << (le_device_db_index & 7);
6874 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
6875 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6876 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6877 	}
6878 }
6879 
6880 uint8_t gap_load_resolving_list_from_le_device_db(void){
6881 	if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) {
6882 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
6883 	}
6884 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
6885 		// restart le resolving list update
6886 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6887 	}
6888 	return ERROR_CODE_SUCCESS;
6889 }
6890 #endif
6891 
6892 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
6893 void hci_setup_test_connections_fuzz(void){
6894     hci_connection_t * conn;
6895 
6896     // default address: 66:55:44:33:00:01
6897     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
6898 
6899     // setup Controller info
6900     hci_stack->num_cmd_packets = 255;
6901     hci_stack->acl_packets_total_num = 255;
6902 
6903     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
6904     addr[5] = 0x01;
6905     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6906     conn->con_handle = addr[5];
6907     conn->role  = HCI_ROLE_SLAVE;
6908     conn->state = RECEIVED_CONNECTION_REQUEST;
6909     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6910 
6911     // setup incoming Classic SCO connection with con handle 0x0002
6912     addr[5] = 0x02;
6913     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6914     conn->con_handle = addr[5];
6915     conn->role  = HCI_ROLE_SLAVE;
6916     conn->state = RECEIVED_CONNECTION_REQUEST;
6917     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6918 
6919     // setup ready Classic ACL connection with con handle 0x0003
6920     addr[5] = 0x03;
6921     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6922     conn->con_handle = addr[5];
6923     conn->role  = HCI_ROLE_SLAVE;
6924     conn->state = OPEN;
6925     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6926 
6927     // setup ready Classic SCO connection with con handle 0x0004
6928     addr[5] = 0x04;
6929     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6930     conn->con_handle = addr[5];
6931     conn->role  = HCI_ROLE_SLAVE;
6932     conn->state = OPEN;
6933     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6934 
6935     // setup ready LE ACL connection with con handle 0x005 and public address
6936     addr[5] = 0x05;
6937     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
6938     conn->con_handle = addr[5];
6939     conn->role  = HCI_ROLE_SLAVE;
6940     conn->state = OPEN;
6941     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6942     conn->sm_connection.sm_connection_encrypted = 1;
6943 }
6944 
6945 void hci_free_connections_fuzz(void){
6946     btstack_linked_list_iterator_t it;
6947     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6948     while (btstack_linked_list_iterator_has_next(&it)){
6949         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6950         btstack_linked_list_iterator_remove(&it);
6951         btstack_memory_hci_connection_free(con);
6952     }
6953 }
6954 void hci_simulate_working_fuzz(void){
6955     hci_init_done();
6956     hci_stack->num_cmd_packets = 255;
6957 }
6958 #endif
6959