xref: /btstack/src/hci.c (revision 63c0b2fd6d47826d696ed89a933941c3cab4e3ad)
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             hci_event_link_key_request_get_bd_addr(packet, addr);
2831             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2832             if (!conn) break;
2833 
2834             // lookup link key in db if not cached
2835             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
2836                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
2837             }
2838 
2839             // response sent by hci_run()
2840             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
2841 #endif
2842             break;
2843 
2844         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2845             hci_event_link_key_request_get_bd_addr(packet, addr);
2846             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2847             if (!conn) break;
2848 
2849             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
2850 
2851             // CVE-2020-26555: ignore NULL link key
2852             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
2853             if (btstack_is_null(&packet[8], 16)) break;
2854 
2855             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2856             // Change Connection Encryption keeps link key type
2857             if (link_key_type != CHANGED_COMBINATION_KEY){
2858                 conn->link_key_type = link_key_type;
2859             }
2860 
2861             // cache link key. link keys stored in little-endian format for legacy reasons
2862             memcpy(&conn->link_key, &packet[8], 16);
2863 
2864             // only store link key:
2865             // - if bondable enabled
2866             if (hci_stack->bondable == false) break;
2867             // - if security level sufficient
2868             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
2869             // - for SSP, also check if remote side requested bonding as well
2870             if (conn->link_key_type != COMBINATION_KEY){
2871                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2872                 if (!remote_bonding){
2873                     break;
2874                 }
2875             }
2876             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2877             break;
2878         }
2879 
2880         case HCI_EVENT_PIN_CODE_REQUEST:
2881             hci_event_pin_code_request_get_bd_addr(packet, addr);
2882             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2883             if (!conn) break;
2884 
2885             hci_pairing_started(conn, false);
2886             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
2887             if (!hci_stack->bondable ){
2888                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
2889                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
2890                 hci_run();
2891                 return;
2892             }
2893             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
2894             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
2895                 log_info("Level 4 required, but SC not supported -> abort");
2896                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
2897                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2898                 hci_run();
2899                 return;
2900             }
2901             break;
2902 
2903         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
2904             hci_event_io_capability_response_get_bd_addr(packet, addr);
2905             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2906             if (!conn) break;
2907 
2908             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
2909             hci_pairing_started(conn, true);
2910             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
2911             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
2912 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2913             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
2914 #endif
2915             break;
2916 
2917         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2918             hci_event_io_capability_response_get_bd_addr(packet, addr);
2919             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2920             if (!conn) break;
2921 
2922             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
2923             hci_connection_timestamp(conn);
2924             hci_pairing_started(conn, true);
2925             break;
2926 
2927 #ifdef ENABLE_CLASSIC_PAIRING_OOB
2928         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
2929             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
2930             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2931             if (!conn) break;
2932 
2933             hci_connection_timestamp(conn);
2934 
2935             hci_pairing_started(conn, true);
2936 
2937             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
2938             break;
2939 #endif
2940 
2941         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2942             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
2943             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2944             if (!conn) break;
2945             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
2946                 if (hci_stack->ssp_auto_accept){
2947                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
2948                 };
2949             } else {
2950                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2951                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
2952                 // don't forward event to app
2953                 hci_run();
2954                 return;
2955             }
2956             break;
2957 
2958         case HCI_EVENT_USER_PASSKEY_REQUEST:
2959             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
2960             if (hci_stack->ssp_auto_accept){
2961                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
2962             };
2963             break;
2964 
2965         case HCI_EVENT_MODE_CHANGE:
2966             handle = hci_event_mode_change_get_handle(packet);
2967             conn = hci_connection_for_handle(handle);
2968             if (!conn) break;
2969             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2970             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2971             break;
2972 #endif
2973 
2974         case HCI_EVENT_ENCRYPTION_CHANGE:
2975             handle = hci_event_encryption_change_get_connection_handle(packet);
2976             conn = hci_connection_for_handle(handle);
2977             if (!conn) break;
2978             if (hci_event_encryption_change_get_status(packet) == 0u) {
2979                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
2980                 if (encryption_enabled){
2981                     if (hci_is_le_connection(conn)){
2982                         // For LE, we accept connection as encrypted
2983                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2984                     }
2985 #ifdef ENABLE_CLASSIC
2986                     else {
2987 
2988                         // dedicated bonding: send result and disconnect
2989                         if (conn->bonding_flags & BONDING_DEDICATED){
2990                             conn->bonding_flags &= ~BONDING_DEDICATED;
2991                             conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2992                             conn->bonding_status = packet[2];
2993                             break;
2994                         }
2995 
2996                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
2997                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type) != 0;
2998                         bool connected_uses_aes_ccm = encryption_enabled == 2;
2999                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
3000                             log_info("SC during pairing, but only E0 now -> abort");
3001                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3002                             break;
3003                         }
3004 
3005                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
3006                         if (connected_uses_aes_ccm){
3007                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3008                         }
3009 
3010 #ifdef ENABLE_TESTING_SUPPORT
3011                         // work around for issue with PTS dongle
3012                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3013 #endif
3014 
3015                         if ((hci_stack->local_supported_commands[0] & 0x80) != 0){
3016                             // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
3017                             conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
3018                         } else {
3019                             // if not, pretend everything is perfect
3020                             hci_handle_read_encryption_key_size_complete(conn, 16);
3021                         }
3022                     }
3023 #endif
3024                 } else {
3025                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
3026                 }
3027             }
3028 
3029             break;
3030 
3031 #ifdef ENABLE_CLASSIC
3032         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
3033             handle = hci_event_authentication_complete_get_connection_handle(packet);
3034             conn = hci_connection_for_handle(handle);
3035             if (!conn) break;
3036 
3037             // clear authentication active flag
3038             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
3039             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
3040 
3041             // authenticated only if auth status == 0
3042             if (hci_event_authentication_complete_get_status(packet) == 0){
3043                 // authenticated
3044                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3045 
3046                 // If not already encrypted, start encryption
3047                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
3048                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3049                     break;
3050                 }
3051             }
3052 
3053             // emit updated security level
3054             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
3055             break;
3056 
3057         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3058             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3059             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3060             if (!conn) break;
3061 
3062             // treat successfully paired connection as authenticated
3063             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
3064                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3065             }
3066 
3067             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
3068             break;
3069 #endif
3070 
3071         // HCI_EVENT_DISCONNECTION_COMPLETE
3072         // has been split, to first notify stack before shutting connection down
3073         // see end of function, too.
3074         case HCI_EVENT_DISCONNECTION_COMPLETE:
3075             if (packet[2]) break;   // status != 0
3076             handle = little_endian_read_16(packet, 3);
3077             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
3078             if (hci_stack->acl_fragmentation_total_size > 0u) {
3079                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3080                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
3081                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
3082                     hci_stack->acl_fragmentation_total_size = 0;
3083                     hci_stack->acl_fragmentation_pos = 0;
3084                     if (release_buffer){
3085                         hci_release_packet_buffer();
3086                     }
3087                 }
3088             }
3089 
3090             conn = hci_connection_for_handle(handle);
3091             if (!conn) break;
3092 #ifdef ENABLE_CLASSIC
3093             // pairing failed if it was ongoing
3094             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
3095 #endif
3096 
3097             // emit dedicatd bonding event
3098             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3099                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3100             }
3101 
3102             // mark connection for shutdown, stop timers, reset state
3103             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3104             hci_connection_stop_timer(conn);
3105             hci_connection_init(conn);
3106 
3107 #ifdef ENABLE_BLE
3108 #ifdef ENABLE_LE_PERIPHERAL
3109             // re-enable advertisements for le connections if active
3110             if (hci_is_le_connection(conn)){
3111                 hci_update_advertisements_enabled_for_current_roles();
3112             }
3113 #endif
3114 #endif
3115             break;
3116 
3117         case HCI_EVENT_HARDWARE_ERROR:
3118             log_error("Hardware Error: 0x%02x", packet[2]);
3119             if (hci_stack->hardware_error_callback){
3120                 (*hci_stack->hardware_error_callback)(packet[2]);
3121             } else {
3122                 // if no special requests, just reboot stack
3123                 hci_power_control_off();
3124                 hci_power_control_on();
3125             }
3126             break;
3127 
3128 #ifdef ENABLE_CLASSIC
3129         case HCI_EVENT_ROLE_CHANGE:
3130             if (packet[2]) break;   // status != 0
3131             reverse_bd_addr(&packet[3], addr);
3132             addr_type = BD_ADDR_TYPE_ACL;
3133             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3134             if (!conn) break;
3135             conn->role = packet[9];
3136             break;
3137 #endif
3138 
3139         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3140             // release packet buffer only for asynchronous transport and if there are not further fragements
3141             if (hci_transport_synchronous()) {
3142                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
3143                 return; // instead of break: to avoid re-entering hci_run()
3144             }
3145             hci_stack->acl_fragmentation_tx_active = 0;
3146             if (hci_stack->acl_fragmentation_total_size) break;
3147             hci_release_packet_buffer();
3148 
3149             // L2CAP receives this event via the hci_emit_event below
3150 
3151 #ifdef ENABLE_CLASSIC
3152             // For SCO, we do the can_send_now_check here
3153             hci_notify_if_sco_can_send_now();
3154 #endif
3155             break;
3156 
3157 #ifdef ENABLE_CLASSIC
3158         case HCI_EVENT_SCO_CAN_SEND_NOW:
3159             // For SCO, we do the can_send_now_check here
3160             hci_stack->sco_can_send_now = true;
3161             hci_notify_if_sco_can_send_now();
3162             return;
3163 
3164         // explode inquriy results for easier consumption
3165         case HCI_EVENT_INQUIRY_RESULT:
3166         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3167         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3168             gap_inquiry_explode(packet, size);
3169             break;
3170 #endif
3171 
3172 #ifdef ENABLE_BLE
3173         case HCI_EVENT_LE_META:
3174             switch (packet[2]){
3175 #ifdef ENABLE_LE_CENTRAL
3176                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
3177                     // log_info("advertising report received");
3178                     if (!hci_stack->le_scanning_enabled) break;
3179                     le_handle_advertisement_report(packet, size);
3180                     break;
3181 #endif
3182                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3183 					event_handle_le_connection_complete(packet);
3184                     break;
3185 
3186                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3187                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3188                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3189                     conn = hci_connection_for_handle(handle);
3190                     if (!conn) break;
3191                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3192                     break;
3193 
3194                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
3195                     // connection
3196                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
3197                     conn = hci_connection_for_handle(handle);
3198                     if (conn) {
3199                         // read arguments
3200                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
3201                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
3202                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
3203                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
3204 
3205                         // validate against current connection parameter range
3206                         le_connection_parameter_range_t existing_range;
3207                         gap_get_connection_parameter_range(&existing_range);
3208                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3209                         if (update_parameter){
3210                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
3211                             conn->le_conn_interval_min = le_conn_interval_min;
3212                             conn->le_conn_interval_max = le_conn_interval_max;
3213                             conn->le_conn_latency = le_conn_latency;
3214                             conn->le_supervision_timeout = le_supervision_timeout;
3215                         } else {
3216                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
3217                         }
3218                     }
3219                     break;
3220 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3221                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
3222                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
3223                     conn = hci_connection_for_handle(handle);
3224                     if (conn) {
3225                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
3226                     }
3227                     break;
3228 #endif
3229                 default:
3230                     break;
3231             }
3232             break;
3233 #endif
3234         case HCI_EVENT_VENDOR_SPECIFIC:
3235             // Vendor specific commands often create vendor specific event instead of num completed packets
3236             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
3237             switch (hci_stack->manufacturer){
3238                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
3239                     hci_stack->num_cmd_packets = 1;
3240                     break;
3241                 default:
3242                     break;
3243             }
3244             break;
3245         default:
3246             break;
3247     }
3248 
3249     handle_event_for_current_stack_state(packet, size);
3250 
3251     // notify upper stack
3252 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
3253 
3254     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
3255     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
3256 		handle = little_endian_read_16(packet, 3);
3257 		hci_connection_t * aConn = hci_connection_for_handle(handle);
3258 		// discard connection if app did not trigger a reconnect in the event handler
3259 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
3260 			hci_shutdown_connection(aConn);
3261 		}
3262     }
3263 
3264 	// execute main loop
3265 	hci_run();
3266 }
3267 
3268 #ifdef ENABLE_CLASSIC
3269 
3270 #ifdef ENABLE_SCO_OVER_HCI
3271 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
3272 static void sco_schedule_tx(hci_connection_t * conn);
3273 
3274 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
3275     log_debug("SCO TX Timeout");
3276     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
3277     hci_connection_t * conn = hci_connection_for_handle(con_handle);
3278     if (!conn) return;
3279 
3280     // trigger send
3281     conn->sco_tx_ready = 1;
3282     // extra packet if CVSD but SCO buffer is too short
3283     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
3284         conn->sco_tx_ready++;
3285     }
3286     hci_notify_if_sco_can_send_now();
3287 }
3288 
3289 
3290 #define SCO_TX_AFTER_RX_MS (6)
3291 
3292 static void sco_schedule_tx(hci_connection_t * conn){
3293 
3294     uint32_t now = btstack_run_loop_get_time_ms();
3295     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
3296     int time_delta_ms = sco_tx_ms - now;
3297 
3298     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
3299 
3300     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
3301     btstack_run_loop_remove_timer(timer);
3302     btstack_run_loop_set_timer(timer, time_delta_ms);
3303     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
3304     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
3305     btstack_run_loop_add_timer(timer);
3306 }
3307 #endif
3308 
3309 static void sco_handler(uint8_t * packet, uint16_t size){
3310     // lookup connection struct
3311     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
3312     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
3313     if (!conn) return;
3314 
3315 #ifdef ENABLE_SCO_OVER_HCI
3316     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
3317     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
3318         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
3319             packet[2] = 0x3c;
3320             memmove(&packet[3], &packet[23], 63);
3321             size = 63;
3322         }
3323     }
3324 
3325     if (hci_have_usb_transport()){
3326         // Nothing to do
3327     } else {
3328         // 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);
3329         if (hci_stack->synchronous_flow_control_enabled == 0){
3330             uint32_t now = btstack_run_loop_get_time_ms();
3331 
3332             if (!conn->sco_rx_valid){
3333                 // ignore first 10 packets
3334                 conn->sco_rx_count++;
3335                 // log_debug("sco rx count %u", conn->sco_rx_count);
3336                 if (conn->sco_rx_count == 10) {
3337                     // use first timestamp as is and pretent it just started
3338                     conn->sco_rx_ms = now;
3339                     conn->sco_rx_valid = 1;
3340                     conn->sco_rx_count = 0;
3341                     sco_schedule_tx(conn);
3342                 }
3343             } else {
3344                 // track expected arrival timme
3345                 conn->sco_rx_count++;
3346                 conn->sco_rx_ms += 7;
3347                 int delta = (int32_t) (now - conn->sco_rx_ms);
3348                 if (delta > 0){
3349                     conn->sco_rx_ms++;
3350                 }
3351                 // log_debug("sco rx %u", conn->sco_rx_ms);
3352                 sco_schedule_tx(conn);
3353             }
3354         }
3355     }
3356 #endif
3357 
3358     // deliver to app
3359     if (hci_stack->sco_packet_handler) {
3360         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
3361     }
3362 
3363 #ifdef HAVE_SCO_TRANSPORT
3364     // We can send one packet for each received packet
3365     conn->sco_tx_ready++;
3366     hci_notify_if_sco_can_send_now();
3367 #endif
3368 
3369 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3370     conn->num_packets_completed++;
3371     hci_stack->host_completed_packets = 1;
3372     hci_run();
3373 #endif
3374 }
3375 #endif
3376 
3377 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
3378     hci_dump_packet(packet_type, 1, packet, size);
3379     switch (packet_type) {
3380         case HCI_EVENT_PACKET:
3381             event_handler(packet, size);
3382             break;
3383         case HCI_ACL_DATA_PACKET:
3384             acl_handler(packet, size);
3385             break;
3386 #ifdef ENABLE_CLASSIC
3387         case HCI_SCO_DATA_PACKET:
3388             sco_handler(packet, size);
3389             break;
3390 #endif
3391         default:
3392             break;
3393     }
3394 }
3395 
3396 /**
3397  * @brief Add event packet handler.
3398  */
3399 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3400     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3401 }
3402 
3403 
3404 /** Register HCI packet handlers */
3405 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3406     hci_stack->acl_packet_handler = handler;
3407 }
3408 
3409 #ifdef ENABLE_CLASSIC
3410 /**
3411  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
3412  */
3413 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
3414     hci_stack->sco_packet_handler = handler;
3415 }
3416 #endif
3417 
3418 static void hci_state_reset(void){
3419     // no connections yet
3420     hci_stack->connections = NULL;
3421 
3422     // keep discoverable/connectable as this has been requested by the client(s)
3423     // hci_stack->discoverable = 0;
3424     // hci_stack->connectable = 0;
3425     // hci_stack->bondable = 1;
3426     // hci_stack->own_addr_type = 0;
3427 
3428     // buffer is free
3429     hci_stack->hci_packet_buffer_reserved = false;
3430 
3431     // no pending cmds
3432     hci_stack->decline_reason = 0;
3433     hci_stack->new_scan_enable_value = 0xff;
3434 
3435     hci_stack->secure_connections_active = false;
3436 
3437 #ifdef ENABLE_CLASSIC
3438     hci_stack->new_page_scan_interval = 0xffff;
3439     hci_stack->new_page_scan_window = 0xffff;
3440     hci_stack->new_page_scan_type = 0xff;
3441     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
3442     hci_stack->gap_tasks =
3443             GAP_TASK_SET_DEFAULT_LINK_POLICY |
3444             GAP_TASK_SET_CLASS_OF_DEVICE |
3445             GAP_TASK_SET_LOCAL_NAME |
3446             GAP_TASK_SET_EIR_DATA;
3447 #endif
3448 
3449 #ifdef ENABLE_CLASSIC_PAIRING_OOB
3450     hci_stack->classic_read_local_oob_data = true;
3451     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
3452 #endif
3453 
3454     // LE
3455 #ifdef ENABLE_BLE
3456     memset(hci_stack->le_random_address, 0, 6);
3457     hci_stack->le_random_address_set = 0;
3458 #endif
3459 #ifdef ENABLE_LE_CENTRAL
3460     hci_stack->le_scanning_active  = false;
3461     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3462     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3463     hci_stack->le_whitelist_capacity = 0;
3464 #endif
3465 #ifdef ENABLE_LE_PERIPHERAL
3466     hci_stack->le_advertisements_active = false;
3467     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PARAMS_SET) != 0){
3468         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3469     }
3470     if (hci_stack->le_advertisements_data != NULL){
3471         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3472     }
3473 #endif
3474 }
3475 
3476 #ifdef ENABLE_CLASSIC
3477 /**
3478  * @brief Configure Bluetooth hardware control. Has to be called before power on.
3479  */
3480 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
3481     // store and open remote device db
3482     hci_stack->link_key_db = link_key_db;
3483     if (hci_stack->link_key_db) {
3484         hci_stack->link_key_db->open();
3485     }
3486 }
3487 #endif
3488 
3489 void hci_init(const hci_transport_t *transport, const void *config){
3490 
3491 #ifdef HAVE_MALLOC
3492     if (!hci_stack) {
3493         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
3494     }
3495 #else
3496     hci_stack = &hci_stack_static;
3497 #endif
3498     memset(hci_stack, 0, sizeof(hci_stack_t));
3499 
3500     // reference to use transport layer implementation
3501     hci_stack->hci_transport = transport;
3502 
3503     // reference to used config
3504     hci_stack->config = config;
3505 
3506     // setup pointer for outgoing packet buffer
3507     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
3508 
3509     // max acl payload size defined in config.h
3510     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
3511 
3512     // register packet handlers with transport
3513     transport->register_packet_handler(&packet_handler);
3514 
3515     hci_stack->state = HCI_STATE_OFF;
3516 
3517     // class of device
3518     hci_stack->class_of_device = 0x007a020c; // Smartphone
3519 
3520     // bondable by default
3521     hci_stack->bondable = 1;
3522 
3523 #ifdef ENABLE_CLASSIC
3524     // classic name
3525     hci_stack->local_name = default_classic_name;
3526 
3527     // Master slave policy
3528     hci_stack->master_slave_policy = 1;
3529 
3530     // Allow Role Switch
3531     hci_stack->allow_role_switch = 1;
3532 
3533     // Default / minimum security level = 2
3534     hci_stack->gap_security_level = LEVEL_2;
3535 
3536     // Default Security Mode 4
3537     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
3538 
3539     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3540     hci_stack->gap_required_encyrption_key_size = 7;
3541 
3542     // Link Supervision Timeout
3543     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
3544 
3545 #endif
3546 
3547     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
3548     hci_stack->ssp_enable = 1;
3549     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
3550     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
3551     hci_stack->ssp_auto_accept = 1;
3552 
3553     // Secure Connections: enable (requires support from Controller)
3554     hci_stack->secure_connections_enable = true;
3555 
3556     // voice setting - signed 16 bit pcm data with CVSD over the air
3557     hci_stack->sco_voice_setting = 0x60;
3558 
3559 #ifdef ENABLE_LE_CENTRAL
3560     // connection parameter to use for outgoing connections
3561     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3562     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3563     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3564     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3565     hci_stack->le_connection_latency      = 4;         // 4
3566     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3567     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3568     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
3569 
3570     // default LE Scanning
3571     hci_stack->le_scan_type     =   0x1; // active
3572     hci_stack->le_scan_interval = 0x1e0; // 300 ms
3573     hci_stack->le_scan_window   =  0x30; //  30 ms
3574 #endif
3575 
3576 #ifdef ENABLE_LE_PERIPHERAL
3577     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
3578 #endif
3579 
3580     // connection parameter range used to answer connection parameter update requests in l2cap
3581     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3582     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3583     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3584     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3585     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3586     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3587 
3588     hci_state_reset();
3589 }
3590 
3591 void hci_deinit(void){
3592 #ifdef HAVE_MALLOC
3593     if (hci_stack) {
3594         free(hci_stack);
3595     }
3596 #endif
3597     hci_stack = NULL;
3598 
3599 #ifdef ENABLE_CLASSIC
3600     disable_l2cap_timeouts = 0;
3601 #endif
3602 }
3603 
3604 /**
3605  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
3606  */
3607 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
3608     hci_stack->chipset = chipset_driver;
3609 
3610     // reset chipset driver - init is also called on power_up
3611     if (hci_stack->chipset && hci_stack->chipset->init){
3612         hci_stack->chipset->init(hci_stack->config);
3613     }
3614 }
3615 
3616 /**
3617  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3618  */
3619 void hci_set_control(const btstack_control_t *hardware_control){
3620     // references to used control implementation
3621     hci_stack->control = hardware_control;
3622     // init with transport config
3623     hardware_control->init(hci_stack->config);
3624 }
3625 
3626 void hci_close(void){
3627 
3628 #ifdef ENABLE_CLASSIC
3629     // close remote device db
3630     if (hci_stack->link_key_db) {
3631         hci_stack->link_key_db->close();
3632     }
3633 #endif
3634 
3635     btstack_linked_list_iterator_t lit;
3636     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
3637     while (btstack_linked_list_iterator_has_next(&lit)){
3638         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
3639         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
3640         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
3641         hci_shutdown_connection(connection);
3642     }
3643 
3644     hci_power_control(HCI_POWER_OFF);
3645 
3646 #ifdef HAVE_MALLOC
3647     free(hci_stack);
3648 #endif
3649     hci_stack = NULL;
3650 }
3651 
3652 #ifdef HAVE_SCO_TRANSPORT
3653 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3654     hci_stack->sco_transport = sco_transport;
3655     sco_transport->register_packet_handler(&packet_handler);
3656 }
3657 #endif
3658 
3659 #ifdef ENABLE_CLASSIC
3660 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3661     // validate ranage and set
3662     if (encryption_key_size < 7)  return;
3663     if (encryption_key_size > 16) return;
3664     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3665 }
3666 
3667 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
3668     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
3669         hci_stack->gap_security_mode = security_mode;
3670         return ERROR_CODE_SUCCESS;
3671     } else {
3672         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3673     }
3674 }
3675 
3676 gap_security_mode_t gap_get_security_mode(void){
3677     return hci_stack->gap_security_mode;
3678 }
3679 
3680 void gap_set_security_level(gap_security_level_t security_level){
3681     hci_stack->gap_security_level = security_level;
3682 }
3683 
3684 gap_security_level_t gap_get_security_level(void){
3685     if (hci_stack->gap_secure_connections_only_mode){
3686         return LEVEL_4;
3687     }
3688     return hci_stack->gap_security_level;
3689 }
3690 
3691 void gap_set_minimal_service_security_level(gap_security_level_t security_level){
3692     hci_stack->gap_minimal_service_security_level = security_level;
3693 }
3694 
3695 void gap_set_secure_connections_only_mode(bool enable){
3696     hci_stack->gap_secure_connections_only_mode = enable;
3697 }
3698 
3699 bool gap_get_secure_connections_only_mode(void){
3700     return hci_stack->gap_secure_connections_only_mode;
3701 }
3702 #endif
3703 
3704 #ifdef ENABLE_CLASSIC
3705 void gap_set_class_of_device(uint32_t class_of_device){
3706     hci_stack->class_of_device = class_of_device;
3707     hci_stack->gap_tasks |= GAP_TASK_SET_CLASS_OF_DEVICE;
3708     hci_run();
3709 }
3710 
3711 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3712     hci_stack->default_link_policy_settings = default_link_policy_settings;
3713     hci_stack->gap_tasks |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
3714     hci_run();
3715 }
3716 
3717 void gap_set_allow_role_switch(bool allow_role_switch){
3718     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3719 }
3720 
3721 uint8_t hci_get_allow_role_switch(void){
3722     return  hci_stack->allow_role_switch;
3723 }
3724 
3725 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
3726     hci_stack->link_supervision_timeout = link_supervision_timeout;
3727 }
3728 
3729 void hci_disable_l2cap_timeout_check(void){
3730     disable_l2cap_timeouts = 1;
3731 }
3732 #endif
3733 
3734 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
3735 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3736 void hci_set_bd_addr(bd_addr_t addr){
3737     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3738     hci_stack->custom_bd_addr_set = 1;
3739 }
3740 #endif
3741 
3742 // State-Module-Driver overview
3743 // state                    module  low-level
3744 // HCI_STATE_OFF             off      close
3745 // HCI_STATE_INITIALIZING,   on       open
3746 // HCI_STATE_WORKING,        on       open
3747 // HCI_STATE_HALTING,        on       open
3748 // HCI_STATE_SLEEPING,    off/sleep   close
3749 // HCI_STATE_FALLING_ASLEEP  on       open
3750 
3751 static int hci_power_control_on(void){
3752 
3753     // power on
3754     int err = 0;
3755     if (hci_stack->control && hci_stack->control->on){
3756         err = (*hci_stack->control->on)();
3757     }
3758     if (err){
3759         log_error( "POWER_ON failed");
3760         hci_emit_hci_open_failed();
3761         return err;
3762     }
3763 
3764     // int chipset driver
3765     if (hci_stack->chipset && hci_stack->chipset->init){
3766         hci_stack->chipset->init(hci_stack->config);
3767     }
3768 
3769     // init transport
3770     if (hci_stack->hci_transport->init){
3771         hci_stack->hci_transport->init(hci_stack->config);
3772     }
3773 
3774     // open transport
3775     err = hci_stack->hci_transport->open();
3776     if (err){
3777         log_error( "HCI_INIT failed, turning Bluetooth off again");
3778         if (hci_stack->control && hci_stack->control->off){
3779             (*hci_stack->control->off)();
3780         }
3781         hci_emit_hci_open_failed();
3782         return err;
3783     }
3784     return 0;
3785 }
3786 
3787 static void hci_power_control_off(void){
3788 
3789     log_info("hci_power_control_off");
3790 
3791     // close low-level device
3792     hci_stack->hci_transport->close();
3793 
3794     log_info("hci_power_control_off - hci_transport closed");
3795 
3796     // power off
3797     if (hci_stack->control && hci_stack->control->off){
3798         (*hci_stack->control->off)();
3799     }
3800 
3801     log_info("hci_power_control_off - control closed");
3802 
3803     hci_stack->state = HCI_STATE_OFF;
3804 }
3805 
3806 static void hci_power_control_sleep(void){
3807 
3808     log_info("hci_power_control_sleep");
3809 
3810 #if 0
3811     // don't close serial port during sleep
3812 
3813     // close low-level device
3814     hci_stack->hci_transport->close(hci_stack->config);
3815 #endif
3816 
3817     // sleep mode
3818     if (hci_stack->control && hci_stack->control->sleep){
3819         (*hci_stack->control->sleep)();
3820     }
3821 
3822     hci_stack->state = HCI_STATE_SLEEPING;
3823 }
3824 
3825 static int hci_power_control_wake(void){
3826 
3827     log_info("hci_power_control_wake");
3828 
3829     // wake on
3830     if (hci_stack->control && hci_stack->control->wake){
3831         (*hci_stack->control->wake)();
3832     }
3833 
3834 #if 0
3835     // open low-level device
3836     int err = hci_stack->hci_transport->open(hci_stack->config);
3837     if (err){
3838         log_error( "HCI_INIT failed, turning Bluetooth off again");
3839         if (hci_stack->control && hci_stack->control->off){
3840             (*hci_stack->control->off)();
3841         }
3842         hci_emit_hci_open_failed();
3843         return err;
3844     }
3845 #endif
3846 
3847     return 0;
3848 }
3849 
3850 static void hci_power_transition_to_initializing(void){
3851     // set up state machine
3852     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
3853     hci_stack->hci_packet_buffer_reserved = false;
3854     hci_stack->state = HCI_STATE_INITIALIZING;
3855     hci_stack->substate = HCI_INIT_SEND_RESET;
3856 }
3857 
3858 // returns error
3859 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
3860     int err;
3861     switch (power_mode){
3862         case HCI_POWER_ON:
3863             err = hci_power_control_on();
3864             if (err != 0) {
3865                 log_error("hci_power_control_on() error %d", err);
3866                 return err;
3867             }
3868             hci_power_transition_to_initializing();
3869             break;
3870         case HCI_POWER_OFF:
3871             // do nothing
3872             break;
3873         case HCI_POWER_SLEEP:
3874             // do nothing (with SLEEP == OFF)
3875             break;
3876         default:
3877             btstack_assert(false);
3878             break;
3879     }
3880     return ERROR_CODE_SUCCESS;
3881 }
3882 
3883 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
3884     switch (power_mode){
3885         case HCI_POWER_ON:
3886             // do nothing
3887             break;
3888         case HCI_POWER_OFF:
3889             // no connections yet, just turn it off
3890             hci_power_control_off();
3891             break;
3892         case HCI_POWER_SLEEP:
3893             // no connections yet, just turn it off
3894             hci_power_control_sleep();
3895             break;
3896         default:
3897             btstack_assert(false);
3898             break;
3899     }
3900     return ERROR_CODE_SUCCESS;
3901 }
3902 
3903 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
3904     switch (power_mode){
3905         case HCI_POWER_ON:
3906             // do nothing
3907             break;
3908         case HCI_POWER_OFF:
3909             // see hci_run
3910             hci_stack->state = HCI_STATE_HALTING;
3911             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3912             break;
3913         case HCI_POWER_SLEEP:
3914             // see hci_run
3915             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3916             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3917             break;
3918         default:
3919             btstack_assert(false);
3920             break;
3921     }
3922     return ERROR_CODE_SUCCESS;
3923 }
3924 
3925 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
3926     switch (power_mode){
3927         case HCI_POWER_ON:
3928             hci_power_transition_to_initializing();
3929             break;
3930         case HCI_POWER_OFF:
3931             // do nothing
3932             break;
3933         case HCI_POWER_SLEEP:
3934             // see hci_run
3935             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3936             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3937             break;
3938         default:
3939             btstack_assert(false);
3940             break;
3941     }
3942     return ERROR_CODE_SUCCESS;
3943 }
3944 
3945 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
3946     switch (power_mode){
3947         case HCI_POWER_ON:
3948 
3949 #ifdef HAVE_PLATFORM_IPHONE_OS
3950             // nothing to do, if H4 supports power management
3951                     if (btstack_control_iphone_power_management_enabled()){
3952                         hci_stack->state = HCI_STATE_INITIALIZING;
3953                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
3954                         break;
3955                     }
3956 #endif
3957             hci_power_transition_to_initializing();
3958             break;
3959         case HCI_POWER_OFF:
3960             // see hci_run
3961             hci_stack->state = HCI_STATE_HALTING;
3962             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3963             break;
3964         case HCI_POWER_SLEEP:
3965             // do nothing
3966             break;
3967         default:
3968             btstack_assert(false);
3969             break;
3970     }
3971     return ERROR_CODE_SUCCESS;
3972 }
3973 
3974 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
3975     int err;
3976     switch (power_mode){
3977         case HCI_POWER_ON:
3978 #ifdef HAVE_PLATFORM_IPHONE_OS
3979             // nothing to do, if H4 supports power management
3980                     if (btstack_control_iphone_power_management_enabled()){
3981                         hci_stack->state = HCI_STATE_INITIALIZING;
3982                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3983                         hci_update_scan_enable();
3984                         break;
3985                     }
3986 #endif
3987             err = hci_power_control_wake();
3988             if (err) return err;
3989             hci_power_transition_to_initializing();
3990             break;
3991         case HCI_POWER_OFF:
3992             hci_stack->state = HCI_STATE_HALTING;
3993             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3994             break;
3995         case HCI_POWER_SLEEP:
3996             // do nothing
3997             break;
3998         default:
3999             btstack_assert(false);
4000             break;
4001     }
4002     return ERROR_CODE_SUCCESS;
4003 }
4004 
4005 int hci_power_control(HCI_POWER_MODE power_mode){
4006     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
4007     int err = 0;
4008     switch (hci_stack->state){
4009         case HCI_STATE_OFF:
4010             err = hci_power_control_state_off(power_mode);
4011             break;
4012         case HCI_STATE_INITIALIZING:
4013             err = hci_power_control_state_initializing(power_mode);
4014             break;
4015         case HCI_STATE_WORKING:
4016             err = hci_power_control_state_working(power_mode);
4017             break;
4018         case HCI_STATE_HALTING:
4019             err = hci_power_control_state_halting(power_mode);
4020             break;
4021         case HCI_STATE_FALLING_ASLEEP:
4022             err = hci_power_control_state_falling_asleep(power_mode);
4023             break;
4024         case HCI_STATE_SLEEPING:
4025             err = hci_power_control_state_sleeping(power_mode);
4026             break;
4027         default:
4028             btstack_assert(false);
4029             break;
4030     }
4031     if (err != 0){
4032         return err;
4033     }
4034 
4035     // create internal event
4036 	hci_emit_state();
4037 
4038 	// trigger next/first action
4039 	hci_run();
4040 
4041     return 0;
4042 }
4043 
4044 
4045 #ifdef ENABLE_CLASSIC
4046 
4047 static void hci_update_scan_enable(void){
4048     // 2 = page scan, 1 = inq scan
4049     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
4050     hci_run();
4051 }
4052 
4053 void gap_discoverable_control(uint8_t enable){
4054     if (enable) enable = 1; // normalize argument
4055 
4056     if (hci_stack->discoverable == enable){
4057         hci_emit_discoverable_enabled(hci_stack->discoverable);
4058         return;
4059     }
4060 
4061     hci_stack->discoverable = enable;
4062     hci_update_scan_enable();
4063 }
4064 
4065 void gap_connectable_control(uint8_t enable){
4066     if (enable) enable = 1; // normalize argument
4067 
4068     // don't emit event
4069     if (hci_stack->connectable == enable) return;
4070 
4071     hci_stack->connectable = enable;
4072     hci_update_scan_enable();
4073 }
4074 #endif
4075 
4076 void gap_local_bd_addr(bd_addr_t address_buffer){
4077     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
4078 }
4079 
4080 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4081 static void hci_host_num_completed_packets(void){
4082 
4083     // create packet manually as arrays are not supported and num_commands should not get reduced
4084     hci_reserve_packet_buffer();
4085     uint8_t * packet = hci_get_outgoing_packet_buffer();
4086 
4087     uint16_t size = 0;
4088     uint16_t num_handles = 0;
4089     packet[size++] = 0x35;
4090     packet[size++] = 0x0c;
4091     size++;  // skip param len
4092     size++;  // skip num handles
4093 
4094     // add { handle, packets } entries
4095     btstack_linked_item_t * it;
4096     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4097         hci_connection_t * connection = (hci_connection_t *) it;
4098         if (connection->num_packets_completed){
4099             little_endian_store_16(packet, size, connection->con_handle);
4100             size += 2;
4101             little_endian_store_16(packet, size, connection->num_packets_completed);
4102             size += 2;
4103             //
4104             num_handles++;
4105             connection->num_packets_completed = 0;
4106         }
4107     }
4108 
4109     packet[2] = size - 3;
4110     packet[3] = num_handles;
4111 
4112     hci_stack->host_completed_packets = 0;
4113 
4114     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4115     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
4116 
4117     // release packet buffer for synchronous transport implementations
4118     if (hci_transport_synchronous()){
4119         hci_release_packet_buffer();
4120         hci_emit_transport_packet_sent();
4121     }
4122 }
4123 #endif
4124 
4125 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
4126     UNUSED(ds);
4127     hci_stack->substate = HCI_HALTING_CLOSE;
4128     // allow packet handlers to defer final shutdown
4129     hci_emit_state();
4130     hci_run();
4131 }
4132 
4133 static bool hci_run_acl_fragments(void){
4134     if (hci_stack->acl_fragmentation_total_size > 0u) {
4135         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
4136         hci_connection_t *connection = hci_connection_for_handle(con_handle);
4137         if (connection) {
4138             if (hci_can_send_prepared_acl_packet_now(con_handle)){
4139                 hci_send_acl_packet_fragments(connection);
4140                 return true;
4141             }
4142         } else {
4143             // connection gone -> discard further fragments
4144             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
4145             hci_stack->acl_fragmentation_total_size = 0;
4146             hci_stack->acl_fragmentation_pos = 0;
4147         }
4148     }
4149     return false;
4150 }
4151 
4152 #ifdef ENABLE_CLASSIC
4153 static bool hci_run_general_gap_classic(void){
4154 
4155     // assert stack is working and classic is active
4156     if (hci_classic_supported() == false)      return false;
4157     if (hci_stack->state != HCI_STATE_WORKING) return false;
4158 
4159     // decline incoming connections
4160     if (hci_stack->decline_reason){
4161         uint8_t reason = hci_stack->decline_reason;
4162         hci_stack->decline_reason = 0;
4163         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
4164         return true;
4165     }
4166 
4167     if ((hci_stack->gap_tasks & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
4168         hci_stack->gap_tasks &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
4169         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
4170         return true;
4171     }
4172     if ((hci_stack->gap_tasks & GAP_TASK_SET_LOCAL_NAME) != 0) {
4173         hci_stack->gap_tasks &= ~GAP_TASK_SET_LOCAL_NAME;
4174         gap_run_set_local_name();
4175         return true;
4176     }
4177     if ((hci_stack->gap_tasks & GAP_TASK_SET_EIR_DATA) != 0) {
4178         hci_stack->gap_tasks &= ~GAP_TASK_SET_EIR_DATA;
4179         gap_run_set_eir_data();
4180         return true;
4181     }
4182     if ((hci_stack->gap_tasks & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
4183         hci_stack->gap_tasks &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
4184         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
4185         return true;
4186     }
4187     // write page scan activity
4188     if (hci_stack->new_page_scan_interval != 0xffff) {
4189         uint16_t new_page_scan_interval = hci_stack->new_page_scan_interval;
4190         uint16_t new_page_scan_window = hci_stack->new_page_scan_window;
4191         hci_stack->new_page_scan_interval = 0xffff;
4192         hci_stack->new_page_scan_window = 0xffff;
4193         hci_send_cmd(&hci_write_page_scan_activity, new_page_scan_interval, new_page_scan_window);
4194         return true;
4195     }
4196     // write page scan type
4197     if (hci_stack->new_page_scan_type != 0xff) {
4198         uint8_t new_page_scan_type = hci_stack->new_page_scan_type;
4199         hci_stack->new_page_scan_type = 0xff;
4200         hci_send_cmd(&hci_write_page_scan_type, new_page_scan_type);
4201         return true;
4202     }
4203     // send scan enable
4204     if (hci_stack->new_scan_enable_value != 0xff) {
4205         uint8_t new_scan_enable_value = hci_stack->new_scan_enable_value;
4206         hci_stack->new_scan_enable_value = 0xff;
4207         hci_send_cmd(&hci_write_scan_enable, new_scan_enable_value);
4208         return true;
4209     }
4210 
4211     // start/stop inquiry
4212     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
4213         uint8_t duration = hci_stack->inquiry_state;
4214         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
4215         hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
4216         return true;
4217     }
4218     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
4219         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
4220         hci_send_cmd(&hci_inquiry_cancel);
4221         return true;
4222     }
4223     // remote name request
4224     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
4225         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
4226         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
4227                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
4228         return true;
4229     }
4230 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4231     // Local OOB data
4232     if (hci_stack->classic_read_local_oob_data){
4233         hci_stack->classic_read_local_oob_data = false;
4234         if (hci_stack->local_supported_commands[1] & 0x10u){
4235             hci_send_cmd(&hci_read_local_extended_oob_data);
4236         } else {
4237             hci_send_cmd(&hci_read_local_oob_data);
4238         }
4239     }
4240 #endif
4241     // pairing
4242     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
4243         uint8_t state = hci_stack->gap_pairing_state;
4244         uint8_t pin_code[16];
4245         switch (state){
4246             case GAP_PAIRING_STATE_SEND_PIN:
4247                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4248                 memset(pin_code, 0, 16);
4249                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
4250                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
4251                 break;
4252             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
4253                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4254                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
4255                 break;
4256             case GAP_PAIRING_STATE_SEND_PASSKEY:
4257                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4258                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
4259                 break;
4260             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
4261                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4262                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
4263                 break;
4264             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
4265                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
4266                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
4267                 break;
4268             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
4269                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
4270                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
4271                 break;
4272             default:
4273                 break;
4274         }
4275         return true;
4276     }
4277     return false;
4278 }
4279 #endif
4280 
4281 #ifdef ENABLE_BLE
4282 static bool hci_run_general_gap_le(void){
4283 
4284     // advertisements, active scanning, and creating connections requires random address to be set if using private address
4285 
4286     if (hci_stack->state != HCI_STATE_WORKING) return false;
4287     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
4288 
4289 
4290     // Phase 1: collect what to stop
4291 
4292     bool scanning_stop = false;
4293     bool connecting_stop = false;
4294     bool advertising_stop = false;
4295 
4296 #ifndef ENABLE_LE_CENTRAL
4297     UNUSED(scanning_stop);
4298     UNUSED(connecting_stop);
4299 #endif
4300 #ifndef ENABLE_LE_PERIPHERAL
4301     UNUSED(advertising_stop);
4302 #endif
4303 
4304     // check if whitelist needs modification
4305     bool whitelist_modification_pending = false;
4306     btstack_linked_list_iterator_t lit;
4307     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4308     while (btstack_linked_list_iterator_has_next(&lit)){
4309         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4310         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
4311             whitelist_modification_pending = true;
4312             break;
4313         }
4314     }
4315     // check if resolving list needs modification
4316     bool resolving_list_modification_pending = false;
4317 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4318     bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0;
4319 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
4320         resolving_list_modification_pending = true;
4321     }
4322 #endif
4323 
4324 #ifdef ENABLE_LE_CENTRAL
4325     // scanning control
4326     if (hci_stack->le_scanning_active) {
4327         // stop if:
4328         // - parameter change required
4329         // - it's disabled
4330         // - whitelist change required but used for scanning
4331         // - resolving list modified
4332         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
4333         if ((hci_stack->le_scanning_param_update) ||
4334             !hci_stack->le_scanning_enabled ||
4335             scanning_uses_whitelist ||
4336             resolving_list_modification_pending){
4337 
4338             scanning_stop = true;
4339         }
4340     }
4341 #endif
4342 
4343 #ifdef ENABLE_LE_CENTRAL
4344     // connecting control
4345     bool connecting_with_whitelist;
4346     switch (hci_stack->le_connecting_state){
4347         case LE_CONNECTING_DIRECT:
4348         case LE_CONNECTING_WHITELIST:
4349             // stop connecting if:
4350             // - connecting uses white and whitelist modification pending
4351             // - if it got disabled
4352             // - resolving list modified
4353             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
4354             if ((connecting_with_whitelist && whitelist_modification_pending) ||
4355                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
4356                 resolving_list_modification_pending) {
4357 
4358                 connecting_stop = true;
4359             }
4360             break;
4361         default:
4362             break;
4363     }
4364 #endif
4365 
4366 #ifdef ENABLE_LE_PERIPHERAL
4367     // le advertisement control
4368     if (hci_stack->le_advertisements_active){
4369         // stop if:
4370         // - parameter change required
4371         // - it's disabled
4372         // - whitelist change required but used for advertisement filter policy
4373         // - resolving list modified
4374         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
4375         bool advertising_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
4376         if (advertising_change ||
4377             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
4378             (advertising_uses_whitelist & whitelist_modification_pending) ||
4379             resolving_list_modification_pending) {
4380 
4381             advertising_stop = true;
4382         }
4383     }
4384 #endif
4385 
4386 
4387     // Phase 2: stop everything that should be off during modifications
4388 
4389 #ifdef ENABLE_LE_CENTRAL
4390     if (scanning_stop){
4391         hci_stack->le_scanning_active = false;
4392         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
4393         return true;
4394     }
4395 #endif
4396 
4397 #ifdef ENABLE_LE_CENTRAL
4398     if (connecting_stop){
4399         hci_send_cmd(&hci_le_create_connection_cancel);
4400         return true;
4401     }
4402 #endif
4403 
4404 #ifdef ENABLE_LE_PERIPHERAL
4405     if (advertising_stop){
4406         hci_stack->le_advertisements_active = false;
4407         hci_send_cmd(&hci_le_set_advertise_enable, 0);
4408         return true;
4409     }
4410 #endif
4411 
4412     // Phase 3: modify
4413 
4414 #ifdef ENABLE_LE_CENTRAL
4415     if (hci_stack->le_scanning_param_update){
4416         hci_stack->le_scanning_param_update = false;
4417         hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
4418                      hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
4419         return true;
4420     }
4421 #endif
4422 
4423 #ifdef ENABLE_LE_PERIPHERAL
4424     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
4425         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4426         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
4427         hci_send_cmd(&hci_le_set_advertising_parameters,
4428                      hci_stack->le_advertisements_interval_min,
4429                      hci_stack->le_advertisements_interval_max,
4430                      hci_stack->le_advertisements_type,
4431                      hci_stack->le_advertisements_own_addr_type,
4432                      hci_stack->le_advertisements_direct_address_type,
4433                      hci_stack->le_advertisements_direct_address,
4434                      hci_stack->le_advertisements_channel_map,
4435                      hci_stack->le_advertisements_filter_policy);
4436         return true;
4437     }
4438     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
4439         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4440         uint8_t adv_data_clean[31];
4441         memset(adv_data_clean, 0, sizeof(adv_data_clean));
4442         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
4443                      hci_stack->le_advertisements_data_len);
4444         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
4445         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
4446         return true;
4447     }
4448     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
4449         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4450         uint8_t scan_data_clean[31];
4451         memset(scan_data_clean, 0, sizeof(scan_data_clean));
4452         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
4453                      hci_stack->le_scan_response_data_len);
4454         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
4455         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
4456         return true;
4457     }
4458 #endif
4459 
4460 
4461 #ifdef ENABLE_LE_CENTRAL
4462     // if connect with whitelist was active and is not cancelled yet, wait until next time
4463     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
4464 #endif
4465 
4466     // LE Whitelist Management
4467     if (whitelist_modification_pending){
4468         // add/remove entries
4469         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4470         while (btstack_linked_list_iterator_has_next(&lit)){
4471             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4472 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
4473 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4474 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
4475 				return true;
4476 			}
4477             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
4478 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
4479                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
4480                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
4481                 return true;
4482             }
4483             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
4484 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
4485 				btstack_memory_whitelist_entry_free(entry);
4486             }
4487         }
4488     }
4489 
4490 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4491     // LE Resolving List Management
4492     if (resolving_list_supported) {
4493 		uint16_t i;
4494 		switch (hci_stack->le_resolving_list_state) {
4495 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
4496 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
4497 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
4498 				return true;
4499 			case LE_RESOLVING_LIST_READ_SIZE:
4500 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
4501 				hci_send_cmd(&hci_le_read_resolving_list_size);
4502 				return true;
4503 			case LE_RESOLVING_LIST_SEND_CLEAR:
4504 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
4505 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
4506 							  sizeof(hci_stack->le_resolving_list_add_entries));
4507 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
4508 							  sizeof(hci_stack->le_resolving_list_remove_entries));
4509 				hci_send_cmd(&hci_le_clear_resolving_list);
4510 				return true;
4511 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
4512 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4513 					uint8_t offset = i >> 3;
4514 					uint8_t mask = 1 << (i & 7);
4515 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
4516 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
4517 					bd_addr_t peer_identity_addreses;
4518 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4519 					sm_key_t peer_irk;
4520 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4521 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4522 
4523 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
4524 					// trigger whitelist entry 'update' (work around for controller bug)
4525 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4526 					while (btstack_linked_list_iterator_has_next(&lit)) {
4527 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
4528 						if (entry->address_type != peer_identity_addr_type) continue;
4529 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
4530 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
4531 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
4532 					}
4533 #endif
4534 
4535 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
4536 								 peer_identity_addreses);
4537 					return true;
4538 				}
4539 
4540 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
4541 
4542 				/* fall through */
4543 
4544 			case LE_RESOLVING_LIST_ADD_ENTRIES:
4545 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
4546 					uint8_t offset = i >> 3;
4547 					uint8_t mask = 1 << (i & 7);
4548 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
4549 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
4550 					bd_addr_t peer_identity_addreses;
4551 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
4552 					sm_key_t peer_irk;
4553 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
4554 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4555 					const uint8_t *local_irk = gap_get_persistent_irk();
4556 					// command uses format specifier 'P' that stores 16-byte value without flip
4557 					uint8_t local_irk_flipped[16];
4558 					uint8_t peer_irk_flipped[16];
4559 					reverse_128(local_irk, local_irk_flipped);
4560 					reverse_128(peer_irk, peer_irk_flipped);
4561 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
4562 								 peer_irk_flipped, local_irk_flipped);
4563 					return true;
4564 				}
4565 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4566 				break;
4567 
4568 			default:
4569 				break;
4570 		}
4571 	}
4572     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
4573 #endif
4574 
4575     // Phase 4: restore state
4576 
4577 #ifdef ENABLE_LE_CENTRAL
4578     // re-start scanning
4579     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
4580         hci_stack->le_scanning_active = true;
4581         hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
4582         return true;
4583     }
4584 #endif
4585 
4586 #ifdef ENABLE_LE_CENTRAL
4587     // re-start connecting
4588     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
4589         bd_addr_t null_addr;
4590         memset(null_addr, 0, 6);
4591         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
4592         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
4593         hci_send_cmd(&hci_le_create_connection,
4594                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
4595                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
4596                      1,         // use whitelist
4597                      0,         // peer address type
4598                      null_addr, // peer bd addr
4599                      hci_stack->le_connection_own_addr_type,   // our addr type:
4600                      hci_stack->le_connection_interval_min,    // conn interval min
4601                      hci_stack->le_connection_interval_max,    // conn interval max
4602                      hci_stack->le_connection_latency,         // conn latency
4603                      hci_stack->le_supervision_timeout,        // conn latency
4604                      hci_stack->le_minimum_ce_length,          // min ce length
4605                      hci_stack->le_maximum_ce_length           // max ce length
4606         );
4607         return true;
4608     }
4609 #endif
4610 
4611 #ifdef ENABLE_LE_PERIPHERAL
4612     // re-start advertising
4613     if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){
4614         // check if advertisements should be enabled given
4615         hci_stack->le_advertisements_active = true;
4616         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
4617         hci_send_cmd(&hci_le_set_advertise_enable, 1);
4618         return true;
4619     }
4620 #endif
4621 
4622     return false;
4623 }
4624 #endif
4625 
4626 static bool hci_run_general_pending_commands(void){
4627     btstack_linked_item_t * it;
4628     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
4629         hci_connection_t * connection = (hci_connection_t *) it;
4630 
4631         switch(connection->state){
4632             case SEND_CREATE_CONNECTION:
4633                 switch(connection->address_type){
4634 #ifdef ENABLE_CLASSIC
4635                     case BD_ADDR_TYPE_ACL:
4636                         log_info("sending hci_create_connection");
4637                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
4638                         break;
4639 #endif
4640                     default:
4641 #ifdef ENABLE_BLE
4642 #ifdef ENABLE_LE_CENTRAL
4643                         log_info("sending hci_le_create_connection");
4644                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
4645                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
4646                         hci_send_cmd(&hci_le_create_connection,
4647                                      hci_stack->le_connection_scan_interval,    // conn scan interval
4648                                      hci_stack->le_connection_scan_window,      // conn scan windows
4649                                      0,         // don't use whitelist
4650                                      connection->address_type, // peer address type
4651                                      connection->address,      // peer bd addr
4652                                      hci_stack->le_connection_own_addr_type,   // our addr type:
4653                                      hci_stack->le_connection_interval_min,    // conn interval min
4654                                      hci_stack->le_connection_interval_max,    // conn interval max
4655                                      hci_stack->le_connection_latency,         // conn latency
4656                                      hci_stack->le_supervision_timeout,        // conn latency
4657                                      hci_stack->le_minimum_ce_length,          // min ce length
4658                                      hci_stack->le_maximum_ce_length          // max ce length
4659                         );
4660                         connection->state = SENT_CREATE_CONNECTION;
4661 #endif
4662 #endif
4663                         break;
4664                 }
4665                 return true;
4666 
4667 #ifdef ENABLE_CLASSIC
4668             case RECEIVED_CONNECTION_REQUEST:
4669                 connection->role  = HCI_ROLE_SLAVE;
4670                 if (connection->address_type == BD_ADDR_TYPE_ACL){
4671                     log_info("sending hci_accept_connection_request");
4672                     connection->state = ACCEPTED_CONNECTION_REQUEST;
4673                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
4674                 }
4675                 return true;
4676 #endif
4677 
4678 #ifdef ENABLE_BLE
4679 #ifdef ENABLE_LE_CENTRAL
4680             case SEND_CANCEL_CONNECTION:
4681                 connection->state = SENT_CANCEL_CONNECTION;
4682                 hci_send_cmd(&hci_le_create_connection_cancel);
4683                 return true;
4684 #endif
4685 #endif
4686             case SEND_DISCONNECT:
4687                 connection->state = SENT_DISCONNECT;
4688                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4689                 return true;
4690 
4691             default:
4692                 break;
4693         }
4694 
4695         // no further commands if connection is about to get shut down
4696         if (connection->state == SENT_DISCONNECT) continue;
4697 
4698         if (connection->authentication_flags & AUTH_FLAG_READ_RSSI){
4699             connectionClearAuthenticationFlags(connection, AUTH_FLAG_READ_RSSI);
4700             hci_send_cmd(&hci_read_rssi, connection->con_handle);
4701             return true;
4702         }
4703 
4704 #ifdef ENABLE_CLASSIC
4705 
4706         if (connection->authentication_flags & AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT){
4707             connectionClearAuthenticationFlags(connection, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
4708             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
4709             return true;
4710         }
4711 
4712         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
4713             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
4714             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
4715             return true;
4716         }
4717 
4718         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
4719             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
4720             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
4721             return true;
4722         }
4723 
4724         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
4725             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
4726             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
4727             return true;
4728         }
4729 
4730         // Handling link key request requires remote supported features
4731         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
4732             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
4733             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
4734 
4735             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
4736             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
4737             if (have_link_key && security_level_sufficient){
4738                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
4739             } else {
4740                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
4741             }
4742             return true;
4743         }
4744 
4745         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
4746             log_info("denying to pin request");
4747             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
4748             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
4749             return true;
4750         }
4751 
4752         // security assessment requires remote features
4753         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
4754             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
4755             hci_ssp_assess_security_on_io_cap_request(connection);
4756             // 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
4757         }
4758 
4759         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
4760             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
4761             // set authentication requirements:
4762             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
4763             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
4764             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
4765             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
4766                 authreq |= 1;
4767             }
4768             bool bonding = hci_stack->bondable;
4769             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
4770                 // if we have received IO Cap Response, we're in responder role
4771                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4772                 if (bonding && !remote_bonding){
4773                     log_info("Remote not bonding, dropping local flag");
4774                     bonding = false;
4775                 }
4776             }
4777             if (bonding){
4778                 if (connection->bonding_flags & BONDING_DEDICATED){
4779                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4780                 } else {
4781                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4782                 }
4783             }
4784             uint8_t have_oob_data = 0;
4785 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4786             if (connection->classic_oob_c_192 != NULL){
4787                     have_oob_data |= 1;
4788             }
4789             if (connection->classic_oob_c_256 != NULL){
4790                 have_oob_data |= 2;
4791             }
4792 #endif
4793             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
4794             return true;
4795         }
4796 
4797         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
4798             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
4799             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
4800             return true;
4801         }
4802 
4803 #ifdef ENABLE_CLASSIC_PAIRING_OOB
4804         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
4805             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
4806             const uint8_t zero[16] = { 0 };
4807             const uint8_t * r_192 = zero;
4808             const uint8_t * c_192 = zero;
4809             const uint8_t * r_256 = zero;
4810             const uint8_t * c_256 = zero;
4811             // verify P-256 OOB
4812             if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) {
4813                 c_256 = connection->classic_oob_c_256;
4814                 if (connection->classic_oob_r_256 != NULL) {
4815                     r_256 = connection->classic_oob_r_256;
4816                 }
4817             }
4818             // verify P-192 OOB
4819             if ((connection->classic_oob_c_192 != NULL)) {
4820                 c_192 = connection->classic_oob_c_192;
4821                 if (connection->classic_oob_r_192 != NULL) {
4822                     r_192 = connection->classic_oob_r_192;
4823                 }
4824             }
4825 
4826             // assess security
4827             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
4828             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
4829             if (need_level_4 && !can_reach_level_4){
4830                 log_info("Level 4 required, but not possible -> abort");
4831                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
4832                 // send oob negative reply
4833                 c_256 = NULL;
4834                 c_192 = NULL;
4835             }
4836 
4837             // Reply
4838             if (c_256 != zero) {
4839                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
4840             } else if (c_192 != zero){
4841                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
4842             } else {
4843                 hci_stack->classic_oob_con_handle = connection->con_handle;
4844                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
4845             }
4846             return true;
4847         }
4848 #endif
4849 
4850         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
4851             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4852             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
4853             return true;
4854         }
4855 
4856         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
4857             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4858             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
4859             return true;
4860         }
4861 
4862         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
4863             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4864             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
4865             return true;
4866         }
4867 
4868         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
4869             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
4870             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
4871             connection->state = SENT_DISCONNECT;
4872             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4873             return true;
4874         }
4875 
4876         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
4877             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
4878             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
4879             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
4880             return true;
4881         }
4882 
4883         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
4884             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
4885             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
4886             return true;
4887         }
4888         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
4889             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4890             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
4891             return true;
4892         }
4893 #endif
4894 
4895         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
4896             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
4897 #ifdef ENABLE_CLASSIC
4898             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
4899 #endif
4900             if (connection->state != SENT_DISCONNECT){
4901                 connection->state = SENT_DISCONNECT;
4902                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4903                 return true;
4904             }
4905         }
4906 
4907 #ifdef ENABLE_CLASSIC
4908         uint16_t sniff_min_interval;
4909         switch (connection->sniff_min_interval){
4910             case 0:
4911                 break;
4912             case 0xffff:
4913                 connection->sniff_min_interval = 0;
4914                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
4915                 return true;
4916             default:
4917                 sniff_min_interval = connection->sniff_min_interval;
4918                 connection->sniff_min_interval = 0;
4919                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
4920                 return true;
4921         }
4922 
4923         if (connection->sniff_subrating_max_latency != 0xffff){
4924             uint16_t max_latency = connection->sniff_subrating_max_latency;
4925             connection->sniff_subrating_max_latency = 0;
4926             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
4927             return true;
4928         }
4929 
4930         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
4931             uint8_t service_type = (uint8_t) connection->qos_service_type;
4932             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
4933             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);
4934             return true;
4935         }
4936 
4937         if (connection->request_role != HCI_ROLE_INVALID){
4938             hci_role_t role = connection->request_role;
4939             connection->request_role = HCI_ROLE_INVALID;
4940             hci_send_cmd(&hci_switch_role_command, connection->address, role);
4941             return true;
4942         }
4943 #endif
4944 
4945 #ifdef ENABLE_BLE
4946         switch (connection->le_con_parameter_update_state){
4947             // response to L2CAP CON PARAMETER UPDATE REQUEST
4948             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
4949                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4950                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
4951                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4952                              0x0000, 0xffff);
4953                 return true;
4954             case CON_PARAMETER_UPDATE_REPLY:
4955                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4956                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
4957                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4958                              0x0000, 0xffff);
4959                 return true;
4960             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
4961                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
4962                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
4963                 return true;
4964             default:
4965                 break;
4966         }
4967         if (connection->le_phy_update_all_phys != 0xffu){
4968             uint8_t all_phys = connection->le_phy_update_all_phys;
4969             connection->le_phy_update_all_phys = 0xff;
4970             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);
4971             return true;
4972         }
4973 #endif
4974     }
4975     return false;
4976 }
4977 
4978 static void hci_run(void){
4979 
4980     bool done;
4981 
4982     // send continuation fragments first, as they block the prepared packet buffer
4983     done = hci_run_acl_fragments();
4984     if (done) return;
4985 
4986 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4987     // send host num completed packets next as they don't require num_cmd_packets > 0
4988     if (!hci_can_send_comand_packet_transport()) return;
4989     if (hci_stack->host_completed_packets){
4990         hci_host_num_completed_packets();
4991         return;
4992     }
4993 #endif
4994 
4995     if (!hci_can_send_command_packet_now()) return;
4996 
4997     // global/non-connection oriented commands
4998 
4999 
5000 #ifdef ENABLE_CLASSIC
5001     // general gap classic
5002     done = hci_run_general_gap_classic();
5003     if (done) return;
5004 #endif
5005 
5006 #ifdef ENABLE_BLE
5007     // general gap le
5008     done = hci_run_general_gap_le();
5009     if (done) return;
5010 #endif
5011 
5012     // send pending HCI commands
5013     done = hci_run_general_pending_commands();
5014     if (done) return;
5015 
5016     // stack state sub statemachines
5017     hci_connection_t * connection;
5018     switch (hci_stack->state){
5019         case HCI_STATE_INITIALIZING:
5020             hci_initializing_run();
5021             break;
5022 
5023         case HCI_STATE_HALTING:
5024 
5025             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5026             switch (hci_stack->substate){
5027                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
5028                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
5029 
5030 #ifdef ENABLE_BLE
5031 #ifdef ENABLE_LE_CENTRAL
5032                     // free whitelist entries
5033                     {
5034                         btstack_linked_list_iterator_t lit;
5035                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5036                         while (btstack_linked_list_iterator_has_next(&lit)){
5037                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5038                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
5039                             btstack_memory_whitelist_entry_free(entry);
5040                         }
5041                     }
5042 #endif
5043 #endif
5044                     // close all open connections
5045                     connection =  (hci_connection_t *) hci_stack->connections;
5046                     if (connection){
5047                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5048                         if (!hci_can_send_command_packet_now()) return;
5049 
5050                         // check state
5051                         if (connection->state == SENT_DISCONNECT) return;
5052                         connection->state = SENT_DISCONNECT;
5053 
5054                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
5055 
5056                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
5057                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
5058 
5059                         // ... which would be ignored anyway as we shutdown (free) the connection now
5060                         hci_shutdown_connection(connection);
5061 
5062                         // finally, send the disconnect command
5063                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5064                         return;
5065                     }
5066 
5067                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
5068                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5069                         log_info("HCI_STATE_HALTING: wait 50 ms");
5070                         hci_stack->substate = HCI_HALTING_W4_TIMER;
5071                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5072                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5073                         btstack_run_loop_add_timer(&hci_stack->timeout);
5074                         break;
5075                     }
5076 
5077                     /* fall through */
5078 
5079                 case HCI_HALTING_CLOSE:
5080                     log_info("HCI_STATE_HALTING, calling off");
5081 
5082                     // switch mode
5083                     hci_power_control_off();
5084 
5085                     log_info("HCI_STATE_HALTING, emitting state");
5086                     hci_emit_state();
5087                     log_info("HCI_STATE_HALTING, done");
5088                     break;
5089 
5090                 case HCI_HALTING_W4_TIMER:
5091                     // keep waiting
5092 
5093                     break;
5094                 default:
5095                     break;
5096             }
5097 
5098             break;
5099 
5100         case HCI_STATE_FALLING_ASLEEP:
5101             switch(hci_stack->substate) {
5102                 case HCI_FALLING_ASLEEP_DISCONNECT:
5103                     log_info("HCI_STATE_FALLING_ASLEEP");
5104                     // close all open connections
5105                     connection =  (hci_connection_t *) hci_stack->connections;
5106 
5107 #ifdef HAVE_PLATFORM_IPHONE_OS
5108                     // don't close connections, if H4 supports power management
5109                     if (btstack_control_iphone_power_management_enabled()){
5110                         connection = NULL;
5111                     }
5112 #endif
5113                     if (connection){
5114 
5115                         // send disconnect
5116                         if (!hci_can_send_command_packet_now()) return;
5117 
5118                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5119                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5120 
5121                         // send disconnected event right away - causes higher layer connections to get closed, too.
5122                         hci_shutdown_connection(connection);
5123                         return;
5124                     }
5125 
5126                     if (hci_classic_supported()){
5127                         // disable page and inquiry scan
5128                         if (!hci_can_send_command_packet_now()) return;
5129 
5130                         log_info("HCI_STATE_HALTING, disabling inq scans");
5131                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5132 
5133                         // continue in next sub state
5134                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5135                         break;
5136                     }
5137 
5138                     /* fall through */
5139 
5140                 case HCI_FALLING_ASLEEP_COMPLETE:
5141                     log_info("HCI_STATE_HALTING, calling sleep");
5142 #ifdef HAVE_PLATFORM_IPHONE_OS
5143                     // don't actually go to sleep, if H4 supports power management
5144                     if (btstack_control_iphone_power_management_enabled()){
5145                         // SLEEP MODE reached
5146                         hci_stack->state = HCI_STATE_SLEEPING;
5147                         hci_emit_state();
5148                         break;
5149                     }
5150 #endif
5151                     // switch mode
5152                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5153                     hci_emit_state();
5154                     break;
5155 
5156                 default:
5157                     break;
5158             }
5159             break;
5160 
5161         default:
5162             break;
5163     }
5164 }
5165 
5166 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
5167     // house-keeping
5168 
5169 #ifdef ENABLE_CLASSIC
5170     bd_addr_t addr;
5171     hci_connection_t * conn;
5172 #endif
5173 #ifdef ENABLE_LE_CENTRAL
5174     uint8_t initiator_filter_policy;
5175 #endif
5176 
5177     uint16_t opcode = little_endian_read_16(packet, 0);
5178     switch (opcode) {
5179         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
5180             hci_stack->loopback_mode = packet[3];
5181             break;
5182 
5183 #ifdef ENABLE_CLASSIC
5184         case HCI_OPCODE_HCI_CREATE_CONNECTION:
5185             reverse_bd_addr(&packet[3], addr);
5186             log_info("Create_connection to %s", bd_addr_to_str(addr));
5187 
5188             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
5189             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
5190                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
5191                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
5192             }
5193 
5194             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5195             if (!conn) {
5196                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
5197                 if (!conn) {
5198                     // notify client that alloc failed
5199                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5200                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
5201                 }
5202                 conn->state = SEND_CREATE_CONNECTION;
5203                 conn->role  = HCI_ROLE_MASTER;
5204             }
5205 
5206             conn->con_handle = HCI_CON_HANDLE_INVALID;
5207             conn->role = HCI_ROLE_INVALID;
5208 
5209             log_info("conn state %u", conn->state);
5210             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
5211             switch (conn->state) {
5212                 // if connection active exists
5213                 case OPEN:
5214                     // and OPEN, emit connection complete command
5215                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
5216                     // packet not sent to controller
5217                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5218                 case RECEIVED_DISCONNECTION_COMPLETE:
5219                     // create connection triggered in disconnect complete event, let's do it now
5220                     break;
5221                 case SEND_CREATE_CONNECTION:
5222                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
5223                     break;
5224                 default:
5225                     // otherwise, just ignore as it is already in the open process
5226                     // packet not sent to controller
5227                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
5228             }
5229             conn->state = SENT_CREATE_CONNECTION;
5230 
5231             // track outgoing connection
5232             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
5233             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
5234             break;
5235         case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY:
5236             if (hci_stack->link_key_db) {
5237                 reverse_bd_addr(&packet[3], addr);
5238                 hci_stack->link_key_db->delete_link_key(addr);
5239             }
5240             break;
5241 
5242 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
5243         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
5244             // setup_synchronous_connection? Voice setting at offset 22
5245             // TODO: compare to current setting if sco connection already active
5246             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
5247             break;
5248         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
5249             // accept_synchronus_connection? Voice setting at offset 18
5250             // TODO: compare to current setting if sco connection already active
5251             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
5252             break;
5253 #endif
5254 #endif
5255 
5256 #ifdef ENABLE_BLE
5257         case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS:
5258             hci_stack->le_random_address_set = 1;
5259             reverse_bd_addr(&packet[3], hci_stack->le_random_address);
5260             break;
5261 #ifdef ENABLE_LE_PERIPHERAL
5262         case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE:
5263             hci_stack->le_advertisements_active = packet[3] != 0;
5264             break;
5265 #endif
5266 #ifdef ENABLE_LE_CENTRAL
5267         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
5268             // white list used?
5269             initiator_filter_policy = packet[7];
5270             switch (initiator_filter_policy) {
5271                 case 0:
5272                     // whitelist not used
5273                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
5274                     break;
5275                 case 1:
5276                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
5277                     break;
5278                 default:
5279                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
5280                     break;
5281             }
5282             // track outgoing connection
5283             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
5284             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
5285             break;
5286         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
5287             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
5288             break;
5289 #endif
5290 #endif
5291         default:
5292             break;
5293     }
5294 
5295     hci_stack->num_cmd_packets--;
5296 
5297     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5298     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
5299     if (err != 0){
5300         return ERROR_CODE_HARDWARE_FAILURE;
5301     }
5302     return ERROR_CODE_SUCCESS;
5303 }
5304 
5305 // disconnect because of security block
5306 void hci_disconnect_security_block(hci_con_handle_t con_handle){
5307     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5308     if (!connection) return;
5309     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
5310 }
5311 
5312 
5313 // Configure Secure Simple Pairing
5314 
5315 #ifdef ENABLE_CLASSIC
5316 
5317 // enable will enable SSP during init
5318 void gap_ssp_set_enable(int enable){
5319     hci_stack->ssp_enable = enable;
5320 }
5321 
5322 static int hci_local_ssp_activated(void){
5323     return gap_ssp_supported() && hci_stack->ssp_enable;
5324 }
5325 
5326 // if set, BTstack will respond to io capability request using authentication requirement
5327 void gap_ssp_set_io_capability(int io_capability){
5328     hci_stack->ssp_io_capability = io_capability;
5329 }
5330 void gap_ssp_set_authentication_requirement(int authentication_requirement){
5331     hci_stack->ssp_authentication_requirement = authentication_requirement;
5332 }
5333 
5334 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
5335 void gap_ssp_set_auto_accept(int auto_accept){
5336     hci_stack->ssp_auto_accept = auto_accept;
5337 }
5338 
5339 void gap_secure_connections_enable(bool enable){
5340     hci_stack->secure_connections_enable = enable;
5341 }
5342 
5343 #endif
5344 
5345 // va_list part of hci_send_cmd
5346 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
5347     if (!hci_can_send_command_packet_now()){
5348         log_error("hci_send_cmd called but cannot send packet now");
5349         return ERROR_CODE_COMMAND_DISALLOWED;
5350     }
5351 
5352     // for HCI INITIALIZATION
5353     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
5354     hci_stack->last_cmd_opcode = cmd->opcode;
5355 
5356     hci_reserve_packet_buffer();
5357     uint8_t * packet = hci_stack->hci_packet_buffer;
5358     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
5359     uint8_t status = hci_send_cmd_packet(packet, size);
5360 
5361     // release packet buffer on error or for synchronous transport implementations
5362     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
5363         hci_release_packet_buffer();
5364         hci_emit_transport_packet_sent();
5365     }
5366 
5367     return status;
5368 }
5369 
5370 /**
5371  * pre: numcmds >= 0 - it's allowed to send a command to the controller
5372  */
5373 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
5374     va_list argptr;
5375     va_start(argptr, cmd);
5376     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
5377     va_end(argptr);
5378     return status;
5379 }
5380 
5381 // Create various non-HCI events.
5382 // TODO: generalize, use table similar to hci_create_command
5383 
5384 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
5385     // dump packet
5386     if (dump) {
5387         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
5388     }
5389 
5390     // dispatch to all event handlers
5391     btstack_linked_list_iterator_t it;
5392     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
5393     while (btstack_linked_list_iterator_has_next(&it)){
5394         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
5395         entry->callback(HCI_EVENT_PACKET, 0, event, size);
5396     }
5397 }
5398 
5399 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
5400     if (!hci_stack->acl_packet_handler) return;
5401     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
5402 }
5403 
5404 #ifdef ENABLE_CLASSIC
5405 static void hci_notify_if_sco_can_send_now(void){
5406     // notify SCO sender if waiting
5407     if (!hci_stack->sco_waiting_for_can_send_now) return;
5408     if (hci_can_send_sco_packet_now()){
5409         hci_stack->sco_waiting_for_can_send_now = 0;
5410         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
5411         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
5412         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
5413     }
5414 }
5415 
5416 // parsing end emitting has been merged to reduce code size
5417 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
5418     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
5419 
5420     uint8_t * eir_data;
5421     ad_context_t context;
5422     const uint8_t * name;
5423     uint8_t         name_len;
5424 
5425     if (size < 3) return;
5426 
5427     int event_type = hci_event_packet_get_type(packet);
5428     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
5429     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
5430 
5431     switch (event_type){
5432         case HCI_EVENT_INQUIRY_RESULT:
5433         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5434             if (size != (3 + (num_responses * 14))) return;
5435             break;
5436         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5437             if (size != 257) return;
5438             if (num_responses != 1) return;
5439             break;
5440         default:
5441             return;
5442     }
5443 
5444     // event[1] is set at the end
5445     int i;
5446     for (i=0; i<num_responses;i++){
5447         memset(event, 0, sizeof(event));
5448         event[0] = GAP_EVENT_INQUIRY_RESULT;
5449         uint8_t event_size = 27;    // if name is not set by EIR
5450 
5451         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
5452         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
5453         (void)memcpy(&event[9],
5454                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
5455                      3); // class of device
5456         (void)memcpy(&event[12],
5457                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
5458                      2); // clock offset
5459 
5460         switch (event_type){
5461             case HCI_EVENT_INQUIRY_RESULT:
5462                 // 14,15,16,17 = 0, size 18
5463                 break;
5464             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
5465                 event[14] = 1;
5466                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5467                 // 16,17 = 0, size 18
5468                 break;
5469             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
5470                 event[14] = 1;
5471                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
5472                 // EIR packets only contain a single inquiry response
5473                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
5474                 name = NULL;
5475                 // Iterate over EIR data
5476                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
5477                     uint8_t data_type    = ad_iterator_get_data_type(&context);
5478                     uint8_t data_size    = ad_iterator_get_data_len(&context);
5479                     const uint8_t * data = ad_iterator_get_data(&context);
5480                     // Prefer Complete Local Name over Shortened Local Name
5481                     switch (data_type){
5482                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
5483                             if (name) continue;
5484                             /* fall through */
5485                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
5486                             name = data;
5487                             name_len = data_size;
5488                             break;
5489                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
5490                             if (data_size != 8) break;
5491                             event[16] = 1;
5492                             memcpy(&event[17], data, 8);
5493                             break;
5494                         default:
5495                             break;
5496                     }
5497                 }
5498                 if (name){
5499                     event[25] = 1;
5500                     // truncate name if needed
5501                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
5502                     event[26] = len;
5503                     (void)memcpy(&event[27], name, len);
5504                     event_size += len;
5505                 }
5506                 break;
5507             default:
5508                 return;
5509         }
5510         event[1] = event_size - 2;
5511         hci_emit_event(event, event_size, 1);
5512     }
5513 }
5514 #endif
5515 
5516 void hci_emit_state(void){
5517     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
5518     uint8_t event[3];
5519     event[0] = BTSTACK_EVENT_STATE;
5520     event[1] = sizeof(event) - 2u;
5521     event[2] = hci_stack->state;
5522     hci_emit_event(event, sizeof(event), 1);
5523 }
5524 
5525 #ifdef ENABLE_CLASSIC
5526 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5527     uint8_t event[13];
5528     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
5529     event[1] = sizeof(event) - 2;
5530     event[2] = status;
5531     little_endian_store_16(event, 3, con_handle);
5532     reverse_bd_addr(address, &event[5]);
5533     event[11] = 1; // ACL connection
5534     event[12] = 0; // encryption disabled
5535     hci_emit_event(event, sizeof(event), 1);
5536 }
5537 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
5538     if (disable_l2cap_timeouts) return;
5539     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
5540     uint8_t event[4];
5541     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
5542     event[1] = sizeof(event) - 2;
5543     little_endian_store_16(event, 2, conn->con_handle);
5544     hci_emit_event(event, sizeof(event), 1);
5545 }
5546 #endif
5547 
5548 #ifdef ENABLE_BLE
5549 #ifdef ENABLE_LE_CENTRAL
5550 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){
5551     uint8_t event[21];
5552     event[0] = HCI_EVENT_LE_META;
5553     event[1] = sizeof(event) - 2u;
5554     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
5555     event[3] = status;
5556     little_endian_store_16(event, 4, con_handle);
5557     event[6] = 0; // TODO: role
5558     event[7] = address_type;
5559     reverse_bd_addr(address, &event[8]);
5560     little_endian_store_16(event, 14, 0); // interval
5561     little_endian_store_16(event, 16, 0); // latency
5562     little_endian_store_16(event, 18, 0); // supervision timeout
5563     event[20] = 0; // master clock accuracy
5564     hci_emit_event(event, sizeof(event), 1);
5565 }
5566 #endif
5567 #endif
5568 
5569 static void hci_emit_transport_packet_sent(void){
5570     // notify upper stack that it might be possible to send again
5571     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
5572     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
5573 }
5574 
5575 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
5576     uint8_t event[6];
5577     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
5578     event[1] = sizeof(event) - 2u;
5579     event[2] = 0; // status = OK
5580     little_endian_store_16(event, 3, con_handle);
5581     event[5] = reason;
5582     hci_emit_event(event, sizeof(event), 1);
5583 }
5584 
5585 static void hci_emit_nr_connections_changed(void){
5586     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
5587     uint8_t event[3];
5588     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
5589     event[1] = sizeof(event) - 2u;
5590     event[2] = nr_hci_connections();
5591     hci_emit_event(event, sizeof(event), 1);
5592 }
5593 
5594 static void hci_emit_hci_open_failed(void){
5595     log_info("BTSTACK_EVENT_POWERON_FAILED");
5596     uint8_t event[2];
5597     event[0] = BTSTACK_EVENT_POWERON_FAILED;
5598     event[1] = sizeof(event) - 2u;
5599     hci_emit_event(event, sizeof(event), 1);
5600 }
5601 
5602 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
5603     log_info("hci_emit_dedicated_bonding_result %u ", status);
5604     uint8_t event[9];
5605     int pos = 0;
5606     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
5607     event[pos++] = sizeof(event) - 2u;
5608     event[pos++] = status;
5609     reverse_bd_addr(address, &event[pos]);
5610     hci_emit_event(event, sizeof(event), 1);
5611 }
5612 
5613 
5614 #ifdef ENABLE_CLASSIC
5615 
5616 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
5617     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
5618     uint8_t event[5];
5619     int pos = 0;
5620     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
5621     event[pos++] = sizeof(event) - 2;
5622     little_endian_store_16(event, 2, con_handle);
5623     pos += 2;
5624     event[pos++] = level;
5625     hci_emit_event(event, sizeof(event), 1);
5626 }
5627 
5628 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
5629     if (!connection) return LEVEL_0;
5630     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
5631     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
5632     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
5633     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
5634     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
5635     // LEVEL 4 always requires 128 bit encrytion key size
5636     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
5637         security_level = LEVEL_3;
5638     }
5639     return security_level;
5640 }
5641 
5642 static void hci_emit_discoverable_enabled(uint8_t enabled){
5643     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
5644     uint8_t event[3];
5645     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
5646     event[1] = sizeof(event) - 2;
5647     event[2] = enabled;
5648     hci_emit_event(event, sizeof(event), 1);
5649 }
5650 
5651 // query if remote side supports eSCO
5652 bool hci_remote_esco_supported(hci_con_handle_t con_handle){
5653     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5654     if (!connection) return false;
5655     return (connection->remote_supported_features[0] & 1) != 0;
5656 }
5657 
5658 static bool hci_ssp_supported(hci_connection_t * connection){
5659     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
5660     return (connection->bonding_flags & mask) == mask;
5661 }
5662 
5663 // query if remote side supports SSP
5664 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
5665     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5666     if (!connection) return false;
5667     return hci_ssp_supported(connection) ? 1 : 0;
5668 }
5669 
5670 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
5671     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
5672 }
5673 
5674 // GAP API
5675 /**
5676  * @bbrief enable/disable bonding. default is enabled
5677  * @praram enabled
5678  */
5679 void gap_set_bondable_mode(int enable){
5680     hci_stack->bondable = enable ? 1 : 0;
5681 }
5682 /**
5683  * @brief Get bondable mode.
5684  * @return 1 if bondable
5685  */
5686 int gap_get_bondable_mode(void){
5687     return hci_stack->bondable;
5688 }
5689 
5690 /**
5691  * @brief map link keys to security levels
5692  */
5693 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
5694     switch (link_key_type){
5695         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5696             return LEVEL_4;
5697         case COMBINATION_KEY:
5698         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5699             return LEVEL_3;
5700         default:
5701             return LEVEL_2;
5702     }
5703 }
5704 
5705 /**
5706  * @brief map link keys to secure connection yes/no
5707  */
5708 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
5709     switch (link_key_type){
5710         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5711         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5712             return 1;
5713         default:
5714             return 0;
5715     }
5716 }
5717 
5718 /**
5719  * @brief map link keys to authenticated
5720  */
5721 int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
5722     switch (link_key_type){
5723         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
5724         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
5725             return 1;
5726         default:
5727             return 0;
5728     }
5729 }
5730 
5731 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
5732     log_info("gap_mitm_protection_required_for_security_level %u", level);
5733     return level > LEVEL_2;
5734 }
5735 
5736 /**
5737  * @brief get current security level
5738  */
5739 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
5740     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5741     if (!connection) return LEVEL_0;
5742     return gap_security_level_for_connection(connection);
5743 }
5744 
5745 /**
5746  * @brief request connection to device to
5747  * @result GAP_AUTHENTICATION_RESULT
5748  */
5749 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
5750     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5751     if (!connection){
5752         hci_emit_security_level(con_handle, LEVEL_0);
5753         return;
5754     }
5755 
5756     btstack_assert(hci_is_le_connection(connection) == false);
5757 
5758     // 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)
5759     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
5760     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
5761         requested_level = LEVEL_4;
5762     }
5763 
5764     gap_security_level_t current_level = gap_security_level(con_handle);
5765     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
5766         requested_level, connection->requested_security_level, current_level);
5767 
5768     // authentication active if authentication request was sent or planned level > 0
5769     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
5770     if (authentication_active){
5771         // authentication already active
5772         if (connection->requested_security_level < requested_level){
5773             // increase requested level as new level is higher
5774             // TODO: handle re-authentication when done
5775             connection->requested_security_level = requested_level;
5776         }
5777     } else {
5778         // no request active, notify if security sufficient
5779         if (requested_level <= current_level){
5780             hci_emit_security_level(con_handle, current_level);
5781             return;
5782         }
5783 
5784         // store request
5785         connection->requested_security_level = requested_level;
5786 
5787         // start to authenticate connection
5788         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
5789         hci_run();
5790     }
5791 }
5792 
5793 /**
5794  * @brief start dedicated bonding with device. disconnect after bonding
5795  * @param device
5796  * @param request MITM protection
5797  * @result GAP_DEDICATED_BONDING_COMPLETE
5798  */
5799 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
5800 
5801     // create connection state machine
5802     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
5803 
5804     if (!connection){
5805         return BTSTACK_MEMORY_ALLOC_FAILED;
5806     }
5807 
5808     // delete linkn key
5809     gap_drop_link_key_for_bd_addr(device);
5810 
5811     // configure LEVEL_2/3, dedicated bonding
5812     connection->state = SEND_CREATE_CONNECTION;
5813     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
5814     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
5815     connection->bonding_flags = BONDING_DEDICATED;
5816 
5817     // wait for GAP Security Result and send GAP Dedicated Bonding complete
5818 
5819     // handle: connnection failure (connection complete != ok)
5820     // handle: authentication failure
5821     // handle: disconnect on done
5822 
5823     hci_run();
5824 
5825     return 0;
5826 }
5827 
5828 void gap_set_local_name(const char * local_name){
5829     hci_stack->local_name = local_name;
5830     hci_stack->gap_tasks |= GAP_TASK_SET_LOCAL_NAME;
5831     // also update EIR if not set by user
5832     if (hci_stack->eir_data == NULL){
5833         hci_stack->gap_tasks |= GAP_TASK_SET_EIR_DATA;
5834     }
5835     hci_run();
5836 }
5837 #endif
5838 
5839 
5840 #ifdef ENABLE_BLE
5841 
5842 #ifdef ENABLE_LE_CENTRAL
5843 void gap_start_scan(void){
5844     hci_stack->le_scanning_enabled = true;
5845     hci_run();
5846 }
5847 
5848 void gap_stop_scan(void){
5849     hci_stack->le_scanning_enabled = false;
5850     hci_run();
5851 }
5852 
5853 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
5854     hci_stack->le_scan_type          = scan_type;
5855     hci_stack->le_scan_filter_policy = scanning_filter_policy;
5856     hci_stack->le_scan_interval      = scan_interval;
5857     hci_stack->le_scan_window        = scan_window;
5858     hci_stack->le_scanning_param_update = true;
5859     hci_run();
5860 }
5861 
5862 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
5863     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
5864 }
5865 
5866 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
5867     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
5868     if (!conn){
5869         // disallow if le connection is already outgoing
5870         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5871             log_error("le connection already active");
5872             return ERROR_CODE_COMMAND_DISALLOWED;
5873         }
5874 
5875         log_info("gap_connect: no connection exists yet, creating context");
5876         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
5877         if (!conn){
5878             // notify client that alloc failed
5879             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5880             log_info("gap_connect: failed to alloc hci_connection_t");
5881             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
5882         }
5883 
5884         // set le connecting state
5885         if (hci_is_le_connection_type(addr_type)){
5886             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
5887         }
5888 
5889         conn->state = SEND_CREATE_CONNECTION;
5890         log_info("gap_connect: send create connection next");
5891         hci_run();
5892         return ERROR_CODE_SUCCESS;
5893     }
5894 
5895     if (!hci_is_le_connection(conn) ||
5896         (conn->state == SEND_CREATE_CONNECTION) ||
5897         (conn->state == SENT_CREATE_CONNECTION)) {
5898         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
5899         log_error("gap_connect: classic connection or connect is already being created");
5900         return GATT_CLIENT_IN_WRONG_STATE;
5901     }
5902 
5903     // check if connection was just disconnected
5904     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5905         log_info("gap_connect: send create connection (again)");
5906         conn->state = SEND_CREATE_CONNECTION;
5907         hci_run();
5908         return ERROR_CODE_SUCCESS;
5909     }
5910 
5911     log_info("gap_connect: context exists with state %u", conn->state);
5912     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
5913     hci_run();
5914     return ERROR_CODE_SUCCESS;
5915 }
5916 
5917 // @assumption: only a single outgoing LE Connection exists
5918 static hci_connection_t * gap_get_outgoing_connection(void){
5919     btstack_linked_item_t *it;
5920     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
5921         hci_connection_t * conn = (hci_connection_t *) it;
5922         if (!hci_is_le_connection(conn)) continue;
5923         switch (conn->state){
5924             case SEND_CREATE_CONNECTION:
5925             case SENT_CREATE_CONNECTION:
5926             case SENT_CANCEL_CONNECTION:
5927                 return conn;
5928             default:
5929                 break;
5930         };
5931     }
5932     return NULL;
5933 }
5934 
5935 uint8_t gap_connect_cancel(void){
5936     hci_connection_t * conn = gap_get_outgoing_connection();
5937     if (!conn) return 0;
5938     switch (conn->state){
5939         case SEND_CREATE_CONNECTION:
5940             // skip sending create connection and emit event instead
5941             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
5942             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
5943             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
5944             btstack_memory_hci_connection_free( conn );
5945             break;
5946         case SENT_CREATE_CONNECTION:
5947             // request to send cancel connection
5948             conn->state = SEND_CANCEL_CONNECTION;
5949             hci_run();
5950             break;
5951         default:
5952             break;
5953     }
5954     return 0;
5955 }
5956 #endif
5957 
5958 #ifdef ENABLE_LE_CENTRAL
5959 /**
5960  * @brief Set connection parameters for outgoing connections
5961  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
5962  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
5963  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
5964  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
5965  * @param conn_latency, default: 4
5966  * @param supervision_timeout (unit: 10ms), default: 720 ms
5967  * @param min_ce_length (unit: 0.625ms), default: 10 ms
5968  * @param max_ce_length (unit: 0.625ms), default: 30 ms
5969  */
5970 
5971 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
5972     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
5973     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
5974     hci_stack->le_connection_scan_interval = conn_scan_interval;
5975     hci_stack->le_connection_scan_window = conn_scan_window;
5976     hci_stack->le_connection_interval_min = conn_interval_min;
5977     hci_stack->le_connection_interval_max = conn_interval_max;
5978     hci_stack->le_connection_latency = conn_latency;
5979     hci_stack->le_supervision_timeout = supervision_timeout;
5980     hci_stack->le_minimum_ce_length = min_ce_length;
5981     hci_stack->le_maximum_ce_length = max_ce_length;
5982 }
5983 #endif
5984 
5985 /**
5986  * @brief Updates the connection parameters for a given LE connection
5987  * @param handle
5988  * @param conn_interval_min (unit: 1.25ms)
5989  * @param conn_interval_max (unit: 1.25ms)
5990  * @param conn_latency
5991  * @param supervision_timeout (unit: 10ms)
5992  * @returns 0 if ok
5993  */
5994 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5995     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5996     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5997     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5998     connection->le_conn_interval_min = conn_interval_min;
5999     connection->le_conn_interval_max = conn_interval_max;
6000     connection->le_conn_latency = conn_latency;
6001     connection->le_supervision_timeout = supervision_timeout;
6002     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
6003     hci_run();
6004     return 0;
6005 }
6006 
6007 /**
6008  * @brief Request an update of the connection parameter for a given LE connection
6009  * @param handle
6010  * @param conn_interval_min (unit: 1.25ms)
6011  * @param conn_interval_max (unit: 1.25ms)
6012  * @param conn_latency
6013  * @param supervision_timeout (unit: 10ms)
6014  * @returns 0 if ok
6015  */
6016 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
6017     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
6018     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6019     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6020     connection->le_conn_interval_min = conn_interval_min;
6021     connection->le_conn_interval_max = conn_interval_max;
6022     connection->le_conn_latency = conn_latency;
6023     connection->le_supervision_timeout = supervision_timeout;
6024     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
6025     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
6026     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
6027     return 0;
6028 }
6029 
6030 #ifdef ENABLE_LE_PERIPHERAL
6031 
6032 /**
6033  * @brief Set Advertisement Data
6034  * @param advertising_data_length
6035  * @param advertising_data (max 31 octets)
6036  * @note data is not copied, pointer has to stay valid
6037  */
6038 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
6039     hci_stack->le_advertisements_data_len = advertising_data_length;
6040     hci_stack->le_advertisements_data = advertising_data;
6041     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6042     hci_run();
6043 }
6044 
6045 /**
6046  * @brief Set Scan Response Data
6047  * @param advertising_data_length
6048  * @param advertising_data (max 31 octets)
6049  * @note data is not copied, pointer has to stay valid
6050  */
6051 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
6052     hci_stack->le_scan_response_data_len = scan_response_data_length;
6053     hci_stack->le_scan_response_data = scan_response_data;
6054     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6055     hci_run();
6056 }
6057 
6058 /**
6059  * @brief Set Advertisement Parameters
6060  * @param adv_int_min
6061  * @param adv_int_max
6062  * @param adv_type
6063  * @param direct_address_type
6064  * @param direct_address
6065  * @param channel_map
6066  * @param filter_policy
6067  *
6068  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
6069  */
6070  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
6071     uint8_t direct_address_typ, bd_addr_t direct_address,
6072     uint8_t channel_map, uint8_t filter_policy) {
6073 
6074     hci_stack->le_advertisements_interval_min = adv_int_min;
6075     hci_stack->le_advertisements_interval_max = adv_int_max;
6076     hci_stack->le_advertisements_type = adv_type;
6077     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
6078     hci_stack->le_advertisements_channel_map = channel_map;
6079     hci_stack->le_advertisements_filter_policy = filter_policy;
6080     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
6081                  6);
6082 
6083     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS | LE_ADVERTISEMENT_TASKS_PARAMS_SET;
6084     hci_run();
6085  }
6086 
6087 /**
6088  * @brief Enable/Disable Advertisements
6089  * @param enabled
6090  */
6091 void gap_advertisements_enable(int enabled){
6092     hci_stack->le_advertisements_enabled = enabled != 0;
6093     hci_update_advertisements_enabled_for_current_roles();
6094     hci_run();
6095 }
6096 
6097 #endif
6098 
6099 void hci_le_set_own_address_type(uint8_t own_address_type){
6100     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
6101     if (own_address_type == hci_stack->le_own_addr_type) return;
6102     hci_stack->le_own_addr_type = own_address_type;
6103 
6104 #ifdef ENABLE_LE_PERIPHERAL
6105     // update advertisement parameters, too
6106     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6107     hci_run();
6108 #endif
6109 #ifdef ENABLE_LE_CENTRAL
6110     // note: we don't update scan parameters or modify ongoing connection attempts
6111 #endif
6112 }
6113 
6114 #endif
6115 
6116 uint8_t gap_disconnect(hci_con_handle_t handle){
6117     hci_connection_t * conn = hci_connection_for_handle(handle);
6118     if (!conn){
6119         hci_emit_disconnection_complete(handle, 0);
6120         return 0;
6121     }
6122     // ignore if already disconnected
6123     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
6124         return 0;
6125     }
6126     conn->state = SEND_DISCONNECT;
6127     hci_run();
6128     return 0;
6129 }
6130 
6131 int gap_read_rssi(hci_con_handle_t con_handle){
6132     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6133     if (hci_connection == NULL) return 0;
6134     connectionSetAuthenticationFlags(hci_connection, AUTH_FLAG_READ_RSSI);
6135     hci_run();
6136     return 1;
6137 }
6138 
6139 /**
6140  * @brief Get connection type
6141  * @param con_handle
6142  * @result connection_type
6143  */
6144 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
6145     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6146     if (!conn) return GAP_CONNECTION_INVALID;
6147     switch (conn->address_type){
6148         case BD_ADDR_TYPE_LE_PUBLIC:
6149         case BD_ADDR_TYPE_LE_RANDOM:
6150             return GAP_CONNECTION_LE;
6151         case BD_ADDR_TYPE_SCO:
6152             return GAP_CONNECTION_SCO;
6153         case BD_ADDR_TYPE_ACL:
6154             return GAP_CONNECTION_ACL;
6155         default:
6156             return GAP_CONNECTION_INVALID;
6157     }
6158 }
6159 
6160 hci_role_t gap_get_role(hci_con_handle_t connection_handle){
6161     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
6162     if (!conn) return HCI_ROLE_INVALID;
6163     return (hci_role_t) conn->role;
6164 }
6165 
6166 
6167 #ifdef ENABLE_CLASSIC
6168 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
6169     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6170     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6171     conn->request_role = role;
6172     hci_run();
6173     return ERROR_CODE_SUCCESS;
6174 }
6175 #endif
6176 
6177 #ifdef ENABLE_BLE
6178 
6179 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){
6180     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6181     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6182 
6183     conn->le_phy_update_all_phys    = all_phys;
6184     conn->le_phy_update_tx_phys     = tx_phys;
6185     conn->le_phy_update_rx_phys     = rx_phys;
6186     conn->le_phy_update_phy_options = phy_options;
6187 
6188     hci_run();
6189 
6190     return 0;
6191 }
6192 
6193 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6194     // check if already in list
6195     btstack_linked_list_iterator_t it;
6196     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6197     while (btstack_linked_list_iterator_has_next(&it)) {
6198         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
6199         if (entry->address_type != address_type) {
6200             continue;
6201         }
6202         if (memcmp(entry->address, address, 6) != 0) {
6203             continue;
6204         }
6205 		// disallow if already scheduled to add
6206 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
6207 			return ERROR_CODE_COMMAND_DISALLOWED;
6208 		}
6209 		// still on controller, but scheduled to remove -> re-add
6210 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
6211 		return ERROR_CODE_SUCCESS;
6212     }
6213     // alloc and add to list
6214     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
6215     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
6216     entry->address_type = address_type;
6217     (void)memcpy(entry->address, address, 6);
6218     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
6219     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
6220     return ERROR_CODE_SUCCESS;
6221 }
6222 
6223 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6224     btstack_linked_list_iterator_t it;
6225     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6226     while (btstack_linked_list_iterator_has_next(&it)){
6227         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6228         if (entry->address_type != address_type) {
6229             continue;
6230         }
6231         if (memcmp(entry->address, address, 6) != 0) {
6232             continue;
6233         }
6234         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6235             // remove from controller if already present
6236             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6237         }  else {
6238             // directly remove entry from whitelist
6239             btstack_linked_list_iterator_remove(&it);
6240             btstack_memory_whitelist_entry_free(entry);
6241         }
6242         return ERROR_CODE_SUCCESS;
6243     }
6244     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6245 }
6246 
6247 static void hci_whitelist_clear(void){
6248     btstack_linked_list_iterator_t it;
6249     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
6250     while (btstack_linked_list_iterator_has_next(&it)){
6251         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
6252         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
6253             // remove from controller if already present
6254             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6255             continue;
6256         }
6257         // directly remove entry from whitelist
6258         btstack_linked_list_iterator_remove(&it);
6259         btstack_memory_whitelist_entry_free(entry);
6260     }
6261 }
6262 
6263 /**
6264  * @brief Clear Whitelist
6265  * @returns 0 if ok
6266  */
6267 uint8_t gap_whitelist_clear(void){
6268     hci_whitelist_clear();
6269     hci_run();
6270     return ERROR_CODE_SUCCESS;
6271 }
6272 
6273 /**
6274  * @brief Add Device to Whitelist
6275  * @param address_typ
6276  * @param address
6277  * @returns 0 if ok
6278  */
6279 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6280     uint8_t status = hci_whitelist_add(address_type, address);
6281     if (status){
6282         return status;
6283     }
6284     hci_run();
6285     return ERROR_CODE_SUCCESS;
6286 }
6287 
6288 /**
6289  * @brief Remove Device from Whitelist
6290  * @param address_typ
6291  * @param address
6292  * @returns 0 if ok
6293  */
6294 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6295     uint8_t status = hci_whitelist_remove(address_type, address);
6296     if (status){
6297         return status;
6298     }
6299     hci_run();
6300     return ERROR_CODE_SUCCESS;
6301 }
6302 
6303 #ifdef ENABLE_LE_CENTRAL
6304 /**
6305  *  @brief Connect with Whitelist
6306  *  @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
6307  *  @returns - if ok
6308  */
6309 uint8_t gap_connect_with_whitelist(void){
6310     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
6311         return ERROR_CODE_COMMAND_DISALLOWED;
6312     }
6313     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6314     hci_run();
6315     return ERROR_CODE_SUCCESS;
6316 }
6317 
6318 /**
6319  * @brief Auto Connection Establishment - Start Connecting to device
6320  * @param address_typ
6321  * @param address
6322  * @returns 0 if ok
6323  */
6324 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
6325     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6326         return ERROR_CODE_COMMAND_DISALLOWED;
6327     }
6328 
6329     uint8_t status = hci_whitelist_add(address_type, address);
6330     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
6331         return status;
6332     }
6333 
6334     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6335 
6336     hci_run();
6337     return ERROR_CODE_SUCCESS;
6338 }
6339 
6340 /**
6341  * @brief Auto Connection Establishment - Stop Connecting to device
6342  * @param address_typ
6343  * @param address
6344  * @returns 0 if ok
6345  */
6346 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
6347     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6348         return ERROR_CODE_COMMAND_DISALLOWED;
6349     }
6350 
6351     hci_whitelist_remove(address_type, address);
6352     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
6353         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6354     }
6355     hci_run();
6356     return 0;
6357 }
6358 
6359 /**
6360  * @brief Auto Connection Establishment - Stop everything
6361  * @note  Convenience function to stop all active auto connection attempts
6362  */
6363 uint8_t gap_auto_connection_stop_all(void){
6364     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
6365         return ERROR_CODE_COMMAND_DISALLOWED;
6366     }
6367     hci_whitelist_clear();
6368     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6369     hci_run();
6370     return ERROR_CODE_SUCCESS;
6371 }
6372 
6373 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
6374     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6375     if (!conn) return 0;
6376     return conn->le_connection_interval;
6377 }
6378 #endif
6379 #endif
6380 
6381 #ifdef ENABLE_CLASSIC
6382 /**
6383  * @brief Set Extended Inquiry Response data
6384  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
6385  * @note has to be done before stack starts up
6386  */
6387 void gap_set_extended_inquiry_response(const uint8_t * data){
6388     hci_stack->eir_data = data;
6389     hci_stack->gap_tasks |= GAP_TASK_SET_EIR_DATA;
6390     hci_run();
6391 }
6392 
6393 /**
6394  * @brief Start GAP Classic Inquiry
6395  * @param duration in 1.28s units
6396  * @return 0 if ok
6397  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
6398  */
6399 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
6400     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
6401     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6402     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
6403         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
6404     }
6405     hci_stack->inquiry_state = duration_in_1280ms_units;
6406     hci_run();
6407     return 0;
6408 }
6409 
6410 /**
6411  * @brief Stop GAP Classic Inquiry
6412  * @returns 0 if ok
6413  */
6414 int gap_inquiry_stop(void){
6415     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
6416         // emit inquiry complete event, before it even started
6417         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
6418         hci_emit_event(event, sizeof(event), 1);
6419         return 0;
6420     }
6421     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
6422     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
6423     hci_run();
6424     return 0;
6425 }
6426 
6427 void gap_inquiry_set_lap(uint32_t lap){
6428     hci_stack->inquiry_lap = lap;
6429 }
6430 
6431 
6432 /**
6433  * @brief Remote Name Request
6434  * @param addr
6435  * @param page_scan_repetition_mode
6436  * @param clock_offset only used when bit 15 is set
6437  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
6438  */
6439 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
6440     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6441     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
6442     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
6443     hci_stack->remote_name_clock_offset = clock_offset;
6444     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
6445     hci_run();
6446     return 0;
6447 }
6448 
6449 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
6450     hci_stack->gap_pairing_state = state;
6451     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
6452     hci_run();
6453     return 0;
6454 }
6455 
6456 /**
6457  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
6458  * @param addr
6459  * @param pin_data
6460  * @param pin_len
6461  * @return 0 if ok
6462  */
6463 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
6464     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6465     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
6466     hci_stack->gap_pairing_pin_len = pin_len;
6467     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
6468 }
6469 
6470 /**
6471  * @brief Legacy Pairing Pin Code Response
6472  * @param addr
6473  * @param pin
6474  * @return 0 if ok
6475  */
6476 int gap_pin_code_response(const bd_addr_t addr, const char * pin){
6477     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
6478 }
6479 
6480 /**
6481  * @brief Abort Legacy Pairing
6482  * @param addr
6483  * @param pin
6484  * @return 0 if ok
6485  */
6486 int gap_pin_code_negative(bd_addr_t addr){
6487     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6488     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
6489 }
6490 
6491 /**
6492  * @brief SSP Passkey Response
6493  * @param addr
6494  * @param passkey
6495  * @return 0 if ok
6496  */
6497 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
6498     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6499     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
6500     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
6501 }
6502 
6503 /**
6504  * @brief Abort SSP Passkey Entry/Pairing
6505  * @param addr
6506  * @param pin
6507  * @return 0 if ok
6508  */
6509 int gap_ssp_passkey_negative(const bd_addr_t addr){
6510     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6511     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
6512 }
6513 
6514 /**
6515  * @brief Accept SSP Numeric Comparison
6516  * @param addr
6517  * @param passkey
6518  * @return 0 if ok
6519  */
6520 int gap_ssp_confirmation_response(const bd_addr_t addr){
6521     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6522     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
6523 }
6524 
6525 /**
6526  * @brief Abort SSP Numeric Comparison/Pairing
6527  * @param addr
6528  * @param pin
6529  * @return 0 if ok
6530  */
6531 int gap_ssp_confirmation_negative(const bd_addr_t addr){
6532     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6533     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
6534 }
6535 
6536 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
6537 
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 
6546 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
6547     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6548 }
6549 
6550 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
6551     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
6552 }
6553 #endif
6554 
6555 #ifdef ENABLE_CLASSIC_PAIRING_OOB
6556 /**
6557  * @brief Report Remote OOB Data
6558  * @param bd_addr
6559  * @param c_192 Simple Pairing Hash C derived from P-192 public key
6560  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
6561  * @param c_256 Simple Pairing Hash C derived from P-256 public key
6562  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
6563  */
6564 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){
6565     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6566     if (connection == NULL) {
6567         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
6568     }
6569     connection->classic_oob_c_192 = c_192;
6570     connection->classic_oob_r_192 = r_192;
6571 
6572     // ignore P-256 if not supported by us
6573     if (hci_stack->secure_connections_active){
6574         connection->classic_oob_c_256 = c_256;
6575         connection->classic_oob_r_256 = r_256;
6576     }
6577 
6578     return ERROR_CODE_SUCCESS;
6579 }
6580 /**
6581  * @brief Generate new OOB data
6582  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
6583  */
6584 void gap_ssp_generate_oob_data(void){
6585     hci_stack->classic_read_local_oob_data = true;
6586     hci_run();
6587 }
6588 
6589 #endif
6590 
6591 /**
6592  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
6593  * @param inquiry_mode see bluetooth_defines.h
6594  */
6595 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
6596     hci_stack->inquiry_mode = inquiry_mode;
6597 }
6598 
6599 /**
6600  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
6601  */
6602 void hci_set_sco_voice_setting(uint16_t voice_setting){
6603     hci_stack->sco_voice_setting = voice_setting;
6604 }
6605 
6606 /**
6607  * @brief Get SCO Voice Setting
6608  * @return current voice setting
6609  */
6610 uint16_t hci_get_sco_voice_setting(void){
6611     return hci_stack->sco_voice_setting;
6612 }
6613 
6614 static int hci_have_usb_transport(void){
6615     if (!hci_stack->hci_transport) return 0;
6616     const char * transport_name = hci_stack->hci_transport->name;
6617     if (!transport_name) return 0;
6618     return (transport_name[0] == 'H') && (transport_name[1] == '2');
6619 }
6620 
6621 /** @brief Get SCO packet length for current SCO Voice setting
6622  *  @note  Using SCO packets of the exact length is required for USB transfer
6623  *  @return Length of SCO packets in bytes (not audio frames)
6624  */
6625 uint16_t hci_get_sco_packet_length(void){
6626     uint16_t sco_packet_length = 0;
6627 
6628 #ifdef ENABLE_SCO_OVER_HCI
6629     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6630     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6631 
6632     if (hci_have_usb_transport()){
6633         // see Core Spec for H2 USB Transfer.
6634         // 3 byte SCO header + 24 bytes per connection
6635         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
6636         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
6637     } else {
6638         // 3 byte SCO header + SCO packet size over the air (60 bytes)
6639         sco_packet_length = 3 + 60 * multiplier;
6640         // assert that it still fits inside an SCO buffer
6641         if (sco_packet_length > hci_stack->sco_data_packet_length){
6642             sco_packet_length = 3 + 60;
6643         }
6644     }
6645 #endif
6646 
6647 #ifdef HAVE_SCO_TRANSPORT
6648     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
6649     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6650     sco_packet_length = 3 + 60 * multiplier;
6651 #endif
6652     return sco_packet_length;
6653 }
6654 
6655 /**
6656 * @brief Sets the master/slave policy
6657 * @param policy (0: attempt to become master, 1: let connecting device decide)
6658 */
6659 void hci_set_master_slave_policy(uint8_t policy){
6660     hci_stack->master_slave_policy = policy;
6661 }
6662 
6663 #endif
6664 
6665 HCI_STATE hci_get_state(void){
6666     return hci_stack->state;
6667 }
6668 
6669 #ifdef ENABLE_CLASSIC
6670 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
6671     hci_stack->gap_classic_accept_callback = accept_callback;
6672 }
6673 #endif
6674 
6675 /**
6676  * @brief Set callback for Bluetooth Hardware Error
6677  */
6678 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
6679     hci_stack->hardware_error_callback = fn;
6680 }
6681 
6682 void hci_disconnect_all(void){
6683     btstack_linked_list_iterator_t it;
6684     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6685     while (btstack_linked_list_iterator_has_next(&it)){
6686         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6687         if (con->state == SENT_DISCONNECT) continue;
6688         con->state = SEND_DISCONNECT;
6689     }
6690     hci_run();
6691 }
6692 
6693 uint16_t hci_get_manufacturer(void){
6694     return hci_stack->manufacturer;
6695 }
6696 
6697 #ifdef ENABLE_BLE
6698 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
6699     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
6700     if (!hci_con) return NULL;
6701     return &hci_con->sm_connection;
6702 }
6703 
6704 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
6705 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
6706 #endif
6707 
6708 int gap_encryption_key_size(hci_con_handle_t con_handle){
6709     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6710     if (hci_connection == NULL) return 0;
6711     if (hci_is_le_connection(hci_connection)){
6712 #ifdef ENABLE_BLE
6713         sm_connection_t * sm_conn = &hci_connection->sm_connection;
6714         if (sm_conn->sm_connection_encrypted) {
6715             return sm_conn->sm_actual_encryption_key_size;
6716         }
6717 #endif
6718     } else {
6719 #ifdef ENABLE_CLASSIC
6720         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
6721             return hci_connection->encryption_key_size;
6722         }
6723 #endif
6724     }
6725     return 0;
6726 }
6727 
6728 int gap_authenticated(hci_con_handle_t con_handle){
6729     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6730     if (hci_connection == NULL) return 0;
6731 
6732     switch (hci_connection->address_type){
6733 #ifdef ENABLE_BLE
6734         case BD_ADDR_TYPE_LE_PUBLIC:
6735         case BD_ADDR_TYPE_LE_RANDOM:
6736             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6737             return hci_connection->sm_connection.sm_connection_authenticated;
6738 #endif
6739 #ifdef ENABLE_CLASSIC
6740         case BD_ADDR_TYPE_SCO:
6741         case BD_ADDR_TYPE_ACL:
6742             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
6743 #endif
6744         default:
6745             return 0;
6746     }
6747 }
6748 
6749 int gap_secure_connection(hci_con_handle_t con_handle){
6750     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6751     if (hci_connection == NULL) return 0;
6752 
6753     switch (hci_connection->address_type){
6754 #ifdef ENABLE_BLE
6755         case BD_ADDR_TYPE_LE_PUBLIC:
6756         case BD_ADDR_TYPE_LE_RANDOM:
6757             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6758             return hci_connection->sm_connection.sm_connection_sc;
6759 #endif
6760 #ifdef ENABLE_CLASSIC
6761         case BD_ADDR_TYPE_SCO:
6762         case BD_ADDR_TYPE_ACL:
6763             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
6764 #endif
6765         default:
6766             return 0;
6767     }
6768 }
6769 
6770 bool gap_bonded(hci_con_handle_t con_handle){
6771 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6772 	if (hci_connection == NULL) return 0;
6773 
6774 #ifdef ENABLE_CLASSIC
6775 	link_key_t link_key;
6776 	link_key_type_t link_key_type;
6777 #endif
6778 	switch (hci_connection->address_type){
6779 #ifdef ENABLE_BLE
6780 		case BD_ADDR_TYPE_LE_PUBLIC:
6781 		case BD_ADDR_TYPE_LE_RANDOM:
6782 			return hci_connection->sm_connection.sm_le_db_index >= 0;
6783 #endif
6784 #ifdef ENABLE_CLASSIC
6785 		case BD_ADDR_TYPE_SCO:
6786 		case BD_ADDR_TYPE_ACL:
6787 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
6788 #endif
6789 		default:
6790 			return false;
6791 	}
6792 }
6793 
6794 #ifdef ENABLE_BLE
6795 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
6796     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
6797     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
6798     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
6799     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
6800     return sm_conn->sm_connection_authorization_state;
6801 }
6802 #endif
6803 
6804 #ifdef ENABLE_CLASSIC
6805 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){
6806     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6807     if (!conn) return GAP_CONNECTION_INVALID;
6808     conn->sniff_min_interval = sniff_min_interval;
6809     conn->sniff_max_interval = sniff_max_interval;
6810     conn->sniff_attempt = sniff_attempt;
6811     conn->sniff_timeout = sniff_timeout;
6812     hci_run();
6813     return 0;
6814 }
6815 
6816 /**
6817  * @brief Exit Sniff mode
6818  * @param con_handle
6819  @ @return 0 if ok
6820  */
6821 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
6822     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6823     if (!conn) return GAP_CONNECTION_INVALID;
6824     conn->sniff_min_interval = 0xffff;
6825     hci_run();
6826     return 0;
6827 }
6828 
6829 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){
6830     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6831     if (!conn) return GAP_CONNECTION_INVALID;
6832     conn->sniff_subrating_max_latency = max_latency;
6833     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
6834     conn->sniff_subrating_min_local_timeout = min_local_timeout;
6835     hci_run();
6836     return ERROR_CODE_SUCCESS;
6837 }
6838 
6839 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){
6840     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6841     if (!conn) return GAP_CONNECTION_INVALID;
6842     conn->qos_service_type = service_type;
6843     conn->qos_token_rate = token_rate;
6844     conn->qos_peak_bandwidth = peak_bandwidth;
6845     conn->qos_latency = latency;
6846     conn->qos_delay_variation = delay_variation;
6847     hci_run();
6848     return ERROR_CODE_SUCCESS;
6849 }
6850 
6851 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
6852     hci_stack->new_page_scan_interval = page_scan_interval;
6853     hci_stack->new_page_scan_window = page_scan_window;
6854     hci_run();
6855 }
6856 
6857 void gap_set_page_scan_type(page_scan_type_t page_scan_type){
6858     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
6859     hci_run();
6860 }
6861 
6862 #endif
6863 
6864 void hci_halting_defer(void){
6865     if (hci_stack->state != HCI_STATE_HALTING) return;
6866     switch (hci_stack->substate){
6867         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
6868         case HCI_HALTING_CLOSE:
6869             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
6870             break;
6871         default:
6872             break;
6873     }
6874 }
6875 
6876 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
6877 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
6878     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6879     if (le_device_db_index >= le_device_db_max_count()) return;
6880     uint8_t offset = le_device_db_index >> 3;
6881     uint8_t mask = 1 << (le_device_db_index & 7);
6882     hci_stack->le_resolving_list_add_entries[offset] |= mask;
6883     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6884     	// note: go back to remove entries, otherwise, a remove + add will skip the add
6885         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6886     }
6887 }
6888 
6889 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
6890 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
6891 	if (le_device_db_index >= le_device_db_max_count()) return;
6892 	uint8_t offset = le_device_db_index >> 3;
6893 	uint8_t mask = 1 << (le_device_db_index & 7);
6894 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
6895 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
6896 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
6897 	}
6898 }
6899 
6900 uint8_t gap_load_resolving_list_from_le_device_db(void){
6901 	if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) {
6902 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
6903 	}
6904 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
6905 		// restart le resolving list update
6906 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6907 	}
6908 	return ERROR_CODE_SUCCESS;
6909 }
6910 #endif
6911 
6912 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
6913 void hci_setup_test_connections_fuzz(void){
6914     hci_connection_t * conn;
6915 
6916     // default address: 66:55:44:33:00:01
6917     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
6918 
6919     // setup Controller info
6920     hci_stack->num_cmd_packets = 255;
6921     hci_stack->acl_packets_total_num = 255;
6922 
6923     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
6924     addr[5] = 0x01;
6925     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6926     conn->con_handle = addr[5];
6927     conn->role  = HCI_ROLE_SLAVE;
6928     conn->state = RECEIVED_CONNECTION_REQUEST;
6929     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6930 
6931     // setup incoming Classic SCO connection with con handle 0x0002
6932     addr[5] = 0x02;
6933     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
6934     conn->con_handle = addr[5];
6935     conn->role  = HCI_ROLE_SLAVE;
6936     conn->state = RECEIVED_CONNECTION_REQUEST;
6937     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6938 
6939     // setup ready Classic ACL connection with con handle 0x0003
6940     addr[5] = 0x03;
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 = OPEN;
6945     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6946 
6947     // setup ready Classic SCO connection with con handle 0x0004
6948     addr[5] = 0x04;
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 = OPEN;
6953     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
6954 
6955     // setup ready LE ACL connection with con handle 0x005 and public address
6956     addr[5] = 0x05;
6957     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
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     conn->sm_connection.sm_connection_encrypted = 1;
6963 }
6964 
6965 void hci_free_connections_fuzz(void){
6966     btstack_linked_list_iterator_t it;
6967     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6968     while (btstack_linked_list_iterator_has_next(&it)){
6969         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6970         btstack_linked_list_iterator_remove(&it);
6971         btstack_memory_hci_connection_free(con);
6972     }
6973 }
6974 void hci_simulate_working_fuzz(void){
6975     hci_init_done();
6976     hci_stack->num_cmd_packets = 255;
6977 }
6978 #endif
6979