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