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