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