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