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