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