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