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