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