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