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