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