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