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