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