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