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