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