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