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